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