1 /* 2 * Copyright (c) 1997, 2025, 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 25 #include "classfile/javaClasses.inline.hpp" 26 #include "classfile/symbolTable.hpp" 27 #include "classfile/vmClasses.hpp" 28 #include "classfile/vmSymbols.hpp" 29 #include "code/codeCache.hpp" 30 #include "compiler/compilationPolicy.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "compiler/disassembler.hpp" 33 #include "gc/shared/barrierSetNMethod.hpp" 34 #include "gc/shared/collectedHeap.hpp" 35 #include "interpreter/bytecodeTracer.hpp" 36 #include "interpreter/interpreter.hpp" 37 #include "interpreter/interpreterRuntime.hpp" 38 #include "interpreter/linkResolver.hpp" 39 #include "interpreter/templateTable.hpp" 40 #include "jvm_io.h" 41 #include "logging/log.hpp" 42 #include "memory/oopFactory.hpp" 43 #include "memory/resourceArea.hpp" 44 #include "memory/universe.hpp" 45 #include "oops/constantPool.inline.hpp" 46 #include "oops/cpCache.inline.hpp" 47 #include "oops/instanceKlass.inline.hpp" 48 #include "oops/klass.inline.hpp" 49 #include "oops/methodData.hpp" 50 #include "oops/method.inline.hpp" 51 #include "oops/objArrayKlass.hpp" 52 #include "oops/objArrayOop.inline.hpp" 53 #include "oops/oop.inline.hpp" 54 #include "oops/symbol.hpp" 55 #include "prims/jvmtiExport.hpp" 56 #include "prims/methodHandles.hpp" 57 #include "prims/nativeLookup.hpp" 58 #include "runtime/atomic.hpp" 59 #include "runtime/continuation.hpp" 60 #include "runtime/deoptimization.hpp" 61 #include "runtime/fieldDescriptor.inline.hpp" 62 #include "runtime/frame.inline.hpp" 63 #include "runtime/handles.inline.hpp" 64 #include "runtime/icache.hpp" 65 #include "runtime/interfaceSupport.inline.hpp" 66 #include "runtime/java.hpp" 67 #include "runtime/javaCalls.hpp" 68 #include "runtime/jfieldIDWorkaround.hpp" 69 #include "runtime/osThread.hpp" 70 #include "runtime/sharedRuntime.hpp" 71 #include "runtime/stackWatermarkSet.hpp" 72 #include "runtime/stubRoutines.hpp" 73 #include "runtime/synchronizer.inline.hpp" 74 #include "utilities/align.hpp" 75 #include "utilities/checkedCast.hpp" 76 #include "utilities/copy.hpp" 77 #include "utilities/events.hpp" 78 #if INCLUDE_JFR 79 #include "jfr/jfr.inline.hpp" 80 #endif 81 82 // Helper class to access current interpreter state 83 class LastFrameAccessor : public StackObj { 84 frame _last_frame; 85 public: 86 LastFrameAccessor(JavaThread* current) { 87 assert(current == Thread::current(), "sanity"); 88 _last_frame = current->last_frame(); 89 } 90 bool is_interpreted_frame() const { return _last_frame.is_interpreted_frame(); } 91 Method* method() const { return _last_frame.interpreter_frame_method(); } 92 address bcp() const { return _last_frame.interpreter_frame_bcp(); } 93 int bci() const { return _last_frame.interpreter_frame_bci(); } 94 address mdp() const { return _last_frame.interpreter_frame_mdp(); } 95 96 void set_bcp(address bcp) { _last_frame.interpreter_frame_set_bcp(bcp); } 97 void set_mdp(address dp) { _last_frame.interpreter_frame_set_mdp(dp); } 98 99 // pass method to avoid calling unsafe bcp_to_method (partial fix 4926272) 100 Bytecodes::Code code() const { return Bytecodes::code_at(method(), bcp()); } 101 102 Bytecode bytecode() const { return Bytecode(method(), bcp()); } 103 int get_index_u1(Bytecodes::Code bc) const { return bytecode().get_index_u1(bc); } 104 int get_index_u2(Bytecodes::Code bc) const { return bytecode().get_index_u2(bc); } 105 int get_index_u4(Bytecodes::Code bc) const { return bytecode().get_index_u4(bc); } 106 int number_of_dimensions() const { return bcp()[3]; } 107 108 oop callee_receiver(Symbol* signature) { 109 return _last_frame.interpreter_callee_receiver(signature); 110 } 111 BasicObjectLock* monitor_begin() const { 112 return _last_frame.interpreter_frame_monitor_begin(); 113 } 114 BasicObjectLock* monitor_end() const { 115 return _last_frame.interpreter_frame_monitor_end(); 116 } 117 BasicObjectLock* next_monitor(BasicObjectLock* current) const { 118 return _last_frame.next_monitor_in_interpreter_frame(current); 119 } 120 121 frame& get_frame() { return _last_frame; } 122 }; 123 124 class ProfileTrapsMark : public StackObj { 125 JavaThread* _thread; 126 public: 127 ProfileTrapsMark(JavaThread* current) : _thread(current) {} 128 ~ProfileTrapsMark() { 129 JavaThread* THREAD = _thread; 130 if (HAS_PENDING_EXCEPTION) { 131 if (ProfileTraps && PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_NullPointerException()) { 132 // Preserve the original exception across the call to note_trap() 133 PreserveExceptionMark pm(_thread); 134 // Recording the trap will help the compiler to potentially recognize this exception as "hot" 135 InterpreterRuntime::note_trap(_thread, Deoptimization::Reason_null_check); 136 } 137 } 138 } 139 }; 140 141 //------------------------------------------------------------------------------------------------------------------------ 142 // State accessors 143 144 void InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread* current) { 145 LastFrameAccessor last_frame(current); 146 last_frame.set_bcp(bcp); 147 if (ProfileInterpreter) { 148 // ProfileTraps uses MDOs independently of ProfileInterpreter. 149 // That is why we must check both ProfileInterpreter and mdo != nullptr. 150 MethodData* mdo = last_frame.method()->method_data(); 151 if (mdo != nullptr) { 152 NEEDS_CLEANUP; 153 last_frame.set_mdp(mdo->bci_to_dp(last_frame.bci())); 154 } 155 } 156 } 157 158 //------------------------------------------------------------------------------------------------------------------------ 159 // Constants 160 161 162 JRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* current, bool wide)) 163 // access constant pool 164 LastFrameAccessor last_frame(current); 165 ConstantPool* pool = last_frame.method()->constants(); 166 int cp_index = wide ? last_frame.get_index_u2(Bytecodes::_ldc_w) : last_frame.get_index_u1(Bytecodes::_ldc); 167 constantTag tag = pool->tag_at(cp_index); 168 169 assert (tag.is_unresolved_klass() || tag.is_klass(), "wrong ldc call"); 170 Klass* klass = pool->klass_at(cp_index, CHECK); 171 oop java_class = klass->java_mirror(); 172 current->set_vm_result_oop(java_class); 173 JRT_END 174 175 JRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* current, Bytecodes::Code bytecode)) { 176 assert(bytecode == Bytecodes::_ldc || 177 bytecode == Bytecodes::_ldc_w || 178 bytecode == Bytecodes::_ldc2_w || 179 bytecode == Bytecodes::_fast_aldc || 180 bytecode == Bytecodes::_fast_aldc_w, "wrong bc"); 181 ResourceMark rm(current); 182 const bool is_fast_aldc = (bytecode == Bytecodes::_fast_aldc || 183 bytecode == Bytecodes::_fast_aldc_w); 184 LastFrameAccessor last_frame(current); 185 methodHandle m (current, last_frame.method()); 186 Bytecode_loadconstant ldc(m, last_frame.bci()); 187 188 // Double-check the size. (Condy can have any type.) 189 BasicType type = ldc.result_type(); 190 switch (type2size[type]) { 191 case 2: guarantee(bytecode == Bytecodes::_ldc2_w, ""); break; 192 case 1: guarantee(bytecode != Bytecodes::_ldc2_w, ""); break; 193 default: ShouldNotReachHere(); 194 } 195 196 // Resolve the constant. This does not do unboxing. 197 // But it does replace Universe::the_null_sentinel by null. 198 oop result = ldc.resolve_constant(CHECK); 199 assert(result != nullptr || is_fast_aldc, "null result only valid for fast_aldc"); 200 201 #ifdef ASSERT 202 { 203 // The bytecode wrappers aren't GC-safe so construct a new one 204 Bytecode_loadconstant ldc2(m, last_frame.bci()); 205 int rindex = ldc2.cache_index(); 206 if (rindex < 0) 207 rindex = m->constants()->cp_to_object_index(ldc2.pool_index()); 208 if (rindex >= 0) { 209 oop coop = m->constants()->resolved_reference_at(rindex); 210 oop roop = (result == nullptr ? Universe::the_null_sentinel() : result); 211 assert(roop == coop, "expected result for assembly code"); 212 } 213 } 214 #endif 215 current->set_vm_result_oop(result); 216 if (!is_fast_aldc) { 217 // Tell the interpreter how to unbox the primitive. 218 guarantee(java_lang_boxing_object::is_instance(result, type), ""); 219 int offset = java_lang_boxing_object::value_offset(type); 220 intptr_t flags = ((as_TosState(type) << ConstantPoolCache::tos_state_shift) 221 | (offset & ConstantPoolCache::field_index_mask)); 222 current->set_vm_result_metadata((Metadata*)flags); 223 } 224 } 225 JRT_END 226 227 228 //------------------------------------------------------------------------------------------------------------------------ 229 // Allocation 230 231 JRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* current, ConstantPool* pool, int index)) 232 Klass* k = pool->klass_at(index, CHECK); 233 InstanceKlass* klass = InstanceKlass::cast(k); 234 235 // Make sure we are not instantiating an abstract klass 236 klass->check_valid_for_instantiation(true, CHECK); 237 238 // Make sure klass is initialized 239 klass->initialize_preemptable(CHECK_AND_CLEAR_PREEMPTED); 240 241 oop obj = klass->allocate_instance(CHECK); 242 current->set_vm_result_oop(obj); 243 JRT_END 244 245 246 JRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* current, BasicType type, jint size)) 247 oop obj = oopFactory::new_typeArray(type, size, CHECK); 248 current->set_vm_result_oop(obj); 249 JRT_END 250 251 252 JRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* current, ConstantPool* pool, int index, jint size)) 253 Klass* klass = pool->klass_at(index, CHECK); 254 objArrayOop obj = oopFactory::new_objArray(klass, size, CHECK); 255 current->set_vm_result_oop(obj); 256 JRT_END 257 258 259 JRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* current, jint* first_size_address)) 260 // We may want to pass in more arguments - could make this slightly faster 261 LastFrameAccessor last_frame(current); 262 ConstantPool* constants = last_frame.method()->constants(); 263 int i = last_frame.get_index_u2(Bytecodes::_multianewarray); 264 Klass* klass = constants->klass_at(i, CHECK); 265 int nof_dims = last_frame.number_of_dimensions(); 266 assert(klass->is_klass(), "not a class"); 267 assert(nof_dims >= 1, "multianewarray rank must be nonzero"); 268 269 // We must create an array of jints to pass to multi_allocate. 270 ResourceMark rm(current); 271 const int small_dims = 10; 272 jint dim_array[small_dims]; 273 jint *dims = &dim_array[0]; 274 if (nof_dims > small_dims) { 275 dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims); 276 } 277 for (int index = 0; index < nof_dims; index++) { 278 // offset from first_size_address is addressed as local[index] 279 int n = Interpreter::local_offset_in_bytes(index)/jintSize; 280 dims[index] = first_size_address[n]; 281 } 282 oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK); 283 current->set_vm_result_oop(obj); 284 JRT_END 285 286 287 JRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* current, oopDesc* obj)) 288 assert(oopDesc::is_oop(obj), "must be a valid oop"); 289 assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise"); 290 InstanceKlass::register_finalizer(instanceOop(obj), CHECK); 291 JRT_END 292 293 294 // Quicken instance-of and check-cast bytecodes 295 JRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* current)) 296 // Force resolving; quicken the bytecode 297 LastFrameAccessor last_frame(current); 298 int which = last_frame.get_index_u2(Bytecodes::_checkcast); 299 ConstantPool* cpool = last_frame.method()->constants(); 300 // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded 301 // program we might have seen an unquick'd bytecode in the interpreter but have another 302 // thread quicken the bytecode before we get here. 303 // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" ); 304 Klass* klass = cpool->klass_at(which, CHECK); 305 current->set_vm_result_metadata(klass); 306 JRT_END 307 308 309 //------------------------------------------------------------------------------------------------------------------------ 310 // Exceptions 311 312 void InterpreterRuntime::note_trap_inner(JavaThread* current, int reason, 313 const methodHandle& trap_method, int trap_bci) { 314 if (trap_method.not_null()) { 315 MethodData* trap_mdo = trap_method->method_data(); 316 if (trap_mdo == nullptr) { 317 ExceptionMark em(current); 318 JavaThread* THREAD = current; // For exception macros. 319 Method::build_profiling_method_data(trap_method, THREAD); 320 if (HAS_PENDING_EXCEPTION) { 321 // Only metaspace OOM is expected. No Java code executed. 322 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), 323 "we expect only an OOM error here"); 324 CLEAR_PENDING_EXCEPTION; 325 } 326 trap_mdo = trap_method->method_data(); 327 // and fall through... 328 } 329 if (trap_mdo != nullptr) { 330 // Update per-method count of trap events. The interpreter 331 // is updating the MDO to simulate the effect of compiler traps. 332 Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason); 333 } 334 } 335 } 336 337 // Assume the compiler is (or will be) interested in this event. 338 // If necessary, create an MDO to hold the information, and record it. 339 void InterpreterRuntime::note_trap(JavaThread* current, int reason) { 340 assert(ProfileTraps, "call me only if profiling"); 341 LastFrameAccessor last_frame(current); 342 methodHandle trap_method(current, last_frame.method()); 343 int trap_bci = trap_method->bci_from(last_frame.bcp()); 344 note_trap_inner(current, reason, trap_method, trap_bci); 345 } 346 347 static Handle get_preinitialized_exception(Klass* k, TRAPS) { 348 // get klass 349 InstanceKlass* klass = InstanceKlass::cast(k); 350 assert(klass->is_initialized(), 351 "this klass should have been initialized during VM initialization"); 352 // create instance - do not call constructor since we may have no 353 // (java) stack space left (should assert constructor is empty) 354 Handle exception; 355 oop exception_oop = klass->allocate_instance(CHECK_(exception)); 356 exception = Handle(THREAD, exception_oop); 357 if (StackTraceInThrowable) { 358 java_lang_Throwable::fill_in_stack_trace(exception); 359 } 360 return exception; 361 } 362 363 // Special handling for stack overflow: since we don't have any (java) stack 364 // space left we use the pre-allocated & pre-initialized StackOverflowError 365 // klass to create an stack overflow error instance. We do not call its 366 // constructor for the same reason (it is empty, anyway). 367 JRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* current)) 368 Handle exception = get_preinitialized_exception( 369 vmClasses::StackOverflowError_klass(), 370 CHECK); 371 // Increment counter for hs_err file reporting 372 Atomic::inc(&Exceptions::_stack_overflow_errors); 373 // Remove the ScopedValue bindings in case we got a StackOverflowError 374 // while we were trying to manipulate ScopedValue bindings. 375 current->clear_scopedValueBindings(); 376 THROW_HANDLE(exception); 377 JRT_END 378 379 JRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* current)) 380 Handle exception = get_preinitialized_exception( 381 vmClasses::StackOverflowError_klass(), 382 CHECK); 383 java_lang_Throwable::set_message(exception(), 384 Universe::delayed_stack_overflow_error_message()); 385 // Increment counter for hs_err file reporting 386 Atomic::inc(&Exceptions::_stack_overflow_errors); 387 // Remove the ScopedValue bindings in case we got a StackOverflowError 388 // while we were trying to manipulate ScopedValue bindings. 389 current->clear_scopedValueBindings(); 390 THROW_HANDLE(exception); 391 JRT_END 392 393 JRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* current, char* name, char* message)) 394 // lookup exception klass 395 TempNewSymbol s = SymbolTable::new_symbol(name); 396 if (ProfileTraps) { 397 if (s == vmSymbols::java_lang_ArithmeticException()) { 398 note_trap(current, Deoptimization::Reason_div0_check); 399 } else if (s == vmSymbols::java_lang_NullPointerException()) { 400 note_trap(current, Deoptimization::Reason_null_check); 401 } 402 } 403 // create exception 404 Handle exception = Exceptions::new_exception(current, s, message); 405 current->set_vm_result_oop(exception()); 406 JRT_END 407 408 409 JRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* current, char* name, oopDesc* obj)) 410 // Produce the error message first because note_trap can safepoint 411 ResourceMark rm(current); 412 const char* klass_name = obj->klass()->external_name(); 413 // lookup exception klass 414 TempNewSymbol s = SymbolTable::new_symbol(name); 415 if (ProfileTraps) { 416 if (s == vmSymbols::java_lang_ArrayStoreException()) { 417 note_trap(current, Deoptimization::Reason_array_check); 418 } else { 419 note_trap(current, Deoptimization::Reason_class_check); 420 } 421 } 422 // create exception, with klass name as detail message 423 Handle exception = Exceptions::new_exception(current, s, klass_name); 424 current->set_vm_result_oop(exception()); 425 JRT_END 426 427 JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* current, arrayOopDesc* a, jint index)) 428 // Produce the error message first because note_trap can safepoint 429 ResourceMark rm(current); 430 stringStream ss; 431 ss.print("Index %d out of bounds for length %d", index, a->length()); 432 433 if (ProfileTraps) { 434 note_trap(current, Deoptimization::Reason_range_check); 435 } 436 437 THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string()); 438 JRT_END 439 440 JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException( 441 JavaThread* current, oopDesc* obj)) 442 443 // Produce the error message first because note_trap can safepoint 444 ResourceMark rm(current); 445 char* message = SharedRuntime::generate_class_cast_message( 446 current, obj->klass()); 447 448 if (ProfileTraps) { 449 note_trap(current, Deoptimization::Reason_class_check); 450 } 451 452 // create exception 453 THROW_MSG(vmSymbols::java_lang_ClassCastException(), message); 454 JRT_END 455 456 // exception_handler_for_exception(...) returns the continuation address, 457 // the exception oop (via TLS) and sets the bci/bcp for the continuation. 458 // The exception oop is returned to make sure it is preserved over GC (it 459 // is only on the stack if the exception was thrown explicitly via athrow). 460 // During this operation, the expression stack contains the values for the 461 // bci where the exception happened. If the exception was propagated back 462 // from a call, the expression stack contains the values for the bci at the 463 // invoke w/o arguments (i.e., as if one were inside the call). 464 // Note that the implementation of this method assumes it's only called when an exception has actually occured 465 JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* current, oopDesc* exception)) 466 // We get here after we have unwound from a callee throwing an exception 467 // into the interpreter. Any deferred stack processing is notified of 468 // the event via the StackWatermarkSet. 469 StackWatermarkSet::after_unwind(current); 470 471 LastFrameAccessor last_frame(current); 472 Handle h_exception(current, exception); 473 methodHandle h_method (current, last_frame.method()); 474 constantPoolHandle h_constants(current, h_method->constants()); 475 bool should_repeat; 476 int handler_bci; 477 int current_bci = last_frame.bci(); 478 479 if (current->frames_to_pop_failed_realloc() > 0) { 480 // Allocation of scalar replaced object used in this frame 481 // failed. Unconditionally pop the frame. 482 current->dec_frames_to_pop_failed_realloc(); 483 current->set_vm_result_oop(h_exception()); 484 // If the method is synchronized we already unlocked the monitor 485 // during deoptimization so the interpreter needs to skip it when 486 // the frame is popped. 487 current->set_do_not_unlock_if_synchronized(true); 488 return Interpreter::remove_activation_entry(); 489 } 490 491 // Need to do this check first since when _do_not_unlock_if_synchronized 492 // is set, we don't want to trigger any classloading which may make calls 493 // into java, or surprisingly find a matching exception handler for bci 0 494 // since at this moment the method hasn't been "officially" entered yet. 495 if (current->do_not_unlock_if_synchronized()) { 496 ResourceMark rm; 497 assert(current_bci == 0, "bci isn't zero for do_not_unlock_if_synchronized"); 498 current->set_vm_result_oop(exception); 499 return Interpreter::remove_activation_entry(); 500 } 501 502 do { 503 should_repeat = false; 504 505 // assertions 506 assert(h_exception.not_null(), "null exceptions should be handled by athrow"); 507 // Check that exception is a subclass of Throwable. 508 assert(h_exception->is_a(vmClasses::Throwable_klass()), 509 "Exception not subclass of Throwable"); 510 511 // tracing 512 if (log_is_enabled(Info, exceptions)) { 513 ResourceMark rm(current); 514 stringStream tempst; 515 tempst.print("interpreter method <%s>\n" 516 " at bci %d for thread " INTPTR_FORMAT " (%s)", 517 h_method->print_value_string(), current_bci, p2i(current), current->name()); 518 Exceptions::log_exception(h_exception, tempst.as_string()); 519 } 520 if (log_is_enabled(Info, exceptions, stacktrace)) { 521 Exceptions::log_exception_stacktrace(h_exception, h_method, current_bci); 522 } 523 524 // Don't go paging in something which won't be used. 525 // else if (extable->length() == 0) { 526 // // disabled for now - interpreter is not using shortcut yet 527 // // (shortcut is not to call runtime if we have no exception handlers) 528 // // warning("performance bug: should not call runtime if method has no exception handlers"); 529 // } 530 // for AbortVMOnException flag 531 Exceptions::debug_check_abort(h_exception); 532 533 // exception handler lookup 534 Klass* klass = h_exception->klass(); 535 handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD); 536 if (HAS_PENDING_EXCEPTION) { 537 // We threw an exception while trying to find the exception handler. 538 // Transfer the new exception to the exception handle which will 539 // be set into thread local storage, and do another lookup for an 540 // exception handler for this exception, this time starting at the 541 // BCI of the exception handler which caused the exception to be 542 // thrown (bug 4307310). 543 h_exception = Handle(THREAD, PENDING_EXCEPTION); 544 CLEAR_PENDING_EXCEPTION; 545 if (handler_bci >= 0) { 546 current_bci = handler_bci; 547 should_repeat = true; 548 } 549 } 550 } while (should_repeat == true); 551 552 #if INCLUDE_JVMCI 553 if (EnableJVMCI && h_method->method_data() != nullptr) { 554 ResourceMark rm(current); 555 MethodData* mdo = h_method->method_data(); 556 557 // Lock to read ProfileData, and ensure lock is not broken by a safepoint 558 MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag); 559 560 ProfileData* pdata = mdo->allocate_bci_to_data(current_bci, nullptr); 561 if (pdata != nullptr && pdata->is_BitData()) { 562 BitData* bit_data = (BitData*) pdata; 563 bit_data->set_exception_seen(); 564 } 565 } 566 #endif 567 568 // notify JVMTI of an exception throw; JVMTI will detect if this is a first 569 // time throw or a stack unwinding throw and accordingly notify the debugger 570 if (JvmtiExport::can_post_on_exceptions()) { 571 JvmtiExport::post_exception_throw(current, h_method(), last_frame.bcp(), h_exception()); 572 } 573 574 address continuation = nullptr; 575 address handler_pc = nullptr; 576 if (handler_bci < 0 || !current->stack_overflow_state()->reguard_stack((address) &continuation)) { 577 // Forward exception to callee (leaving bci/bcp untouched) because (a) no 578 // handler in this method, or (b) after a stack overflow there is not yet 579 // enough stack space available to reprotect the stack. 580 continuation = Interpreter::remove_activation_entry(); 581 #if COMPILER2_OR_JVMCI 582 // Count this for compilation purposes 583 h_method->interpreter_throwout_increment(THREAD); 584 #endif 585 } else { 586 // handler in this method => change bci/bcp to handler bci/bcp and continue there 587 handler_pc = h_method->code_base() + handler_bci; 588 h_method->set_exception_handler_entered(handler_bci); // profiling 589 #ifndef ZERO 590 set_bcp_and_mdp(handler_pc, current); 591 continuation = Interpreter::dispatch_table(vtos)[*handler_pc]; 592 #else 593 continuation = (address)(intptr_t) handler_bci; 594 #endif 595 } 596 597 // notify debugger of an exception catch 598 // (this is good for exceptions caught in native methods as well) 599 if (JvmtiExport::can_post_on_exceptions()) { 600 JvmtiExport::notice_unwind_due_to_exception(current, h_method(), handler_pc, h_exception(), (handler_pc != nullptr)); 601 } 602 603 current->set_vm_result_oop(h_exception()); 604 return continuation; 605 JRT_END 606 607 608 JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* current)) 609 assert(current->has_pending_exception(), "must only be called if there's an exception pending"); 610 // nothing to do - eventually we should remove this code entirely (see comments @ call sites) 611 JRT_END 612 613 614 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* current)) 615 THROW(vmSymbols::java_lang_AbstractMethodError()); 616 JRT_END 617 618 // This method is called from the "abstract_entry" of the interpreter. 619 // At that point, the arguments have already been removed from the stack 620 // and therefore we don't have the receiver object at our fingertips. (Though, 621 // on some platforms the receiver still resides in a register...). Thus, 622 // we have no choice but print an error message not containing the receiver 623 // type. 624 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* current, 625 Method* missingMethod)) 626 ResourceMark rm(current); 627 assert(missingMethod != nullptr, "sanity"); 628 methodHandle m(current, missingMethod); 629 LinkResolver::throw_abstract_method_error(m, THREAD); 630 JRT_END 631 632 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* current, 633 Klass* recvKlass, 634 Method* missingMethod)) 635 ResourceMark rm(current); 636 methodHandle mh = methodHandle(current, missingMethod); 637 LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD); 638 JRT_END 639 640 641 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* current)) 642 THROW(vmSymbols::java_lang_IncompatibleClassChangeError()); 643 JRT_END 644 645 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* current, 646 Klass* recvKlass, 647 Klass* interfaceKlass)) 648 ResourceMark rm(current); 649 char buf[1000]; 650 buf[0] = '\0'; 651 jio_snprintf(buf, sizeof(buf), 652 "Class %s does not implement the requested interface %s", 653 recvKlass ? recvKlass->external_name() : "nullptr", 654 interfaceKlass ? interfaceKlass->external_name() : "nullptr"); 655 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf); 656 JRT_END 657 658 JRT_ENTRY(void, InterpreterRuntime::throw_NullPointerException(JavaThread* current)) 659 THROW(vmSymbols::java_lang_NullPointerException()); 660 JRT_END 661 662 //------------------------------------------------------------------------------------------------------------------------ 663 // Fields 664 // 665 666 void InterpreterRuntime::resolve_get_put(JavaThread* current, Bytecodes::Code bytecode) { 667 JavaThread* THREAD = current; 668 LastFrameAccessor last_frame(current); 669 constantPoolHandle pool(current, last_frame.method()->constants()); 670 methodHandle m(current, last_frame.method()); 671 672 resolve_get_put(bytecode, last_frame.get_index_u2(bytecode), m, pool, StaticMode::initialize_klass_preemptable, CHECK_AND_CLEAR_PREEMPTED); 673 } 674 675 void InterpreterRuntime::resolve_get_put(Bytecodes::Code bytecode, int field_index, 676 methodHandle& m, 677 constantPoolHandle& pool, 678 StaticMode static_mode, TRAPS) { 679 fieldDescriptor info; 680 bool is_put = (bytecode == Bytecodes::_putfield || bytecode == Bytecodes::_nofast_putfield || 681 bytecode == Bytecodes::_putstatic); 682 bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic); 683 684 { 685 JvmtiHideSingleStepping jhss(THREAD); 686 LinkResolver::resolve_field_access(info, pool, field_index, 687 m, bytecode, static_mode, CHECK); 688 } // end JvmtiHideSingleStepping 689 690 // check if link resolution caused cpCache to be updated 691 if (pool->resolved_field_entry_at(field_index)->is_resolved(bytecode)) return; 692 693 // compute auxiliary field attributes 694 TosState state = as_TosState(info.field_type()); 695 696 // Resolution of put instructions on final fields is delayed. That is required so that 697 // exceptions are thrown at the correct place (when the instruction is actually invoked). 698 // If we do not resolve an instruction in the current pass, leaving the put_code 699 // set to zero will cause the next put instruction to the same field to reresolve. 700 701 // Resolution of put instructions to final instance fields with invalid updates (i.e., 702 // to final instance fields with updates originating from a method different than <init>) 703 // is inhibited. A putfield instruction targeting an instance final field must throw 704 // an IllegalAccessError if the instruction is not in an instance 705 // initializer method <init>. If resolution were not inhibited, a putfield 706 // in an initializer method could be resolved in the initializer. Subsequent 707 // putfield instructions to the same field would then use cached information. 708 // As a result, those instructions would not pass through the VM. That is, 709 // checks in resolve_field_access() would not be executed for those instructions 710 // and the required IllegalAccessError would not be thrown. 711 // 712 // Also, we need to delay resolving getstatic and putstatic instructions until the 713 // class is initialized. This is required so that access to the static 714 // field will call the initialization function every time until the class 715 // is completely initialized ala. in 2.17.5 in JVM Specification. 716 InstanceKlass* klass = info.field_holder(); 717 bool uninitialized_static = is_static && !klass->is_initialized(); 718 bool has_initialized_final_update = info.field_holder()->major_version() >= 53 && 719 info.has_initialized_final_update(); 720 assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final"); 721 722 Bytecodes::Code get_code = (Bytecodes::Code)0; 723 Bytecodes::Code put_code = (Bytecodes::Code)0; 724 if (!uninitialized_static) { 725 get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield); 726 if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) { 727 put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield); 728 } 729 } 730 731 ResolvedFieldEntry* entry = pool->resolved_field_entry_at(field_index); 732 entry->set_flags(info.access_flags().is_final(), info.access_flags().is_volatile()); 733 entry->fill_in(info.field_holder(), info.offset(), 734 checked_cast<u2>(info.index()), checked_cast<u1>(state), 735 static_cast<u1>(get_code), static_cast<u1>(put_code)); 736 } 737 738 739 //------------------------------------------------------------------------------------------------------------------------ 740 // Synchronization 741 // 742 // The interpreter's synchronization code is factored out so that it can 743 // be shared by method invocation and synchronized blocks. 744 //%note synchronization_3 745 746 //%note monitor_1 747 JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* current, BasicObjectLock* elem)) 748 #ifdef ASSERT 749 current->last_frame().interpreter_frame_verify_monitor(elem); 750 #endif 751 Handle h_obj(current, elem->obj()); 752 assert(Universe::heap()->is_in_or_null(h_obj()), 753 "must be null or an object"); 754 ObjectSynchronizer::enter(h_obj, elem->lock(), current); 755 assert(Universe::heap()->is_in_or_null(elem->obj()), 756 "must be null or an object"); 757 #ifdef ASSERT 758 if (!current->preempting()) current->last_frame().interpreter_frame_verify_monitor(elem); 759 #endif 760 JRT_END 761 762 JRT_LEAF(void, InterpreterRuntime::monitorexit(BasicObjectLock* elem)) 763 oop obj = elem->obj(); 764 assert(Universe::heap()->is_in(obj), "must be an object"); 765 // The object could become unlocked through a JNI call, which we have no other checks for. 766 // Give a fatal message if CheckJNICalls. Otherwise we ignore it. 767 if (obj->is_unlocked()) { 768 if (CheckJNICalls) { 769 fatal("Object has been unlocked by JNI"); 770 } 771 return; 772 } 773 ObjectSynchronizer::exit(obj, elem->lock(), JavaThread::current()); 774 // Free entry. If it is not cleared, the exception handling code will try to unlock the monitor 775 // again at method exit or in the case of an exception. 776 elem->set_obj(nullptr); 777 JRT_END 778 779 780 JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* current)) 781 THROW(vmSymbols::java_lang_IllegalMonitorStateException()); 782 JRT_END 783 784 785 JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* current)) 786 // Returns an illegal exception to install into the current thread. The 787 // pending_exception flag is cleared so normal exception handling does not 788 // trigger. Any current installed exception will be overwritten. This 789 // method will be called during an exception unwind. 790 791 assert(!HAS_PENDING_EXCEPTION, "no pending exception"); 792 Handle exception(current, current->vm_result_oop()); 793 assert(exception() != nullptr, "vm result should be set"); 794 current->set_vm_result_oop(nullptr); // clear vm result before continuing (may cause memory leaks and assert failures) 795 exception = get_preinitialized_exception(vmClasses::IllegalMonitorStateException_klass(), CATCH); 796 current->set_vm_result_oop(exception()); 797 JRT_END 798 799 800 //------------------------------------------------------------------------------------------------------------------------ 801 // Invokes 802 803 JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* current, Method* method, address bcp)) 804 return method->orig_bytecode_at(method->bci_from(bcp)); 805 JRT_END 806 807 JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* current, Method* method, address bcp, Bytecodes::Code new_code)) 808 method->set_orig_bytecode_at(method->bci_from(bcp), new_code); 809 JRT_END 810 811 JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* current, Method* method, address bcp)) 812 JvmtiExport::post_raw_breakpoint(current, method, bcp); 813 JRT_END 814 815 void InterpreterRuntime::resolve_invoke(JavaThread* current, Bytecodes::Code bytecode) { 816 LastFrameAccessor last_frame(current); 817 // extract receiver from the outgoing argument list if necessary 818 Handle receiver(current, nullptr); 819 if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface || 820 bytecode == Bytecodes::_invokespecial) { 821 ResourceMark rm(current); 822 methodHandle m (current, last_frame.method()); 823 Bytecode_invoke call(m, last_frame.bci()); 824 Symbol* signature = call.signature(); 825 receiver = Handle(current, last_frame.callee_receiver(signature)); 826 827 assert(Universe::heap()->is_in_or_null(receiver()), 828 "sanity check"); 829 assert(receiver.is_null() || 830 !Universe::heap()->is_in(receiver->klass()), 831 "sanity check"); 832 } 833 834 // resolve method 835 CallInfo info; 836 constantPoolHandle pool(current, last_frame.method()->constants()); 837 838 methodHandle resolved_method; 839 840 int method_index = last_frame.get_index_u2(bytecode); 841 { ProfileTrapsMark pt(current); 842 JvmtiHideSingleStepping jhss(current); 843 JavaThread* THREAD = current; // For exception macros. 844 LinkResolver::resolve_invoke(info, receiver, pool, 845 method_index, bytecode, 846 StaticMode::initialize_klass_preemptable, CHECK_AND_CLEAR_PREEMPTED); 847 resolved_method = methodHandle(current, info.resolved_method()); 848 ResourceMark rm(THREAD); 849 } // end JvmtiHideSingleStepping 850 851 update_invoke_cp_cache_entry(info, bytecode, resolved_method, pool, method_index); 852 } 853 854 void InterpreterRuntime::update_invoke_cp_cache_entry(CallInfo& info, Bytecodes::Code bytecode, 855 methodHandle& resolved_method, 856 constantPoolHandle& pool, 857 int method_index) { 858 // Don't allow safepoints until the method is cached. 859 NoSafepointVerifier nsv; 860 861 // check if link resolution caused cpCache to be updated 862 ConstantPoolCache* cache = pool->cache(); 863 if (cache->resolved_method_entry_at(method_index)->is_resolved(bytecode)) return; 864 865 #ifdef ASSERT 866 if (bytecode == Bytecodes::_invokeinterface) { 867 if (resolved_method->method_holder() == vmClasses::Object_klass()) { 868 // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec 869 // (see also CallInfo::set_interface for details) 870 assert(info.call_kind() == CallInfo::vtable_call || 871 info.call_kind() == CallInfo::direct_call, ""); 872 assert(resolved_method->is_final() || info.has_vtable_index(), 873 "should have been set already"); 874 } else if (!resolved_method->has_itable_index()) { 875 // Resolved something like CharSequence.toString. Use vtable not itable. 876 assert(info.call_kind() != CallInfo::itable_call, ""); 877 } else { 878 // Setup itable entry 879 assert(info.call_kind() == CallInfo::itable_call, ""); 880 int index = resolved_method->itable_index(); 881 assert(info.itable_index() == index, ""); 882 } 883 } else if (bytecode == Bytecodes::_invokespecial) { 884 assert(info.call_kind() == CallInfo::direct_call, "must be direct call"); 885 } else { 886 assert(info.call_kind() == CallInfo::direct_call || 887 info.call_kind() == CallInfo::vtable_call, ""); 888 } 889 #endif 890 // Get sender and only set cpCache entry to resolved if it is not an 891 // interface. The receiver for invokespecial calls within interface 892 // methods must be checked for every call. 893 InstanceKlass* sender = pool->pool_holder(); 894 895 switch (info.call_kind()) { 896 case CallInfo::direct_call: 897 cache->set_direct_call(bytecode, method_index, resolved_method, sender->is_interface()); 898 break; 899 case CallInfo::vtable_call: 900 cache->set_vtable_call(bytecode, method_index, resolved_method, info.vtable_index()); 901 break; 902 case CallInfo::itable_call: 903 cache->set_itable_call( 904 bytecode, 905 method_index, 906 info.resolved_klass(), 907 resolved_method, 908 info.itable_index()); 909 break; 910 default: ShouldNotReachHere(); 911 } 912 } 913 914 void InterpreterRuntime::cds_resolve_invoke(Bytecodes::Code bytecode, int method_index, 915 constantPoolHandle& pool, TRAPS) { 916 LinkInfo link_info(pool, method_index, bytecode, CHECK); 917 918 if (!link_info.resolved_klass()->is_instance_klass() || InstanceKlass::cast(link_info.resolved_klass())->is_linked()) { 919 CallInfo call_info; 920 switch (bytecode) { 921 case Bytecodes::_invokevirtual: LinkResolver::cds_resolve_virtual_call (call_info, link_info, CHECK); break; 922 case Bytecodes::_invokeinterface: LinkResolver::cds_resolve_interface_call(call_info, link_info, CHECK); break; 923 case Bytecodes::_invokespecial: LinkResolver::cds_resolve_special_call (call_info, link_info, CHECK); break; 924 925 default: fatal("Unimplemented: %s", Bytecodes::name(bytecode)); 926 } 927 methodHandle resolved_method(THREAD, call_info.resolved_method()); 928 guarantee(resolved_method->method_holder()->is_linked(), ""); 929 update_invoke_cp_cache_entry(call_info, bytecode, resolved_method, pool, method_index); 930 } else { 931 // FIXME: why a shared class is not linked yet? 932 // Can't link it here since there are no guarantees it'll be prelinked on the next run. 933 ResourceMark rm; 934 InstanceKlass* resolved_iklass = InstanceKlass::cast(link_info.resolved_klass()); 935 log_info(aot, resolve)("Not resolved: class not linked: %s %s %s", 936 resolved_iklass->is_shared() ? "is_shared" : "", 937 resolved_iklass->init_state_name(), 938 resolved_iklass->external_name()); 939 } 940 } 941 942 // First time execution: Resolve symbols, create a permanent MethodType object. 943 void InterpreterRuntime::resolve_invokehandle(JavaThread* current) { 944 const Bytecodes::Code bytecode = Bytecodes::_invokehandle; 945 LastFrameAccessor last_frame(current); 946 947 // resolve method 948 CallInfo info; 949 constantPoolHandle pool(current, last_frame.method()->constants()); 950 int method_index = last_frame.get_index_u2(bytecode); 951 { 952 JvmtiHideSingleStepping jhss(current); 953 JavaThread* THREAD = current; // For exception macros. 954 LinkResolver::resolve_invoke(info, Handle(), pool, 955 method_index, bytecode, 956 CHECK); 957 } // end JvmtiHideSingleStepping 958 959 pool->cache()->set_method_handle(method_index, info); 960 } 961 962 void InterpreterRuntime::cds_resolve_invokehandle(int raw_index, 963 constantPoolHandle& pool, TRAPS) { 964 const Bytecodes::Code bytecode = Bytecodes::_invokehandle; 965 CallInfo info; 966 LinkResolver::resolve_invoke(info, Handle(), pool, raw_index, bytecode, CHECK); 967 968 pool->cache()->set_method_handle(raw_index, info); 969 } 970 971 // First time execution: Resolve symbols, create a permanent CallSite object. 972 void InterpreterRuntime::resolve_invokedynamic(JavaThread* current) { 973 LastFrameAccessor last_frame(current); 974 const Bytecodes::Code bytecode = Bytecodes::_invokedynamic; 975 976 // resolve method 977 CallInfo info; 978 constantPoolHandle pool(current, last_frame.method()->constants()); 979 int index = last_frame.get_index_u4(bytecode); 980 { 981 JvmtiHideSingleStepping jhss(current); 982 JavaThread* THREAD = current; // For exception macros. 983 LinkResolver::resolve_invoke(info, Handle(), pool, 984 index, bytecode, CHECK); 985 } // end JvmtiHideSingleStepping 986 987 pool->cache()->set_dynamic_call(info, index); 988 } 989 990 void InterpreterRuntime::cds_resolve_invokedynamic(int raw_index, 991 constantPoolHandle& pool, TRAPS) { 992 const Bytecodes::Code bytecode = Bytecodes::_invokedynamic; 993 CallInfo info; 994 LinkResolver::resolve_invoke(info, Handle(), pool, raw_index, bytecode, CHECK); 995 pool->cache()->set_dynamic_call(info, raw_index); 996 } 997 998 // This function is the interface to the assembly code. It returns the resolved 999 // cpCache entry. This doesn't safepoint, but the helper routines safepoint. 1000 // This function will check for redefinition! 1001 JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* current, Bytecodes::Code bytecode)) { 1002 switch (bytecode) { 1003 case Bytecodes::_getstatic: 1004 case Bytecodes::_putstatic: 1005 case Bytecodes::_getfield: 1006 case Bytecodes::_putfield: 1007 resolve_get_put(current, bytecode); 1008 break; 1009 case Bytecodes::_invokevirtual: 1010 case Bytecodes::_invokespecial: 1011 case Bytecodes::_invokestatic: 1012 case Bytecodes::_invokeinterface: 1013 resolve_invoke(current, bytecode); 1014 break; 1015 case Bytecodes::_invokehandle: 1016 resolve_invokehandle(current); 1017 break; 1018 case Bytecodes::_invokedynamic: 1019 resolve_invokedynamic(current); 1020 break; 1021 default: 1022 fatal("unexpected bytecode: %s", Bytecodes::name(bytecode)); 1023 break; 1024 } 1025 } 1026 JRT_END 1027 1028 //------------------------------------------------------------------------------------------------------------------------ 1029 // Miscellaneous 1030 1031 1032 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* current, address branch_bcp) { 1033 // Enable WXWrite: the function is called directly by interpreter. 1034 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current)); 1035 1036 // frequency_counter_overflow_inner can throw async exception. 1037 nmethod* nm = frequency_counter_overflow_inner(current, branch_bcp); 1038 assert(branch_bcp != nullptr || nm == nullptr, "always returns null for non OSR requests"); 1039 if (branch_bcp != nullptr && nm != nullptr) { 1040 // This was a successful request for an OSR nmethod. Because 1041 // frequency_counter_overflow_inner ends with a safepoint check, 1042 // nm could have been unloaded so look it up again. It's unsafe 1043 // to examine nm directly since it might have been freed and used 1044 // for something else. 1045 LastFrameAccessor last_frame(current); 1046 Method* method = last_frame.method(); 1047 int bci = method->bci_from(last_frame.bcp()); 1048 nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false); 1049 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1050 if (nm != nullptr) { 1051 // in case the transition passed a safepoint we need to barrier this again 1052 if (!bs_nm->nmethod_osr_entry_barrier(nm)) { 1053 nm = nullptr; 1054 } 1055 } 1056 } 1057 if (nm != nullptr && current->is_interp_only_mode()) { 1058 // Normally we never get an nm if is_interp_only_mode() is true, because 1059 // policy()->event has a check for this and won't compile the method when 1060 // true. However, it's possible for is_interp_only_mode() to become true 1061 // during the compilation. We don't want to return the nm in that case 1062 // because we want to continue to execute interpreted. 1063 nm = nullptr; 1064 } 1065 #ifndef PRODUCT 1066 if (TraceOnStackReplacement) { 1067 if (nm != nullptr) { 1068 tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry())); 1069 nm->print(); 1070 } 1071 } 1072 #endif 1073 return nm; 1074 } 1075 1076 JRT_ENTRY(nmethod*, 1077 InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* current, address branch_bcp)) 1078 // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized 1079 // flag, in case this method triggers classloading which will call into Java. 1080 UnlockFlagSaver fs(current); 1081 1082 LastFrameAccessor last_frame(current); 1083 assert(last_frame.is_interpreted_frame(), "must come from interpreter"); 1084 methodHandle method(current, last_frame.method()); 1085 const int branch_bci = branch_bcp != nullptr ? method->bci_from(branch_bcp) : InvocationEntryBci; 1086 const int bci = branch_bcp != nullptr ? method->bci_from(last_frame.bcp()) : InvocationEntryBci; 1087 1088 nmethod* osr_nm = CompilationPolicy::event(method, method, branch_bci, bci, CompLevel_none, nullptr, CHECK_NULL); 1089 1090 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod(); 1091 if (osr_nm != nullptr) { 1092 if (!bs_nm->nmethod_osr_entry_barrier(osr_nm)) { 1093 osr_nm = nullptr; 1094 } 1095 } 1096 return osr_nm; 1097 JRT_END 1098 1099 JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp)) 1100 assert(ProfileInterpreter, "must be profiling interpreter"); 1101 int bci = method->bci_from(cur_bcp); 1102 MethodData* mdo = method->method_data(); 1103 if (mdo == nullptr) return 0; 1104 return mdo->bci_to_di(bci); 1105 JRT_END 1106 1107 #ifdef ASSERT 1108 JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp)) 1109 assert(ProfileInterpreter, "must be profiling interpreter"); 1110 1111 MethodData* mdo = method->method_data(); 1112 assert(mdo != nullptr, "must not be null"); 1113 1114 int bci = method->bci_from(bcp); 1115 1116 address mdp2 = mdo->bci_to_dp(bci); 1117 if (mdp != mdp2) { 1118 ResourceMark rm; 1119 tty->print_cr("FAILED verify : actual mdp %p expected mdp %p @ bci %d", mdp, mdp2, bci); 1120 int current_di = mdo->dp_to_di(mdp); 1121 int expected_di = mdo->dp_to_di(mdp2); 1122 tty->print_cr(" actual di %d expected di %d", current_di, expected_di); 1123 int expected_approx_bci = mdo->data_at(expected_di)->bci(); 1124 int approx_bci = -1; 1125 if (current_di >= 0) { 1126 approx_bci = mdo->data_at(current_di)->bci(); 1127 } 1128 tty->print_cr(" actual bci is %d expected bci %d", approx_bci, expected_approx_bci); 1129 mdo->print_on(tty); 1130 method->print_codes(); 1131 } 1132 assert(mdp == mdp2, "wrong mdp"); 1133 JRT_END 1134 #endif // ASSERT 1135 1136 JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* current, int return_bci)) 1137 assert(ProfileInterpreter, "must be profiling interpreter"); 1138 ResourceMark rm(current); 1139 LastFrameAccessor last_frame(current); 1140 assert(last_frame.is_interpreted_frame(), "must come from interpreter"); 1141 MethodData* h_mdo = last_frame.method()->method_data(); 1142 1143 // Grab a lock to ensure atomic access to setting the return bci and 1144 // the displacement. This can block and GC, invalidating all naked oops. 1145 MutexLocker ml(RetData_lock); 1146 1147 // ProfileData is essentially a wrapper around a derived oop, so we 1148 // need to take the lock before making any ProfileData structures. 1149 ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp())); 1150 guarantee(data != nullptr, "profile data must be valid"); 1151 RetData* rdata = data->as_RetData(); 1152 address new_mdp = rdata->fixup_ret(return_bci, h_mdo); 1153 last_frame.set_mdp(new_mdp); 1154 JRT_END 1155 1156 JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* current, Method* m)) 1157 return Method::build_method_counters(current, m); 1158 JRT_END 1159 1160 1161 JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* current)) 1162 // We used to need an explicit preserve_arguments here for invoke bytecodes. However, 1163 // stack traversal automatically takes care of preserving arguments for invoke, so 1164 // this is no longer needed. 1165 1166 // JRT_END does an implicit safepoint check, hence we are guaranteed to block 1167 // if this is called during a safepoint 1168 1169 if (JvmtiExport::should_post_single_step()) { 1170 // This function is called by the interpreter when single stepping. Such single 1171 // stepping could unwind a frame. Then, it is important that we process any frames 1172 // that we might return into. 1173 StackWatermarkSet::before_unwind(current); 1174 1175 // We are called during regular safepoints and when the VM is 1176 // single stepping. If any thread is marked for single stepping, 1177 // then we may have JVMTI work to do. 1178 LastFrameAccessor last_frame(current); 1179 JvmtiExport::at_single_stepping_point(current, last_frame.method(), last_frame.bcp()); 1180 } 1181 JRT_END 1182 1183 JRT_LEAF(void, InterpreterRuntime::at_unwind(JavaThread* current)) 1184 assert(current == JavaThread::current(), "pre-condition"); 1185 JFR_ONLY(Jfr::check_and_process_sample_request(current);) 1186 // This function is called by the interpreter when the return poll found a reason 1187 // to call the VM. The reason could be that we are returning into a not yet safe 1188 // to access frame. We handle that below. 1189 // Note that this path does not check for single stepping, because we do not want 1190 // to single step when unwinding frames for an exception being thrown. Instead, 1191 // such single stepping code will use the safepoint table, which will use the 1192 // InterpreterRuntime::at_safepoint callback. 1193 StackWatermarkSet::before_unwind(current); 1194 JRT_END 1195 1196 JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread* current, oopDesc* obj, 1197 ResolvedFieldEntry *entry)) 1198 1199 // check the access_flags for the field in the klass 1200 1201 InstanceKlass* ik = entry->field_holder(); 1202 int index = entry->field_index(); 1203 if (!ik->field_status(index).is_access_watched()) return; 1204 1205 bool is_static = (obj == nullptr); 1206 HandleMark hm(current); 1207 1208 Handle h_obj; 1209 if (!is_static) { 1210 // non-static field accessors have an object, but we need a handle 1211 h_obj = Handle(current, obj); 1212 } 1213 InstanceKlass* field_holder = entry->field_holder(); // HERE 1214 jfieldID fid = jfieldIDWorkaround::to_jfieldID(field_holder, entry->field_offset(), is_static); 1215 LastFrameAccessor last_frame(current); 1216 JvmtiExport::post_field_access(current, last_frame.method(), last_frame.bcp(), field_holder, h_obj, fid); 1217 JRT_END 1218 1219 JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread* current, oopDesc* obj, 1220 ResolvedFieldEntry *entry, jvalue *value)) 1221 1222 InstanceKlass* ik = entry->field_holder(); 1223 1224 // check the access_flags for the field in the klass 1225 int index = entry->field_index(); 1226 // bail out if field modifications are not watched 1227 if (!ik->field_status(index).is_modification_watched()) return; 1228 1229 char sig_type = '\0'; 1230 1231 switch((TosState)entry->tos_state()) { 1232 case btos: sig_type = JVM_SIGNATURE_BYTE; break; 1233 case ztos: sig_type = JVM_SIGNATURE_BOOLEAN; break; 1234 case ctos: sig_type = JVM_SIGNATURE_CHAR; break; 1235 case stos: sig_type = JVM_SIGNATURE_SHORT; break; 1236 case itos: sig_type = JVM_SIGNATURE_INT; break; 1237 case ftos: sig_type = JVM_SIGNATURE_FLOAT; break; 1238 case atos: sig_type = JVM_SIGNATURE_CLASS; break; 1239 case ltos: sig_type = JVM_SIGNATURE_LONG; break; 1240 case dtos: sig_type = JVM_SIGNATURE_DOUBLE; break; 1241 default: ShouldNotReachHere(); return; 1242 } 1243 bool is_static = (obj == nullptr); 1244 1245 HandleMark hm(current); 1246 jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, entry->field_offset(), is_static); 1247 jvalue fvalue; 1248 #ifdef _LP64 1249 fvalue = *value; 1250 #else 1251 // Long/double values are stored unaligned and also noncontiguously with 1252 // tagged stacks. We can't just do a simple assignment even in the non- 1253 // J/D cases because a C++ compiler is allowed to assume that a jvalue is 1254 // 8-byte aligned, and interpreter stack slots are only 4-byte aligned. 1255 // We assume that the two halves of longs/doubles are stored in interpreter 1256 // stack slots in platform-endian order. 1257 jlong_accessor u; 1258 jint* newval = (jint*)value; 1259 u.words[0] = newval[0]; 1260 u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag 1261 fvalue.j = u.long_value; 1262 #endif // _LP64 1263 1264 Handle h_obj; 1265 if (!is_static) { 1266 // non-static field accessors have an object, but we need a handle 1267 h_obj = Handle(current, obj); 1268 } 1269 1270 LastFrameAccessor last_frame(current); 1271 JvmtiExport::post_raw_field_modification(current, last_frame.method(), last_frame.bcp(), ik, h_obj, 1272 fid, sig_type, &fvalue); 1273 JRT_END 1274 1275 JRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread* current)) 1276 LastFrameAccessor last_frame(current); 1277 JvmtiExport::post_method_entry(current, last_frame.method(), last_frame.get_frame()); 1278 JRT_END 1279 1280 1281 // This is a JRT_BLOCK_ENTRY because we have to stash away the return oop 1282 // before transitioning to VM, and restore it after transitioning back 1283 // to Java. The return oop at the top-of-stack, is not walked by the GC. 1284 JRT_BLOCK_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread* current)) 1285 LastFrameAccessor last_frame(current); 1286 JvmtiExport::post_method_exit(current, last_frame.method(), last_frame.get_frame()); 1287 JRT_END 1288 1289 JRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc)) 1290 { 1291 return (Interpreter::contains(Continuation::get_top_return_pc_post_barrier(JavaThread::current(), pc)) ? 1 : 0); 1292 } 1293 JRT_END 1294 1295 1296 // Implementation of SignatureHandlerLibrary 1297 1298 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS 1299 // Dummy definition (else normalization method is defined in CPU 1300 // dependent code) 1301 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) { 1302 return fingerprint; 1303 } 1304 #endif 1305 1306 address SignatureHandlerLibrary::set_handler_blob() { 1307 BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size); 1308 if (handler_blob == nullptr) { 1309 return nullptr; 1310 } 1311 address handler = handler_blob->code_begin(); 1312 _handler_blob = handler_blob; 1313 _handler = handler; 1314 return handler; 1315 } 1316 1317 void SignatureHandlerLibrary::initialize() { 1318 if (_fingerprints != nullptr) { 1319 return; 1320 } 1321 if (set_handler_blob() == nullptr) { 1322 vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers"); 1323 } 1324 1325 BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer", 1326 SignatureHandlerLibrary::buffer_size); 1327 _buffer = bb->code_begin(); 1328 1329 _fingerprints = new (mtCode) GrowableArray<uint64_t>(32, mtCode); 1330 _handlers = new (mtCode) GrowableArray<address>(32, mtCode); 1331 } 1332 1333 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) { 1334 address handler = _handler; 1335 int insts_size = buffer->pure_insts_size(); 1336 if (handler + insts_size > _handler_blob->code_end()) { 1337 // get a new handler blob 1338 handler = set_handler_blob(); 1339 } 1340 if (handler != nullptr) { 1341 memcpy(handler, buffer->insts_begin(), insts_size); 1342 pd_set_handler(handler); 1343 ICache::invalidate_range(handler, insts_size); 1344 _handler = handler + insts_size; 1345 } 1346 return handler; 1347 } 1348 1349 void SignatureHandlerLibrary::add(const methodHandle& method) { 1350 if (method->signature_handler() == nullptr) { 1351 // use slow signature handler if we can't do better 1352 int handler_index = -1; 1353 // check if we can use customized (fast) signature handler 1354 if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::fp_max_size_of_parameters) { 1355 // use customized signature handler 1356 MutexLocker mu(SignatureHandlerLibrary_lock); 1357 // make sure data structure is initialized 1358 initialize(); 1359 // lookup method signature's fingerprint 1360 uint64_t fingerprint = Fingerprinter(method).fingerprint(); 1361 // allow CPU dependent code to optimize the fingerprints for the fast handler 1362 fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint); 1363 handler_index = _fingerprints->find(fingerprint); 1364 // create handler if necessary 1365 if (handler_index < 0) { 1366 ResourceMark rm; 1367 ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer; 1368 CodeBuffer buffer((address)(_buffer + align_offset), 1369 checked_cast<int>(SignatureHandlerLibrary::buffer_size - align_offset)); 1370 InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint); 1371 // copy into code heap 1372 address handler = set_handler(&buffer); 1373 if (handler == nullptr) { 1374 // use slow signature handler (without memorizing it in the fingerprints) 1375 } else { 1376 // debugging support 1377 if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) { 1378 ttyLocker ttyl; 1379 tty->cr(); 1380 tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)", 1381 _handlers->length(), 1382 (method->is_static() ? "static" : "receiver"), 1383 method->name_and_sig_as_C_string(), 1384 fingerprint, 1385 buffer.insts_size()); 1386 if (buffer.insts_size() > 0) { 1387 Disassembler::decode(handler, handler + buffer.insts_size(), tty 1388 NOT_PRODUCT(COMMA &buffer.asm_remarks())); 1389 } 1390 #ifndef PRODUCT 1391 address rh_begin = Interpreter::result_handler(method()->result_type()); 1392 if (CodeCache::contains(rh_begin)) { 1393 // else it might be special platform dependent values 1394 tty->print_cr(" --- associated result handler ---"); 1395 address rh_end = rh_begin; 1396 while (*(int*)rh_end != 0) { 1397 rh_end += sizeof(int); 1398 } 1399 Disassembler::decode(rh_begin, rh_end); 1400 } else { 1401 tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin)); 1402 } 1403 #endif 1404 } 1405 // add handler to library 1406 _fingerprints->append(fingerprint); 1407 _handlers->append(handler); 1408 // set handler index 1409 assert(_fingerprints->length() == _handlers->length(), "sanity check"); 1410 handler_index = _fingerprints->length() - 1; 1411 } 1412 } 1413 // Set handler under SignatureHandlerLibrary_lock 1414 if (handler_index < 0) { 1415 // use generic signature handler 1416 method->set_signature_handler(Interpreter::slow_signature_handler()); 1417 } else { 1418 // set handler 1419 method->set_signature_handler(_handlers->at(handler_index)); 1420 } 1421 } else { 1422 DEBUG_ONLY(JavaThread::current()->check_possible_safepoint()); 1423 // use generic signature handler 1424 method->set_signature_handler(Interpreter::slow_signature_handler()); 1425 } 1426 } 1427 #ifdef ASSERT 1428 int handler_index = -1; 1429 int fingerprint_index = -2; 1430 { 1431 // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized 1432 // in any way if accessed from multiple threads. To avoid races with another 1433 // thread which may change the arrays in the above, mutex protected block, we 1434 // have to protect this read access here with the same mutex as well! 1435 MutexLocker mu(SignatureHandlerLibrary_lock); 1436 if (_handlers != nullptr) { 1437 handler_index = _handlers->find(method->signature_handler()); 1438 uint64_t fingerprint = Fingerprinter(method).fingerprint(); 1439 fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint); 1440 fingerprint_index = _fingerprints->find(fingerprint); 1441 } 1442 } 1443 assert(method->signature_handler() == Interpreter::slow_signature_handler() || 1444 handler_index == fingerprint_index, "sanity check"); 1445 #endif // ASSERT 1446 } 1447 1448 BufferBlob* SignatureHandlerLibrary::_handler_blob = nullptr; 1449 address SignatureHandlerLibrary::_handler = nullptr; 1450 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = nullptr; 1451 GrowableArray<address>* SignatureHandlerLibrary::_handlers = nullptr; 1452 address SignatureHandlerLibrary::_buffer = nullptr; 1453 1454 1455 JRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* current, Method* method)) 1456 methodHandle m(current, method); 1457 assert(m->is_native(), "sanity check"); 1458 // lookup native function entry point if it doesn't exist 1459 if (!m->has_native_function()) { 1460 NativeLookup::lookup(m, CHECK); 1461 } 1462 // make sure signature handler is installed 1463 SignatureHandlerLibrary::add(m); 1464 // The interpreter entry point checks the signature handler first, 1465 // before trying to fetch the native entry point and klass mirror. 1466 // We must set the signature handler last, so that multiple processors 1467 // preparing the same method will be sure to see non-null entry & mirror. 1468 JRT_END 1469 1470 #if defined(IA32) || defined(AMD64) || defined(ARM) 1471 JRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* current, void* src_address, void* dest_address)) 1472 assert(current == JavaThread::current(), "pre-condition"); 1473 if (src_address == dest_address) { 1474 return; 1475 } 1476 ResourceMark rm; 1477 LastFrameAccessor last_frame(current); 1478 assert(last_frame.is_interpreted_frame(), ""); 1479 jint bci = last_frame.bci(); 1480 methodHandle mh(current, last_frame.method()); 1481 Bytecode_invoke invoke(mh, bci); 1482 ArgumentSizeComputer asc(invoke.signature()); 1483 int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver 1484 Copy::conjoint_jbytes(src_address, dest_address, 1485 size_of_arguments * Interpreter::stackElementSize); 1486 JRT_END 1487 #endif 1488 1489 #if INCLUDE_JVMTI 1490 // This is a support of the JVMTI PopFrame interface. 1491 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument 1492 // and return it as a vm_result_oop so that it can be reloaded in the list of invokestatic parameters. 1493 // The member_name argument is a saved reference (in local#0) to the member_name. 1494 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle. 1495 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated. 1496 JRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* current, address member_name, 1497 Method* method, address bcp)) 1498 Bytecodes::Code code = Bytecodes::code_at(method, bcp); 1499 if (code != Bytecodes::_invokestatic) { 1500 return; 1501 } 1502 ConstantPool* cpool = method->constants(); 1503 int cp_index = Bytes::get_native_u2(bcp + 1); 1504 Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index, code)); 1505 Symbol* mname = cpool->name_ref_at(cp_index, code); 1506 1507 if (MethodHandles::has_member_arg(cname, mname)) { 1508 oop member_name_oop = cast_to_oop(member_name); 1509 if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) { 1510 // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated. 1511 member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop); 1512 } 1513 current->set_vm_result_oop(member_name_oop); 1514 } else { 1515 current->set_vm_result_oop(nullptr); 1516 } 1517 JRT_END 1518 #endif // INCLUDE_JVMTI 1519 1520 #ifndef PRODUCT 1521 // This must be a JRT_LEAF function because the interpreter must save registers on x86 to 1522 // call this, which changes rsp and makes the interpreter's expression stack not walkable. 1523 // The generated code still uses call_VM because that will set up the frame pointer for 1524 // bcp and method. 1525 JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* current, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2)) 1526 assert(current == JavaThread::current(), "pre-condition"); 1527 LastFrameAccessor last_frame(current); 1528 assert(last_frame.is_interpreted_frame(), "must be an interpreted frame"); 1529 methodHandle mh(current, last_frame.method()); 1530 BytecodeTracer::trace_interpreter(mh, last_frame.bcp(), tos, tos2); 1531 return preserve_this_value; 1532 JRT_END 1533 #endif // !PRODUCT