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