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