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