1 /*
   2  * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "asm/codeBuffer.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "jvmci/jvmciRuntime.hpp"
  31 #include "jvmci/jvmciCompilerToVM.hpp"
  32 #include "jvmci/jvmciCompiler.hpp"
  33 #include "jvmci/jvmciJavaClasses.hpp"
  34 #include "jvmci/jvmciEnv.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "oops/objArrayOop.inline.hpp"
  39 #include "prims/jvm.h"
  40 #include "runtime/biasedLocking.hpp"
  41 #include "runtime/interfaceSupport.hpp"
  42 #include "runtime/reflection.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "utilities/debug.hpp"
  45 #include "utilities/defaultStream.hpp"
  46 
  47 #if defined(_MSC_VER)
  48 #define strtoll _strtoi64
  49 #endif
  50 
  51 jobject JVMCIRuntime::_HotSpotJVMCIRuntime_instance = NULL;
  52 bool JVMCIRuntime::_HotSpotJVMCIRuntime_initialized = false;
  53 bool JVMCIRuntime::_well_known_classes_initialized = false;
  54 const char* JVMCIRuntime::_compiler = NULL;
  55 int JVMCIRuntime::_options_count = 0;
  56 SystemProperty** JVMCIRuntime::_options = NULL;
  57 int JVMCIRuntime::_trivial_prefixes_count = 0;
  58 char** JVMCIRuntime::_trivial_prefixes = NULL;
  59 bool JVMCIRuntime::_shutdown_called = false;
  60 
  61 static const char* OPTION_PREFIX = "jvmci.option.";
  62 static const size_t OPTION_PREFIX_LEN = strlen(OPTION_PREFIX);
  63 
  64 BasicType JVMCIRuntime::kindToBasicType(Handle kind, TRAPS) {
  65   if (kind.is_null()) {
  66     THROW_(vmSymbols::java_lang_NullPointerException(), T_ILLEGAL);
  67   }
  68   jchar ch = JavaKind::typeChar(kind);
  69   switch(ch) {
  70     case 'z': return T_BOOLEAN;
  71     case 'b': return T_BYTE;
  72     case 's': return T_SHORT;
  73     case 'c': return T_CHAR;
  74     case 'i': return T_INT;
  75     case 'f': return T_FLOAT;
  76     case 'j': return T_LONG;
  77     case 'd': return T_DOUBLE;
  78     case 'a': return T_OBJECT;
  79     case '-': return T_ILLEGAL;
  80     default:
  81       JVMCI_ERROR_(T_ILLEGAL, "unexpected Kind: %c", ch);
  82   }
  83 }
  84 
  85 // Simple helper to see if the caller of a runtime stub which
  86 // entered the VM has been deoptimized
  87 
  88 static bool caller_is_deopted() {
  89   JavaThread* thread = JavaThread::current();
  90   RegisterMap reg_map(thread, false);
  91   frame runtime_frame = thread->last_frame();
  92   frame caller_frame = runtime_frame.sender(&reg_map);
  93   assert(caller_frame.is_compiled_frame(), "must be compiled");
  94   return caller_frame.is_deoptimized_frame();
  95 }
  96 
  97 // Stress deoptimization
  98 static void deopt_caller() {
  99   if ( !caller_is_deopted()) {
 100     JavaThread* thread = JavaThread::current();
 101     RegisterMap reg_map(thread, false);
 102     frame runtime_frame = thread->last_frame();
 103     frame caller_frame = runtime_frame.sender(&reg_map);
 104     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
 105     assert(caller_is_deopted(), "Must be deoptimized");
 106   }
 107 }
 108 
 109 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance(JavaThread* thread, Klass* klass))
 110   JRT_BLOCK;
 111   assert(klass->is_klass(), "not a class");
 112   instanceKlassHandle h(thread, klass);
 113   h->check_valid_for_instantiation(true, CHECK);
 114   // make sure klass is initialized
 115   h->initialize(CHECK);
 116   // allocate instance and return via TLS
 117   oop obj = h->allocate_instance(CHECK);
 118   thread->set_vm_result(obj);
 119   JRT_BLOCK_END;
 120 
 121   if (ReduceInitialCardMarks) {
 122     new_store_pre_barrier(thread);
 123   }
 124 JRT_END
 125 
 126 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length))
 127   JRT_BLOCK;
 128   // Note: no handle for klass needed since they are not used
 129   //       anymore after new_objArray() and no GC can happen before.
 130   //       (This may have to change if this code changes!)
 131   assert(array_klass->is_klass(), "not a class");
 132   oop obj;
 133   if (array_klass->is_typeArray_klass()) {
 134     BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
 135     obj = oopFactory::new_typeArray(elt_type, length, CHECK);
 136   } else {
 137     Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
 138     obj = oopFactory::new_objArray(elem_klass, length, CHECK);
 139   }
 140   thread->set_vm_result(obj);
 141   // This is pretty rare but this runtime patch is stressful to deoptimization
 142   // if we deoptimize here so force a deopt to stress the path.
 143   if (DeoptimizeALot) {
 144     static int deopts = 0;
 145     // Alternate between deoptimizing and raising an error (which will also cause a deopt)
 146     if (deopts++ % 2 == 0) {
 147       ResourceMark rm(THREAD);
 148       THROW(vmSymbols::java_lang_OutOfMemoryError());
 149     } else {
 150       deopt_caller();
 151     }
 152   }
 153   JRT_BLOCK_END;
 154 
 155   if (ReduceInitialCardMarks) {
 156     new_store_pre_barrier(thread);
 157   }
 158 JRT_END
 159 
 160 void JVMCIRuntime::new_store_pre_barrier(JavaThread* thread) {
 161   // After any safepoint, just before going back to compiled code,
 162   // we inform the GC that we will be doing initializing writes to
 163   // this object in the future without emitting card-marks, so
 164   // GC may take any compensating steps.
 165   // NOTE: Keep this code consistent with GraphKit::store_barrier.
 166 
 167   oop new_obj = thread->vm_result();
 168   if (new_obj == NULL)  return;
 169 
 170   assert(Universe::heap()->can_elide_tlab_store_barriers(),
 171          "compiler must check this first");
 172   // GC may decide to give back a safer copy of new_obj.
 173   new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj);
 174   thread->set_vm_result(new_obj);
 175 }
 176 
 177 JRT_ENTRY(void, JVMCIRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims))
 178   assert(klass->is_klass(), "not a class");
 179   assert(rank >= 1, "rank must be nonzero");
 180   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
 181   thread->set_vm_result(obj);
 182 JRT_END
 183 
 184 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length))
 185   oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
 186   thread->set_vm_result(obj);
 187 JRT_END
 188 
 189 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror))
 190   instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(type_mirror));
 191 
 192   if (klass == NULL) {
 193     ResourceMark rm(THREAD);
 194     THROW(vmSymbols::java_lang_InstantiationException());
 195   }
 196 
 197   // Create new instance (the receiver)
 198   klass->check_valid_for_instantiation(false, CHECK);
 199 
 200   // Make sure klass gets initialized
 201   klass->initialize(CHECK);
 202 
 203   oop obj = klass->allocate_instance(CHECK);
 204   thread->set_vm_result(obj);
 205 JRT_END
 206 
 207 extern void vm_exit(int code);
 208 
 209 // Enter this method from compiled code handler below. This is where we transition
 210 // to VM mode. This is done as a helper routine so that the method called directly
 211 // from compiled code does not have to transition to VM. This allows the entry
 212 // method to see if the nmethod that we have just looked up a handler for has
 213 // been deoptimized while we were in the vm. This simplifies the assembly code
 214 // cpu directories.
 215 //
 216 // We are entering here from exception stub (via the entry method below)
 217 // If there is a compiled exception handler in this method, we will continue there;
 218 // otherwise we will unwind the stack and continue at the caller of top frame method
 219 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
 220 // control the area where we can allow a safepoint. After we exit the safepoint area we can
 221 // check to see if the handler we are going to return is now in a nmethod that has
 222 // been deoptimized. If that is the case we return the deopt blob
 223 // unpack_with_exception entry instead. This makes life for the exception blob easier
 224 // because making that same check and diverting is painful from assembly language.
 225 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm))
 226   // Reset method handle flag.
 227   thread->set_is_method_handle_return(false);
 228 
 229   Handle exception(thread, ex);
 230   nm = CodeCache::find_nmethod(pc);
 231   assert(nm != NULL, "this is not a compiled method");
 232   // Adjust the pc as needed/
 233   if (nm->is_deopt_pc(pc)) {
 234     RegisterMap map(thread, false);
 235     frame exception_frame = thread->last_frame().sender(&map);
 236     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 237     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 238     pc = exception_frame.pc();
 239   }
 240 #ifdef ASSERT
 241   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
 242   assert(exception->is_oop(), "just checking");
 243   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 244   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
 245     if (ExitVMOnVerifyError) vm_exit(-1);
 246     ShouldNotReachHere();
 247   }
 248 #endif
 249 
 250   // Check the stack guard pages and reenable them if necessary and there is
 251   // enough space on the stack to do so.  Use fast exceptions only if the guard
 252   // pages are enabled.
 253   bool guard_pages_enabled = thread->stack_guards_enabled();
 254   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
 255 
 256   if (JvmtiExport::can_post_on_exceptions()) {
 257     // To ensure correct notification of exception catches and throws
 258     // we have to deoptimize here.  If we attempted to notify the
 259     // catches and throws during this exception lookup it's possible
 260     // we could deoptimize on the way out of the VM and end back in
 261     // the interpreter at the throw site.  This would result in double
 262     // notifications since the interpreter would also notify about
 263     // these same catches and throws as it unwound the frame.
 264 
 265     RegisterMap reg_map(thread);
 266     frame stub_frame = thread->last_frame();
 267     frame caller_frame = stub_frame.sender(&reg_map);
 268 
 269     // We don't really want to deoptimize the nmethod itself since we
 270     // can actually continue in the exception handler ourselves but I
 271     // don't see an easy way to have the desired effect.
 272     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
 273     assert(caller_is_deopted(), "Must be deoptimized");
 274 
 275     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 276   }
 277 
 278   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
 279   if (guard_pages_enabled) {
 280     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
 281     if (fast_continuation != NULL) {
 282       // Set flag if return address is a method handle call site.
 283       thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
 284       return fast_continuation;
 285     }
 286   }
 287 
 288   // If the stack guard pages are enabled, check whether there is a handler in
 289   // the current method.  Otherwise (guard pages disabled), force an unwind and
 290   // skip the exception cache update (i.e., just leave continuation==NULL).
 291   address continuation = NULL;
 292   if (guard_pages_enabled) {
 293 
 294     // New exception handling mechanism can support inlined methods
 295     // with exception handlers since the mappings are from PC to PC
 296 
 297     // debugging support
 298     // tracing
 299     if (log_is_enabled(Info, exceptions)) {
 300       ResourceMark rm;
 301       log_info(exceptions)("Exception <%s> (" INTPTR_FORMAT ") thrown in"
 302                            " compiled method <%s> at PC " INTPTR_FORMAT
 303                            " for thread " INTPTR_FORMAT,
 304                            exception->print_value_string(),
 305                            p2i((address)exception()),
 306                            nm->method()->print_value_string(), p2i(pc),
 307                            p2i(thread));
 308     }
 309     // for AbortVMOnException flag
 310     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
 311 
 312     // Clear out the exception oop and pc since looking up an
 313     // exception handler can cause class loading, which might throw an
 314     // exception and those fields are expected to be clear during
 315     // normal bytecode execution.
 316     thread->clear_exception_oop_and_pc();
 317 
 318     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
 319     // If an exception was thrown during exception dispatch, the exception oop may have changed
 320     thread->set_exception_oop(exception());
 321     thread->set_exception_pc(pc);
 322 
 323     // the exception cache is used only by non-implicit exceptions
 324     if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) {
 325       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
 326     }
 327   }
 328 
 329   // Set flag if return address is a method handle call site.
 330   thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
 331 
 332   if (log_is_enabled(Info, exceptions)) {
 333     ResourceMark rm;
 334     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
 335                          " for exception thrown at PC " PTR_FORMAT,
 336                          p2i(thread), p2i(continuation), p2i(pc));
 337   }
 338 
 339   return continuation;
 340 JRT_END
 341 
 342 // Enter this method from compiled code only if there is a Java exception handler
 343 // in the method handling the exception.
 344 // We are entering here from exception stub. We don't do a normal VM transition here.
 345 // We do it in a helper. This is so we can check to see if the nmethod we have just
 346 // searched for an exception handler has been deoptimized in the meantime.
 347 address JVMCIRuntime::exception_handler_for_pc(JavaThread* thread) {
 348   oop exception = thread->exception_oop();
 349   address pc = thread->exception_pc();
 350   // Still in Java mode
 351   DEBUG_ONLY(ResetNoHandleMark rnhm);
 352   nmethod* nm = NULL;
 353   address continuation = NULL;
 354   {
 355     // Enter VM mode by calling the helper
 356     ResetNoHandleMark rnhm;
 357     continuation = exception_handler_for_pc_helper(thread, exception, pc, nm);
 358   }
 359   // Back in JAVA, use no oops DON'T safepoint
 360 
 361   // Now check to see if the compiled method we were called from is now deoptimized.
 362   // If so we must return to the deopt blob and deoptimize the nmethod
 363   if (nm != NULL && caller_is_deopted()) {
 364     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 365   }
 366 
 367   assert(continuation != NULL, "no handler found");
 368   return continuation;
 369 }
 370 
 371 JRT_ENTRY(void, JVMCIRuntime::create_null_exception(JavaThread* thread))
 372   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
 373   thread->set_vm_result(PENDING_EXCEPTION);
 374   CLEAR_PENDING_EXCEPTION;
 375 JRT_END
 376 
 377 JRT_ENTRY(void, JVMCIRuntime::create_out_of_bounds_exception(JavaThread* thread, jint index))
 378   char message[jintAsStringSize];
 379   sprintf(message, "%d", index);
 380   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
 381   thread->set_vm_result(PENDING_EXCEPTION);
 382   CLEAR_PENDING_EXCEPTION;
 383 JRT_END
 384 
 385 JRT_ENTRY_NO_ASYNC(void, JVMCIRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 386   IF_TRACE_jvmci_3 {
 387     char type[O_BUFLEN];
 388     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 389     markOop mark = obj->mark();
 390     TRACE_jvmci_3("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock));
 391     tty->flush();
 392   }
 393 #ifdef ASSERT
 394   if (PrintBiasedLockingStatistics) {
 395     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 396   }
 397 #endif
 398   Handle h_obj(thread, obj);
 399   assert(h_obj()->is_oop(), "must be NULL or an object");
 400   if (UseBiasedLocking) {
 401     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 402     ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
 403   } else {
 404     if (JVMCIUseFastLocking) {
 405       // When using fast locking, the compiled code has already tried the fast case
 406       ObjectSynchronizer::slow_enter(h_obj, lock, THREAD);
 407     } else {
 408       ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD);
 409     }
 410   }
 411   TRACE_jvmci_3("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj));
 412 JRT_END
 413 
 414 JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 415   assert(thread == JavaThread::current(), "threads must correspond");
 416   assert(thread->last_Java_sp(), "last_Java_sp must be set");
 417   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
 418   EXCEPTION_MARK;
 419 
 420 #ifdef DEBUG
 421   if (!obj->is_oop()) {
 422     ResetNoHandleMark rhm;
 423     nmethod* method = thread->last_frame().cb()->as_nmethod_or_null();
 424     if (method != NULL) {
 425       tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj));
 426     }
 427     thread->print_stack_on(tty);
 428     assert(false, "invalid lock object pointer dected");
 429   }
 430 #endif
 431 
 432   if (JVMCIUseFastLocking) {
 433     // When using fast locking, the compiled code has already tried the fast case
 434     ObjectSynchronizer::slow_exit(obj, lock, THREAD);
 435   } else {
 436     ObjectSynchronizer::fast_exit(obj, lock, THREAD);
 437   }
 438   IF_TRACE_jvmci_3 {
 439     char type[O_BUFLEN];
 440     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 441     TRACE_jvmci_3("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock));
 442     tty->flush();
 443   }
 444 JRT_END
 445 
 446 JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
 447   ttyLocker ttyl;
 448 
 449   if (obj == NULL) {
 450     tty->print("NULL");
 451   } else if (obj->is_oop_or_null(true) && (!as_string || !java_lang_String::is_instance(obj))) {
 452     if (obj->is_oop_or_null(true)) {
 453       char buf[O_BUFLEN];
 454       tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
 455     } else {
 456       tty->print(INTPTR_FORMAT, p2i(obj));
 457     }
 458   } else {
 459     ResourceMark rm;
 460     assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
 461     char *buf = java_lang_String::as_utf8_string(obj);
 462     tty->print_raw(buf);
 463   }
 464   if (newline) {
 465     tty->cr();
 466   }
 467 JRT_END
 468 
 469 JRT_LEAF(void, JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj))
 470   thread->satb_mark_queue().enqueue(obj);
 471 JRT_END
 472 
 473 JRT_LEAF(void, JVMCIRuntime::write_barrier_post(JavaThread* thread, void* card_addr))
 474   thread->dirty_card_queue().enqueue(card_addr);
 475 JRT_END
 476 
 477 JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
 478   bool ret = true;
 479   if(!Universe::heap()->is_in_closed_subset(parent)) {
 480     tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
 481     parent->print();
 482     ret=false;
 483   }
 484   if(!Universe::heap()->is_in_closed_subset(child)) {
 485     tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
 486     child->print();
 487     ret=false;
 488   }
 489   return (jint)ret;
 490 JRT_END
 491 
 492 JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value))
 493   ResourceMark rm;
 494   const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
 495   char *detail_msg = NULL;
 496   if (format != 0L) {
 497     const char* buf = (char*) (address) format;
 498     size_t detail_msg_length = strlen(buf) * 2;
 499     detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
 500     jio_snprintf(detail_msg, detail_msg_length, buf, value);
 501     report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
 502   } else {
 503     report_vm_error(__FILE__, __LINE__, error_msg);
 504   }
 505 JRT_END
 506 
 507 JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
 508   oop exception = thread->exception_oop();
 509   assert(exception != NULL, "npe");
 510   thread->set_exception_oop(NULL);
 511   thread->set_exception_pc(0);
 512   return exception;
 513 JRT_END
 514 
 515 PRAGMA_DIAG_PUSH
 516 PRAGMA_FORMAT_NONLITERAL_IGNORED
 517 JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3))
 518   ResourceMark rm;
 519   assert(format != NULL && java_lang_String::is_instance(format), "must be");
 520   char *buf = java_lang_String::as_utf8_string(format);
 521   tty->print((const char*)buf, v1, v2, v3);
 522 JRT_END
 523 PRAGMA_DIAG_POP
 524 
 525 static void decipher(jlong v, bool ignoreZero) {
 526   if (v != 0 || !ignoreZero) {
 527     void* p = (void *)(address) v;
 528     CodeBlob* cb = CodeCache::find_blob(p);
 529     if (cb) {
 530       if (cb->is_nmethod()) {
 531         char buf[O_BUFLEN];
 532         tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin()));
 533         return;
 534       }
 535       cb->print_value_on(tty);
 536       return;
 537     }
 538     if (Universe::heap()->is_in(p)) {
 539       oop obj = oop(p);
 540       obj->print_value_on(tty);
 541       return;
 542     }
 543     tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
 544   }
 545 }
 546 
 547 PRAGMA_DIAG_PUSH
 548 PRAGMA_FORMAT_NONLITERAL_IGNORED
 549 JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
 550   ResourceMark rm;
 551   const char *buf = (const char*) (address) format;
 552   if (vmError) {
 553     if (buf != NULL) {
 554       fatal(buf, v1, v2, v3);
 555     } else {
 556       fatal("<anonymous error>");
 557     }
 558   } else if (buf != NULL) {
 559     tty->print(buf, v1, v2, v3);
 560   } else {
 561     assert(v2 == 0, "v2 != 0");
 562     assert(v3 == 0, "v3 != 0");
 563     decipher(v1, false);
 564   }
 565 JRT_END
 566 PRAGMA_DIAG_POP
 567 
 568 JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
 569   union {
 570       jlong l;
 571       jdouble d;
 572       jfloat f;
 573   } uu;
 574   uu.l = value;
 575   switch (typeChar) {
 576     case 'z': tty->print(value == 0 ? "false" : "true"); break;
 577     case 'b': tty->print("%d", (jbyte) value); break;
 578     case 'c': tty->print("%c", (jchar) value); break;
 579     case 's': tty->print("%d", (jshort) value); break;
 580     case 'i': tty->print("%d", (jint) value); break;
 581     case 'f': tty->print("%f", uu.f); break;
 582     case 'j': tty->print(JLONG_FORMAT, value); break;
 583     case 'd': tty->print("%lf", uu.d); break;
 584     default: assert(false, "unknown typeChar"); break;
 585   }
 586   if (newline) {
 587     tty->cr();
 588   }
 589 JRT_END
 590 
 591 JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj))
 592   return (jint) obj->identity_hash();
 593 JRT_END
 594 
 595 JRT_ENTRY(jboolean, JVMCIRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted))
 596   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
 597   // This locking requires thread_in_vm which is why this method cannot be JRT_LEAF.
 598   Handle receiverHandle(thread, receiver);
 599   MutexLockerEx ml(thread->threadObj() == (void*)receiver ? NULL : Threads_lock);
 600   JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle());
 601   if (receiverThread == NULL) {
 602     // The other thread may exit during this process, which is ok so return false.
 603     return JNI_FALSE;
 604   } else {
 605     return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0);
 606   }
 607 JRT_END
 608 
 609 JRT_ENTRY(jint, JVMCIRuntime::test_deoptimize_call_int(JavaThread* thread, int value))
 610   deopt_caller();
 611   return value;
 612 JRT_END
 613 
 614 // private static JVMCIRuntime JVMCI.initializeRuntime()
 615 JVM_ENTRY(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
 616   if (!EnableJVMCI) {
 617     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled")
 618   }
 619   JVMCIRuntime::initialize_HotSpotJVMCIRuntime(CHECK_NULL);
 620   jobject ret = JVMCIRuntime::get_HotSpotJVMCIRuntime_jobject(CHECK_NULL);
 621   return ret;
 622 JVM_END
 623 
 624 Handle JVMCIRuntime::callStatic(const char* className, const char* methodName, const char* signature, JavaCallArguments* args, TRAPS) {
 625   guarantee(!_HotSpotJVMCIRuntime_initialized, "cannot reinitialize HotSpotJVMCIRuntime");
 626 
 627   TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_(Handle()));
 628   KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, CHECK_(Handle()));
 629   TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_(Handle()));
 630   TempNewSymbol sig = SymbolTable::new_symbol(signature, CHECK_(Handle()));
 631   JavaValue result(T_OBJECT);
 632   if (args == NULL) {
 633     JavaCalls::call_static(&result, klass, runtime, sig, CHECK_(Handle()));
 634   } else {
 635     JavaCalls::call_static(&result, klass, runtime, sig, args, CHECK_(Handle()));
 636   }
 637   return Handle((oop)result.get_jobject());
 638 }
 639 
 640 static bool jvmci_options_file_exists() {
 641   const char* home = Arguments::get_java_home();
 642   size_t path_len = strlen(home) + strlen("/lib/jvmci.options") + 1;
 643   char path[JVM_MAXPATHLEN];
 644   char sep = os::file_separator()[0];
 645   jio_snprintf(path, JVM_MAXPATHLEN, "%s%clib%cjvmci.options", home, sep, sep);
 646   struct stat st;
 647   return os::stat(path, &st) == 0;
 648 }
 649 
 650 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(TRAPS) {
 651   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 652 #ifdef ASSERT
 653     // This should only be called in the context of the JVMCI class being initialized
 654     TempNewSymbol name = SymbolTable::new_symbol("jdk/vm/ci/runtime/JVMCI", CHECK);
 655     Klass* k = SystemDictionary::resolve_or_null(name, CHECK);
 656     instanceKlassHandle klass = InstanceKlass::cast(k);
 657     assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD),
 658            "HotSpotJVMCIRuntime initialization should only be triggered through JVMCI initialization");
 659 #endif
 660 
 661     bool parseOptionsFile = jvmci_options_file_exists();
 662     if (_options != NULL || parseOptionsFile) {
 663       JavaCallArguments args;
 664       objArrayOop options;
 665       if (_options != NULL) {
 666         options = oopFactory::new_objArray(SystemDictionary::String_klass(), _options_count * 2, CHECK);
 667         for (int i = 0; i < _options_count; i++) {
 668           SystemProperty* prop = _options[i];
 669           oop name = java_lang_String::create_oop_from_str(prop->key() + OPTION_PREFIX_LEN, CHECK);
 670           const char* prop_value = prop->value() != NULL ? prop->value() : "";
 671           oop value = java_lang_String::create_oop_from_str(prop_value, CHECK);
 672           options->obj_at_put(i * 2, name);
 673           options->obj_at_put((i * 2) + 1, value);
 674         }
 675       } else {
 676         options = NULL;
 677       }
 678       args.push_oop(options);
 679       args.push_int(parseOptionsFile);
 680       callStatic("jdk/vm/ci/options/OptionsParser",
 681                  "parseOptionsFromVM",
 682                  "([Ljava/lang/String;Z)Ljava/lang/Boolean;", &args, CHECK);
 683     }
 684 
 685     if (_compiler != NULL) {
 686       JavaCallArguments args;
 687       oop compiler = java_lang_String::create_oop_from_str(_compiler, CHECK);
 688       args.push_oop(compiler);
 689       callStatic("jdk/vm/ci/hotspot/HotSpotJVMCICompilerConfig",
 690                  "selectCompiler",
 691                  "(Ljava/lang/String;)Ljava/lang/Boolean;", &args, CHECK);
 692     }
 693 
 694     Handle result = callStatic("jdk/vm/ci/hotspot/HotSpotJVMCIRuntime",
 695                                "runtime",
 696                                "()Ljdk/vm/ci/hotspot/HotSpotJVMCIRuntime;", NULL, CHECK);
 697     objArrayOop trivial_prefixes = HotSpotJVMCIRuntime::trivialPrefixes(result);
 698     if (trivial_prefixes != NULL) {
 699       char** prefixes = NEW_C_HEAP_ARRAY(char*, trivial_prefixes->length(), mtCompiler);
 700       for (int i = 0; i < trivial_prefixes->length(); i++) {
 701         oop str = trivial_prefixes->obj_at(i);
 702         if (str == NULL) {
 703           THROW(vmSymbols::java_lang_NullPointerException());
 704         } else {
 705           prefixes[i] = strdup(java_lang_String::as_utf8_string(str));
 706         }
 707       }
 708       _trivial_prefixes = prefixes;
 709       _trivial_prefixes_count = trivial_prefixes->length();
 710     }
 711     _HotSpotJVMCIRuntime_initialized = true;
 712     _HotSpotJVMCIRuntime_instance = JNIHandles::make_global(result());
 713   }
 714 }
 715 
 716 void JVMCIRuntime::initialize_JVMCI(TRAPS) {
 717   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 718     callStatic("jdk/vm/ci/runtime/JVMCI",
 719                "getRuntime",
 720                "()Ljdk/vm/ci/runtime/JVMCIRuntime;", NULL, CHECK);
 721   }
 722   assert(_HotSpotJVMCIRuntime_initialized == true, "what?");
 723 }
 724 
 725 void JVMCIRuntime::initialize_well_known_classes(TRAPS) {
 726   if (JVMCIRuntime::_well_known_classes_initialized == false) {
 727     SystemDictionary::WKID scan = SystemDictionary::FIRST_JVMCI_WKID;
 728     SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_JVMCI_WKID, scan, CHECK);
 729     JVMCIJavaClasses::compute_offsets(CHECK);
 730     JVMCIRuntime::_well_known_classes_initialized = true;
 731   }
 732 }
 733 
 734 void JVMCIRuntime::metadata_do(void f(Metadata*)) {
 735   // For simplicity, the existence of HotSpotJVMCIMetaAccessContext in
 736   // the SystemDictionary well known classes should ensure the other
 737   // classes have already been loaded, so make sure their order in the
 738   // table enforces that.
 739   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedJavaMethodImpl) <
 740          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 741   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotConstantPool) <
 742          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 743   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedObjectTypeImpl) <
 744          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 745 
 746   if (HotSpotJVMCIMetaAccessContext::klass() == NULL ||
 747       !HotSpotJVMCIMetaAccessContext::klass()->is_linked()) {
 748     // Nothing could be registered yet
 749     return;
 750   }
 751 
 752   // WeakReference<HotSpotJVMCIMetaAccessContext>[]
 753   objArrayOop allContexts = HotSpotJVMCIMetaAccessContext::allContexts();
 754   if (allContexts == NULL) {
 755     return;
 756   }
 757 
 758   // These must be loaded at this point but the linking state doesn't matter.
 759   assert(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass() != NULL, "must be loaded");
 760   assert(SystemDictionary::HotSpotConstantPool_klass() != NULL, "must be loaded");
 761   assert(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass() != NULL, "must be loaded");
 762 
 763   for (int i = 0; i < allContexts->length(); i++) {
 764     oop ref = allContexts->obj_at(i);
 765     if (ref != NULL) {
 766       oop referent = java_lang_ref_Reference::referent(ref);
 767       if (referent != NULL) {
 768         // Chunked Object[] with last element pointing to next chunk
 769         objArrayOop metadataRoots = HotSpotJVMCIMetaAccessContext::metadataRoots(referent);
 770         while (metadataRoots != NULL) {
 771           for (int typeIndex = 0; typeIndex < metadataRoots->length() - 1; typeIndex++) {
 772             oop reference = metadataRoots->obj_at(typeIndex);
 773             if (reference == NULL) {
 774               continue;
 775             }
 776             oop metadataRoot = java_lang_ref_Reference::referent(reference);
 777             if (metadataRoot == NULL) {
 778               continue;
 779             }
 780             if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 781               Method* method = CompilerToVM::asMethod(metadataRoot);
 782               f(method);
 783             } else if (metadataRoot->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 784               ConstantPool* constantPool = CompilerToVM::asConstantPool(metadataRoot);
 785               f(constantPool);
 786             } else if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 787               Klass* klass = CompilerToVM::asKlass(metadataRoot);
 788               f(klass);
 789             } else {
 790               metadataRoot->print();
 791               ShouldNotReachHere();
 792             }
 793           }
 794           metadataRoots = (objArrayOop)metadataRoots->obj_at(metadataRoots->length() - 1);
 795           assert(metadataRoots == NULL || metadataRoots->is_objArray(), "wrong type");
 796         }
 797       }
 798     }
 799   }
 800 }
 801 
 802 // private static void CompilerToVM.registerNatives()
 803 JVM_ENTRY(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
 804   if (!EnableJVMCI) {
 805     THROW_MSG(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled");
 806   }
 807 
 808 #ifdef _LP64
 809 #ifndef TARGET_ARCH_sparc
 810   uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end();
 811   uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024;
 812   guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)");
 813 #endif // TARGET_ARCH_sparc
 814 #else
 815   fatal("check TLAB allocation code for address space conflicts");
 816 #endif
 817 
 818   JVMCIRuntime::initialize_well_known_classes(CHECK);
 819 
 820   {
 821     ThreadToNativeFromVM trans(thread);
 822 
 823     // Ensure _non_oop_bits is initialized
 824     Universe::non_oop_word();
 825 
 826     env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count());
 827   }
 828 JVM_END
 829 
 830 /**
 831  * Closure for parsing a line from a *.properties file in jre/lib/jvmci/properties.
 832  * The line must match the regular expression "[^=]+=.*". That is one or more
 833  * characters other than '=' followed by '=' followed by zero or more characters.
 834  * Everything before the '=' is the property name and everything after '=' is the value.
 835  * Lines that start with '#' are treated as comments and ignored.
 836  * No special processing of whitespace or any escape characters is performed.
 837  * The last definition of a property "wins" (i.e., it overrides all earlier
 838  * definitions of the property).
 839  */
 840 class JVMCIPropertiesFileClosure : public ParseClosure {
 841   SystemProperty** _plist;
 842 public:
 843   JVMCIPropertiesFileClosure(SystemProperty** plist) : _plist(plist) {}
 844   void do_line(char* line) {
 845     if (line[0] == '#') {
 846       // skip comment
 847       return;
 848     }
 849     size_t len = strlen(line);
 850     char* sep = strchr(line, '=');
 851     if (sep == NULL) {
 852       warn_and_abort("invalid format: could not find '=' character");
 853       return;
 854     }
 855     if (sep == line) {
 856       warn_and_abort("invalid format: name cannot be empty");
 857       return;
 858     }
 859     *sep = '\0';
 860     const char* name = line;
 861     char* value = sep + 1;
 862     Arguments::PropertyList_unique_add(_plist, name, value);
 863   }
 864 };
 865 
 866 void JVMCIRuntime::init_system_properties(SystemProperty** plist) {
 867   char jvmciDir[JVM_MAXPATHLEN];
 868   const char* fileSep = os::file_separator();
 869   jio_snprintf(jvmciDir, sizeof(jvmciDir), "%s%slib%sjvmci",
 870                Arguments::get_java_home(), fileSep, fileSep, fileSep);
 871   DIR* dir = os::opendir(jvmciDir);
 872   if (dir != NULL) {
 873     struct dirent *entry;
 874     char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(jvmciDir), mtInternal);
 875     JVMCIPropertiesFileClosure closure(plist);
 876     const unsigned suffix_len = (unsigned)strlen(".properties");
 877     while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL && !closure.is_aborted()) {
 878       const char* name = entry->d_name;
 879       if (strlen(name) > suffix_len && strcmp(name + strlen(name) - suffix_len, ".properties") == 0) {
 880         char propertiesFilePath[JVM_MAXPATHLEN];
 881         jio_snprintf(propertiesFilePath, sizeof(propertiesFilePath), "%s%s%s",jvmciDir, fileSep, name);
 882         JVMCIRuntime::parse_lines(propertiesFilePath, &closure, false);
 883       }
 884     }
 885     FREE_C_HEAP_ARRAY(char, dbuf);
 886     os::closedir(dir);
 887   }
 888 }
 889 
 890 #define CHECK_WARN_ABORT_(message) THREAD); \
 891   if (HAS_PENDING_EXCEPTION) { \
 892     warning(message); \
 893     char buf[512]; \
 894     jio_snprintf(buf, 512, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 895     JVMCIRuntime::abort_on_pending_exception(PENDING_EXCEPTION, buf); \
 896     return; \
 897   } \
 898   (void)(0
 899 
 900 void JVMCIRuntime::save_compiler(const char* compiler) {
 901   assert(compiler != NULL, "npe");
 902   assert(_compiler == NULL, "cannot reassign JVMCI compiler");
 903   _compiler = compiler;
 904 }
 905 
 906 void JVMCIRuntime::maybe_print_flags(TRAPS) {
 907   if (_options != NULL) {
 908     for (int i = 0; i < _options_count; i++) {
 909       SystemProperty* p = _options[i];
 910       const char* name = p->key() + OPTION_PREFIX_LEN;
 911       if (strcmp(name, "PrintFlags") == 0 || strcmp(name, "ShowFlags") == 0) {
 912         JVMCIRuntime::initialize_well_known_classes(CHECK);
 913         HandleMark hm;
 914         ResourceMark rm;
 915         JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK);
 916         return;
 917       }
 918     }
 919   }
 920 }
 921 
 922 void JVMCIRuntime::save_options(SystemProperty* props) {
 923   int count = 0;
 924   SystemProperty* first = NULL;
 925   for (SystemProperty* p = props; p != NULL; p = p->next()) {
 926     if (strncmp(p->key(), OPTION_PREFIX, OPTION_PREFIX_LEN) == 0) {
 927       if (first == NULL) {
 928         first = p;
 929       }
 930       count++;
 931     }
 932   }
 933   if (count != 0) {
 934     _options_count = count;
 935     _options = NEW_C_HEAP_ARRAY(SystemProperty*, count, mtCompiler);
 936     _options[0] = first;
 937     SystemProperty** insert_pos = _options + 1;
 938     for (SystemProperty* p = first->next(); p != NULL; p = p->next()) {
 939       if (strncmp(p->key(), OPTION_PREFIX, OPTION_PREFIX_LEN) == 0) {
 940         *insert_pos = p;
 941         insert_pos++;
 942       }
 943     }
 944     assert (insert_pos - _options == count, "must be");
 945   }
 946 }
 947 
 948 void JVMCIRuntime::shutdown() {
 949   if (_HotSpotJVMCIRuntime_instance != NULL) {
 950     _shutdown_called = true;
 951     JavaThread* THREAD = JavaThread::current();
 952     HandleMark hm(THREAD);
 953     Handle receiver = get_HotSpotJVMCIRuntime(CHECK_ABORT);
 954     JavaValue result(T_VOID);
 955     JavaCallArguments args;
 956     args.push_oop(receiver);
 957     JavaCalls::call_special(&result, receiver->klass(), vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK_ABORT);
 958   }
 959 }
 960 
 961 bool JVMCIRuntime::treat_as_trivial(Method* method) {
 962   if (_HotSpotJVMCIRuntime_initialized) {
 963     oop loader = method->method_holder()->class_loader();
 964     if (loader == NULL) {
 965       for (int i = 0; i < _trivial_prefixes_count; i++) {
 966         if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) {
 967           return true;
 968         }
 969       }
 970     }
 971   }
 972   return false;
 973 }
 974 
 975 void JVMCIRuntime::call_printStackTrace(Handle exception, Thread* thread) {
 976   assert(exception->is_a(SystemDictionary::Throwable_klass()), "Throwable instance expected");
 977   JavaValue result(T_VOID);
 978   JavaCalls::call_virtual(&result,
 979                           exception,
 980                           KlassHandle(thread,
 981                           SystemDictionary::Throwable_klass()),
 982                           vmSymbols::printStackTrace_name(),
 983                           vmSymbols::void_method_signature(),
 984                           thread);
 985 }
 986 
 987 void JVMCIRuntime::abort_on_pending_exception(Handle exception, const char* message, bool dump_core) {
 988   Thread* THREAD = Thread::current();
 989   CLEAR_PENDING_EXCEPTION;
 990   tty->print_raw_cr(message);
 991   call_printStackTrace(exception, THREAD);
 992 
 993   // Give other aborting threads to also print their stack traces.
 994   // This can be very useful when debugging class initialization
 995   // failures.
 996   os::sleep(THREAD, 200, false);
 997 
 998   vm_abort(dump_core);
 999 }
1000 
1001 void JVMCIRuntime::parse_lines(char* path, ParseClosure* closure, bool warnStatFailure) {
1002   struct stat st;
1003   if (::stat(path, &st) == 0 && (st.st_mode & S_IFREG) == S_IFREG) { // exists & is regular file
1004     int file_handle = ::open(path, os::default_file_open_flags(), 0);
1005     if (file_handle != -1) {
1006       char* buffer = NEW_C_HEAP_ARRAY(char, st.st_size + 1, mtInternal);
1007       int num_read;
1008       num_read = (int) ::read(file_handle, (char*) buffer, st.st_size);
1009       if (num_read == -1) {
1010         warning("Error reading file %s due to %s", path, strerror(errno));
1011       } else if (num_read != st.st_size) {
1012         warning("Only read %d of " SIZE_FORMAT " bytes from %s", num_read, (size_t) st.st_size, path);
1013       }
1014       ::close(file_handle);
1015       closure->set_filename(path);
1016       if (num_read == st.st_size) {
1017         buffer[num_read] = '\0';
1018 
1019         char* line = buffer;
1020         while (line - buffer < num_read && !closure->is_aborted()) {
1021           // find line end (\r, \n or \r\n)
1022           char* nextline = NULL;
1023           char* cr = strchr(line, '\r');
1024           char* lf = strchr(line, '\n');
1025           if (cr != NULL && lf != NULL) {
1026             char* min = MIN2(cr, lf);
1027             *min = '\0';
1028             if (lf == cr + 1) {
1029               nextline = lf + 1;
1030             } else {
1031               nextline = min + 1;
1032             }
1033           } else if (cr != NULL) {
1034             *cr = '\0';
1035             nextline = cr + 1;
1036           } else if (lf != NULL) {
1037             *lf = '\0';
1038             nextline = lf + 1;
1039           }
1040           // trim left
1041           while (*line == ' ' || *line == '\t') line++;
1042           char* end = line + strlen(line);
1043           // trim right
1044           while (end > line && (*(end -1) == ' ' || *(end -1) == '\t')) end--;
1045           *end = '\0';
1046           // skip comments and empty lines
1047           if (*line != '#' && strlen(line) > 0) {
1048             closure->parse_line(line);
1049           }
1050           if (nextline != NULL) {
1051             line = nextline;
1052           } else {
1053             // File without newline at the end
1054             break;
1055           }
1056         }
1057       }
1058       FREE_C_HEAP_ARRAY(char, buffer);
1059     } else {
1060       warning("Error opening file %s due to %s", path, strerror(errno));
1061     }
1062   } else if (warnStatFailure) {
1063     warning("Could not stat file %s due to %s", path, strerror(errno));
1064   }
1065 }