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