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