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