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