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