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