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 jobject ret = JVMCIRuntime::get_HotSpotJVMCIRuntime_jobject(CHECK_NULL); 629 return ret; 630 JVM_END 631 632 Handle JVMCIRuntime::callStatic(const char* className, const char* methodName, const char* signature, JavaCallArguments* args, TRAPS) { 633 guarantee(!_HotSpotJVMCIRuntime_initialized, "cannot reinitialize HotSpotJVMCIRuntime"); 634 635 TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_(Handle())); 636 KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, CHECK_(Handle())); 637 TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_(Handle())); 638 TempNewSymbol sig = SymbolTable::new_symbol(signature, CHECK_(Handle())); 639 JavaValue result(T_OBJECT); 640 if (args == NULL) { 641 JavaCalls::call_static(&result, klass, runtime, sig, CHECK_(Handle())); 642 } else { 643 JavaCalls::call_static(&result, klass, runtime, sig, args, CHECK_(Handle())); 644 } 645 return Handle((oop)result.get_jobject()); 646 } 647 648 static bool jvmci_options_file_exists() { 649 const char* home = Arguments::get_java_home(); 650 size_t path_len = strlen(home) + strlen("/lib/jvmci/options") + 1; 651 char path[JVM_MAXPATHLEN]; 652 char sep = os::file_separator()[0]; 653 jio_snprintf(path, JVM_MAXPATHLEN, "%s%clib%cjvmci%coptions", home, sep, sep, sep); 654 struct stat st; 655 return os::stat(path, &st) == 0; 656 } 657 658 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(TRAPS) { 659 if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) { 660 #ifdef ASSERT 661 // This should only be called in the context of the JVMCI class being initialized 662 TempNewSymbol name = SymbolTable::new_symbol("jdk/internal/jvmci/runtime/JVMCI", CHECK); 663 Klass* k = SystemDictionary::resolve_or_null(name, CHECK); 664 instanceKlassHandle klass = InstanceKlass::cast(k); 665 assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD), 666 "HotSpotJVMCIRuntime initialization should only be triggered through JVMCI initialization"); 667 #endif 668 669 bool parseOptionsFile = jvmci_options_file_exists(); 670 if (_options != NULL || parseOptionsFile) { 671 JavaCallArguments args; 672 oop options = java_lang_String::create_oop_from_str(_options, CHECK); 673 args.push_oop(options); 674 args.push_int(parseOptionsFile); 675 callStatic("jdk/internal/jvmci/options/OptionsParser", 676 "parseOptionsFromVM", 677 "(Ljava/lang/String;Z)Ljava/lang/Boolean;", &args, CHECK); 678 } 679 680 if (_compiler != NULL) { 681 JavaCallArguments args; 682 oop compiler = java_lang_String::create_oop_from_str(_compiler, CHECK); 683 args.push_oop(compiler); 684 callStatic("jdk/internal/jvmci/hotspot/HotSpotJVMCICompilerConfig", 685 "selectCompiler", 686 "(Ljava/lang/String;)Ljava/lang/Boolean;", &args, CHECK); 687 } 688 689 Handle result = callStatic("jdk/internal/jvmci/hotspot/HotSpotJVMCIRuntime", 690 "runtime", 691 "()Ljdk/internal/jvmci/hotspot/HotSpotJVMCIRuntime;", NULL, CHECK); 692 _HotSpotJVMCIRuntime_initialized = true; 693 _HotSpotJVMCIRuntime_instance = JNIHandles::make_global(result()); 694 } 695 } 696 697 void JVMCIRuntime::initialize_JVMCI(TRAPS) { 698 if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) { 699 callStatic("jdk/internal/jvmci/runtime/JVMCI", 700 "getRuntime", 701 "()Ljdk/internal/jvmci/runtime/JVMCIRuntime;", NULL, CHECK); 702 } 703 assert(_HotSpotJVMCIRuntime_initialized == true, "what?"); 704 } 705 706 void JVMCIRuntime::metadata_do(void f(Metadata*)) { 707 // For simplicity, the existence of HotSpotJVMCIMetaAccessContext in 708 // the SystemDictionary well known classes should ensure the other 709 // classes have already been loaded, so make sure their order in the 710 // table enforces that. 711 assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotResolvedJavaMethodImpl) < 712 SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier"); 713 assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotConstantPool) < 714 SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier"); 715 assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotResolvedObjectTypeImpl) < 716 SystemDictionary::WK_KLASS_ENUM_NAME(jdk_internal_jvmci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier"); 717 718 if (HotSpotJVMCIMetaAccessContext::klass() == NULL || 719 !HotSpotJVMCIMetaAccessContext::klass()->is_linked()) { 720 // Nothing could be registered yet 721 return; 722 } 723 724 // WeakReference<HotSpotJVMCIMetaAccessContext>[] 725 objArrayOop allContexts = HotSpotJVMCIMetaAccessContext::allContexts(); 726 if (allContexts == NULL) { 727 return; 728 } 729 730 // These must be loaded at this point but the linking state doesn't matter. 731 assert(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass() != NULL, "must be loaded"); 732 assert(SystemDictionary::HotSpotConstantPool_klass() != NULL, "must be loaded"); 733 assert(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass() != NULL, "must be loaded"); 734 735 for (int i = 0; i < allContexts->length(); i++) { 736 oop ref = allContexts->obj_at(i); 737 if (ref != NULL) { 738 oop referent = java_lang_ref_Reference::referent(ref); 739 if (referent != NULL) { 740 // Chunked Object[] with last element pointing to next chunk 741 objArrayOop metadataRoots = HotSpotJVMCIMetaAccessContext::metadataRoots(referent); 742 while (metadataRoots != NULL) { 743 for (int typeIndex = 0; typeIndex < metadataRoots->length() - 1; typeIndex++) { 744 oop reference = metadataRoots->obj_at(typeIndex); 745 if (reference == NULL) { 746 continue; 747 } 748 oop metadataRoot = java_lang_ref_Reference::referent(reference); 749 if (metadataRoot == NULL) { 750 continue; 751 } 752 if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) { 753 Method* method = CompilerToVM::asMethod(metadataRoot); 754 f(method); 755 } else if (metadataRoot->is_a(SystemDictionary::HotSpotConstantPool_klass())) { 756 ConstantPool* constantPool = CompilerToVM::asConstantPool(metadataRoot); 757 f(constantPool); 758 } else if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) { 759 Klass* klass = CompilerToVM::asKlass(metadataRoot); 760 f(klass); 761 } else { 762 metadataRoot->print(); 763 ShouldNotReachHere(); 764 } 765 } 766 metadataRoots = (objArrayOop)metadataRoots->obj_at(metadataRoots->length() - 1); 767 assert(metadataRoots == NULL || metadataRoots->is_objArray(), "wrong type"); 768 } 769 } 770 } 771 } 772 } 773 774 // private static void CompilerToVM.init() 775 JVM_ENTRY(void, JVM_InitializeJVMCINatives(JNIEnv *env, jclass c2vmClass)) 776 JVMCIRuntime::initialize_natives(env, c2vmClass); 777 JVM_END 778 779 /** 780 * Closure for parsing a line from a *.properties file in jre/lib/jvmci/properties. 781 * The line must match the regular expression "[^=]+=.*". That is one or more 782 * characters other than '=' followed by '=' followed by zero or more characters. 783 * Everything before the '=' is the property name and everything after '=' is the value. 784 * Lines that start with '#' are treated as comments and ignored. 785 * No special processing of whitespace or any escape characters is performed. 786 * The last definition of a property "wins" (i.e., it overrides all earlier 787 * definitions of the property). 788 */ 789 class JVMCIPropertiesFileClosure : public ParseClosure { 790 SystemProperty** _plist; 791 public: 792 JVMCIPropertiesFileClosure(SystemProperty** plist) : _plist(plist) {} 793 void do_line(char* line) { 794 if (line[0] == '#') { 795 // skip comment 796 return; 797 } 798 size_t len = strlen(line); 799 char* sep = strchr(line, '='); 800 if (sep == NULL) { 801 warn_and_abort("invalid format: could not find '=' character"); 802 return; 803 } 804 if (sep == line) { 805 warn_and_abort("invalid format: name cannot be empty"); 806 return; 807 } 808 *sep = '\0'; 809 const char* name = line; 810 char* value = sep + 1; 811 Arguments::PropertyList_unique_add(_plist, name, value); 812 } 813 }; 814 815 void JVMCIRuntime::parse_properties(SystemProperty** plist) { 816 char jvmciDir[JVM_MAXPATHLEN]; 817 const char* fileSep = os::file_separator(); 818 jio_snprintf(jvmciDir, sizeof(jvmciDir), "%s%slib%sjvmci", 819 Arguments::get_java_home(), fileSep, fileSep, fileSep); 820 DIR* dir = os::opendir(jvmciDir); 821 if (dir != NULL) { 822 struct dirent *entry; 823 char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(jvmciDir), mtInternal); 824 JVMCIPropertiesFileClosure closure(plist); 825 const unsigned suffix_len = (unsigned)strlen(".properties"); 826 while ((entry = os::readdir(dir, (dirent *) dbuf)) != NULL && !closure.is_aborted()) { 827 const char* name = entry->d_name; 828 if (strlen(name) > suffix_len && strcmp(name + strlen(name) - suffix_len, ".properties") == 0) { 829 char propertiesFilePath[JVM_MAXPATHLEN]; 830 jio_snprintf(propertiesFilePath, sizeof(propertiesFilePath), "%s%s%s",jvmciDir, fileSep, name); 831 JVMCIRuntime::parse_lines(propertiesFilePath, &closure, false); 832 } 833 } 834 FREE_C_HEAP_ARRAY(char, dbuf); 835 os::closedir(dir); 836 } 837 } 838 839 #define CHECK_WARN_ABORT_(message) THREAD); \ 840 if (HAS_PENDING_EXCEPTION) { \ 841 warning(message); \ 842 char buf[512]; \ 843 jio_snprintf(buf, 512, "Uncaught exception at %s:%d", __FILE__, __LINE__); \ 844 JVMCIRuntime::abort_on_pending_exception(PENDING_EXCEPTION, buf); \ 845 return; \ 846 } \ 847 (void)(0 848 849 void JVMCIRuntime::save_compiler(const char* compiler) { 850 assert(compiler != NULL, "npe"); 851 assert(_compiler == NULL, "cannot reassign JVMCI compiler"); 852 _compiler = compiler; 853 } 854 855 void JVMCIRuntime::save_options(const char* options) { 856 assert(options != NULL, "npe"); 857 assert(_options == NULL, "cannot reassign JVMCI options"); 858 _options = options; 859 } 860 861 void JVMCIRuntime::shutdown() { 862 if (_HotSpotJVMCIRuntime_instance != NULL) { 863 _shutdown_called = true; 864 JavaThread* THREAD = JavaThread::current(); 865 HandleMark hm(THREAD); 866 Handle receiver = get_HotSpotJVMCIRuntime(CHECK_ABORT); 867 JavaValue result(T_VOID); 868 JavaCallArguments args; 869 args.push_oop(receiver); 870 JavaCalls::call_special(&result, receiver->klass(), vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK_ABORT); 871 } 872 } 873 874 void JVMCIRuntime::call_printStackTrace(Handle exception, Thread* thread) { 875 assert(exception->is_a(SystemDictionary::Throwable_klass()), "Throwable instance expected"); 876 JavaValue result(T_VOID); 877 JavaCalls::call_virtual(&result, 878 exception, 879 KlassHandle(thread, 880 SystemDictionary::Throwable_klass()), 881 vmSymbols::printStackTrace_name(), 882 vmSymbols::void_method_signature(), 883 thread); 884 } 885 886 void JVMCIRuntime::abort_on_pending_exception(Handle exception, const char* message, bool dump_core) { 887 Thread* THREAD = Thread::current(); 888 CLEAR_PENDING_EXCEPTION; 889 tty->print_raw_cr(message); 890 call_printStackTrace(exception, THREAD); 891 892 // Give other aborting threads to also print their stack traces. 893 // This can be very useful when debugging class initialization 894 // failures. 895 os::sleep(THREAD, 200, false); 896 897 vm_abort(dump_core); 898 } 899 900 void JVMCIRuntime::parse_lines(char* path, ParseClosure* closure, bool warnStatFailure) { 901 struct stat st; 902 if (os::stat(path, &st) == 0 && (st.st_mode & S_IFREG) == S_IFREG) { // exists & is regular file 903 int file_handle = os::open(path, 0, 0); 904 if (file_handle != -1) { 905 char* buffer = NEW_C_HEAP_ARRAY(char, st.st_size + 1, mtInternal); 906 int num_read; 907 num_read = (int) os::read(file_handle, (char*) buffer, st.st_size); 908 if (num_read == -1) { 909 warning("Error reading file %s due to %s", path, strerror(errno)); 910 } else if (num_read != st.st_size) { 911 warning("Only read %d of " SIZE_FORMAT " bytes from %s", num_read, (size_t) st.st_size, path); 912 } 913 os::close(file_handle); 914 closure->set_filename(path); 915 if (num_read == st.st_size) { 916 buffer[num_read] = '\0'; 917 918 char* line = buffer; 919 while (line - buffer < num_read && !closure->is_aborted()) { 920 // find line end (\r, \n or \r\n) 921 char* nextline = NULL; 922 char* cr = strchr(line, '\r'); 923 char* lf = strchr(line, '\n'); 924 if (cr != NULL && lf != NULL) { 925 char* min = MIN2(cr, lf); 926 *min = '\0'; 927 if (lf == cr + 1) { 928 nextline = lf + 1; 929 } else { 930 nextline = min + 1; 931 } 932 } else if (cr != NULL) { 933 *cr = '\0'; 934 nextline = cr + 1; 935 } else if (lf != NULL) { 936 *lf = '\0'; 937 nextline = lf + 1; 938 } 939 // trim left 940 while (*line == ' ' || *line == '\t') line++; 941 char* end = line + strlen(line); 942 // trim right 943 while (end > line && (*(end -1) == ' ' || *(end -1) == '\t')) end--; 944 *end = '\0'; 945 // skip comments and empty lines 946 if (*line != '#' && strlen(line) > 0) { 947 closure->parse_line(line); 948 } 949 if (nextline != NULL) { 950 line = nextline; 951 } else { 952 // File without newline at the end 953 break; 954 } 955 } 956 } 957 FREE_C_HEAP_ARRAY(char, buffer); 958 } else { 959 warning("Error opening file %s due to %s", path, strerror(errno)); 960 } 961 } else if (warnStatFailure) { 962 warning("Could not stat file %s due to %s", path, strerror(errno)); 963 } 964 }