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