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::aconst_init(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, aconst_init will just return null instead of throwing an exception
 262     THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 263   }
 264   assert(k->is_inline_klass(), "aconst_init 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, an 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 initialize 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_h()->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     if (s == vmSymbols::java_lang_ArrayStoreException()) {
 661       note_trap(current, Deoptimization::Reason_array_check);
 662     } else {
 663       note_trap(current, Deoptimization::Reason_class_check);
 664     }
 665   }
 666   // create exception, with klass name as detail message
 667   Handle exception = Exceptions::new_exception(current, s, klass_name);
 668   current->set_vm_result(exception());
 669 JRT_END
 670 
 671 JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* current, arrayOopDesc* a, jint index))
 672   // Produce the error message first because note_trap can safepoint
 673   ResourceMark rm(current);
 674   stringStream ss;
 675   ss.print("Index %d out of bounds for length %d", index, a->length());
 676 
 677   if (ProfileTraps) {
 678     note_trap(current, Deoptimization::Reason_range_check);
 679   }
 680 
 681   THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
 682 JRT_END
 683 
 684 JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 685   JavaThread* current, oopDesc* obj))
 686 
 687   // Produce the error message first because note_trap can safepoint
 688   ResourceMark rm(current);
 689   char* message = SharedRuntime::generate_class_cast_message(
 690     current, obj->klass());
 691 
 692   if (ProfileTraps) {
 693     note_trap(current, Deoptimization::Reason_class_check);
 694   }
 695 
 696   // create exception
 697   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 698 JRT_END
 699 
 700 // exception_handler_for_exception(...) returns the continuation address,
 701 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 702 // The exception oop is returned to make sure it is preserved over GC (it
 703 // is only on the stack if the exception was thrown explicitly via athrow).
 704 // During this operation, the expression stack contains the values for the
 705 // bci where the exception happened. If the exception was propagated back
 706 // from a call, the expression stack contains the values for the bci at the
 707 // invoke w/o arguments (i.e., as if one were inside the call).
 708 JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* current, oopDesc* exception))
 709   // We get here after we have unwound from a callee throwing an exception
 710   // into the interpreter. Any deferred stack processing is notified of
 711   // the event via the StackWatermarkSet.
 712   StackWatermarkSet::after_unwind(current);
 713 
 714   LastFrameAccessor last_frame(current);
 715   Handle             h_exception(current, exception);
 716   methodHandle       h_method   (current, last_frame.method());
 717   constantPoolHandle h_constants(current, h_method->constants());
 718   bool               should_repeat;
 719   int                handler_bci;
 720   int                current_bci = last_frame.bci();
 721 
 722   if (current->frames_to_pop_failed_realloc() > 0) {
 723     // Allocation of scalar replaced object used in this frame
 724     // failed. Unconditionally pop the frame.
 725     current->dec_frames_to_pop_failed_realloc();
 726     current->set_vm_result(h_exception());
 727     // If the method is synchronized we already unlocked the monitor
 728     // during deoptimization so the interpreter needs to skip it when
 729     // the frame is popped.
 730     current->set_do_not_unlock_if_synchronized(true);
 731     return Interpreter::remove_activation_entry();
 732   }
 733 
 734   // Need to do this check first since when _do_not_unlock_if_synchronized
 735   // is set, we don't want to trigger any classloading which may make calls
 736   // into java, or surprisingly find a matching exception handler for bci 0
 737   // since at this moment the method hasn't been "officially" entered yet.
 738   if (current->do_not_unlock_if_synchronized()) {
 739     ResourceMark rm;
 740     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 741     current->set_vm_result(exception);
 742     return Interpreter::remove_activation_entry();
 743   }
 744 
 745   do {
 746     should_repeat = false;
 747 
 748     // assertions
 749     assert(h_exception.not_null(), "NULL exceptions should be handled by athrow");
 750     // Check that exception is a subclass of Throwable.
 751     assert(h_exception->is_a(vmClasses::Throwable_klass()),
 752            "Exception not subclass of Throwable");
 753 
 754     // tracing
 755     if (log_is_enabled(Info, exceptions)) {
 756       ResourceMark rm(current);
 757       stringStream tempst;
 758       tempst.print("interpreter method <%s>\n"
 759                    " at bci %d for thread " INTPTR_FORMAT " (%s)",
 760                    h_method->print_value_string(), current_bci, p2i(current), current->name());
 761       Exceptions::log_exception(h_exception, tempst.as_string());
 762     }
 763 // Don't go paging in something which won't be used.
 764 //     else if (extable->length() == 0) {
 765 //       // disabled for now - interpreter is not using shortcut yet
 766 //       // (shortcut is not to call runtime if we have no exception handlers)
 767 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 768 //     }
 769     // for AbortVMOnException flag
 770     Exceptions::debug_check_abort(h_exception);
 771 
 772     // exception handler lookup
 773     Klass* klass = h_exception->klass();
 774     handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD);
 775     if (HAS_PENDING_EXCEPTION) {
 776       // We threw an exception while trying to find the exception handler.
 777       // Transfer the new exception to the exception handle which will
 778       // be set into thread local storage, and do another lookup for an
 779       // exception handler for this exception, this time starting at the
 780       // BCI of the exception handler which caused the exception to be
 781       // thrown (bug 4307310).
 782       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 783       CLEAR_PENDING_EXCEPTION;
 784       if (handler_bci >= 0) {
 785         current_bci = handler_bci;
 786         should_repeat = true;
 787       }
 788     }
 789   } while (should_repeat == true);
 790 
 791 #if INCLUDE_JVMCI
 792   if (EnableJVMCI && h_method->method_data() != NULL) {
 793     ResourceMark rm(current);
 794     ProfileData* pdata = h_method->method_data()->allocate_bci_to_data(current_bci, NULL);
 795     if (pdata != NULL && pdata->is_BitData()) {
 796       BitData* bit_data = (BitData*) pdata;
 797       bit_data->set_exception_seen();
 798     }
 799   }
 800 #endif
 801 
 802   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 803   // time throw or a stack unwinding throw and accordingly notify the debugger
 804   if (JvmtiExport::can_post_on_exceptions()) {
 805     JvmtiExport::post_exception_throw(current, h_method(), last_frame.bcp(), h_exception());
 806   }
 807 
 808   address continuation = NULL;
 809   address handler_pc = NULL;
 810   if (handler_bci < 0 || !current->stack_overflow_state()->reguard_stack((address) &continuation)) {
 811     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 812     // handler in this method, or (b) after a stack overflow there is not yet
 813     // enough stack space available to reprotect the stack.
 814     continuation = Interpreter::remove_activation_entry();
 815 #if COMPILER2_OR_JVMCI
 816     // Count this for compilation purposes
 817     h_method->interpreter_throwout_increment(THREAD);
 818 #endif
 819   } else {
 820     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 821     handler_pc = h_method->code_base() + handler_bci;
 822 #ifndef ZERO
 823     set_bcp_and_mdp(handler_pc, current);
 824     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 825 #else
 826     continuation = (address)(intptr_t) handler_bci;
 827 #endif
 828   }
 829 
 830   // notify debugger of an exception catch
 831   // (this is good for exceptions caught in native methods as well)
 832   if (JvmtiExport::can_post_on_exceptions()) {
 833     JvmtiExport::notice_unwind_due_to_exception(current, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
 834   }
 835 
 836   current->set_vm_result(h_exception());
 837   return continuation;
 838 JRT_END
 839 
 840 
 841 JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* current))
 842   assert(current->has_pending_exception(), "must only be called if there's an exception pending");
 843   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 844 JRT_END
 845 
 846 
 847 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* current))
 848   THROW(vmSymbols::java_lang_AbstractMethodError());
 849 JRT_END
 850 
 851 // This method is called from the "abstract_entry" of the interpreter.
 852 // At that point, the arguments have already been removed from the stack
 853 // and therefore we don't have the receiver object at our fingertips. (Though,
 854 // on some platforms the receiver still resides in a register...). Thus,
 855 // we have no choice but print an error message not containing the receiver
 856 // type.
 857 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* current,
 858                                                                         Method* missingMethod))
 859   ResourceMark rm(current);
 860   assert(missingMethod != NULL, "sanity");
 861   methodHandle m(current, missingMethod);
 862   LinkResolver::throw_abstract_method_error(m, THREAD);
 863 JRT_END
 864 
 865 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* current,
 866                                                                      Klass* recvKlass,
 867                                                                      Method* missingMethod))
 868   ResourceMark rm(current);
 869   methodHandle mh = methodHandle(current, missingMethod);
 870   LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD);
 871 JRT_END
 872 
 873 JRT_ENTRY(void, InterpreterRuntime::throw_InstantiationError(JavaThread* current))
 874   THROW(vmSymbols::java_lang_InstantiationError());
 875 JRT_END
 876 
 877 
 878 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 879   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 880 JRT_END
 881 
 882 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* current,
 883                                                                               Klass* recvKlass,
 884                                                                               Klass* interfaceKlass))
 885   ResourceMark rm(current);
 886   char buf[1000];
 887   buf[0] = '\0';
 888   jio_snprintf(buf, sizeof(buf),
 889                "Class %s does not implement the requested interface %s",
 890                recvKlass ? recvKlass->external_name() : "NULL",
 891                interfaceKlass ? interfaceKlass->external_name() : "NULL");
 892   THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 893 JRT_END
 894 
 895 JRT_ENTRY(void, InterpreterRuntime::throw_NullPointerException(JavaThread* current))
 896   THROW(vmSymbols::java_lang_NullPointerException());
 897 JRT_END
 898 
 899 //------------------------------------------------------------------------------------------------------------------------
 900 // Fields
 901 //
 902 
 903 void InterpreterRuntime::resolve_get_put(JavaThread* current, Bytecodes::Code bytecode) {
 904   // resolve field
 905   fieldDescriptor info;
 906   LastFrameAccessor last_frame(current);
 907   constantPoolHandle pool(current, last_frame.method()->constants());
 908   methodHandle m(current, last_frame.method());
 909   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
 910                     bytecode == Bytecodes::_putstatic || bytecode == Bytecodes::_withfield);
 911   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 912   bool is_inline_type  = bytecode == Bytecodes::_withfield;
 913 
 914   {
 915     JvmtiHideSingleStepping jhss(current);
 916     JavaThread* THREAD = current; // For exception macros.
 917     LinkResolver::resolve_field_access(info, pool, last_frame.get_index_u2_cpcache(bytecode),
 918                                        m, bytecode, CHECK);
 919   } // end JvmtiHideSingleStepping
 920 
 921   // check if link resolution caused cpCache to be updated
 922   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
 923   if (cp_cache_entry->is_resolved(bytecode)) return;
 924 
 925   // compute auxiliary field attributes
 926   TosState state  = as_TosState(info.field_type());
 927 
 928   // Resolution of put instructions on final fields is delayed. That is required so that
 929   // exceptions are thrown at the correct place (when the instruction is actually invoked).
 930   // If we do not resolve an instruction in the current pass, leaving the put_code
 931   // set to zero will cause the next put instruction to the same field to reresolve.
 932 
 933   // Resolution of put instructions to final instance fields with invalid updates (i.e.,
 934   // to final instance fields with updates originating from a method different than <init>)
 935   // is inhibited. A putfield instruction targeting an instance final field must throw
 936   // an IllegalAccessError if the instruction is not in an instance
 937   // initializer method <init>. If resolution were not inhibited, a putfield
 938   // in an initializer method could be resolved in the initializer. Subsequent
 939   // putfield instructions to the same field would then use cached information.
 940   // As a result, those instructions would not pass through the VM. That is,
 941   // checks in resolve_field_access() would not be executed for those instructions
 942   // and the required IllegalAccessError would not be thrown.
 943   //
 944   // Also, we need to delay resolving getstatic and putstatic instructions until the
 945   // class is initialized.  This is required so that access to the static
 946   // field will call the initialization function every time until the class
 947   // is completely initialized ala. in 2.17.5 in JVM Specification.
 948   InstanceKlass* klass = info.field_holder();
 949   bool uninitialized_static = is_static && !klass->is_initialized();
 950   bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
 951                                       info.has_initialized_final_update();
 952   assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
 953 
 954   Bytecodes::Code get_code = (Bytecodes::Code)0;
 955   Bytecodes::Code put_code = (Bytecodes::Code)0;
 956   if (!uninitialized_static) {
 957     if (is_static) {
 958       get_code = Bytecodes::_getstatic;
 959     } else {
 960       get_code = Bytecodes::_getfield;
 961     }
 962     if (is_put && is_inline_type) {
 963         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_withfield);
 964     } else if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
 965         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 966     }
 967   }
 968 
 969   cp_cache_entry->set_field(
 970     get_code,
 971     put_code,
 972     info.field_holder(),
 973     info.index(),
 974     info.offset(),
 975     state,
 976     info.access_flags().is_final(),
 977     info.access_flags().is_volatile(),
 978     info.is_inlined(),
 979     info.signature()->is_Q_signature() && info.is_inline_type()
 980   );
 981 }
 982 
 983 
 984 //------------------------------------------------------------------------------------------------------------------------
 985 // Synchronization
 986 //
 987 // The interpreter's synchronization code is factored out so that it can
 988 // be shared by method invocation and synchronized blocks.
 989 //%note synchronization_3
 990 
 991 //%note monitor_1
 992 JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* current, BasicObjectLock* elem))
 993 #ifdef ASSERT
 994   current->last_frame().interpreter_frame_verify_monitor(elem);
 995 #endif
 996   Handle h_obj(current, elem->obj());
 997   assert(Universe::heap()->is_in_or_null(h_obj()),
 998          "must be NULL or an object");
 999   ObjectSynchronizer::enter(h_obj, elem->lock(), current);
1000   assert(Universe::heap()->is_in_or_null(elem->obj()),
1001          "must be NULL or an object");
1002 #ifdef ASSERT
1003   current->last_frame().interpreter_frame_verify_monitor(elem);
1004 #endif
1005 JRT_END
1006 
1007 
1008 JRT_LEAF(void, InterpreterRuntime::monitorexit(BasicObjectLock* elem))
1009   oop obj = elem->obj();
1010   assert(Universe::heap()->is_in(obj), "must be an object");
1011   // The object could become unlocked through a JNI call, which we have no other checks for.
1012   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
1013   if (obj->is_unlocked()) {
1014     if (CheckJNICalls) {
1015       fatal("Object has been unlocked by JNI");
1016     }
1017     return;
1018   }
1019   ObjectSynchronizer::exit(obj, elem->lock(), JavaThread::current());
1020   // Free entry. If it is not cleared, the exception handling code will try to unlock the monitor
1021   // again at method exit or in the case of an exception.
1022   elem->set_obj(NULL);
1023 JRT_END
1024 
1025 
1026 JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* current))
1027   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
1028 JRT_END
1029 
1030 
1031 JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* current))
1032   // Returns an illegal exception to install into the current thread. The
1033   // pending_exception flag is cleared so normal exception handling does not
1034   // trigger. Any current installed exception will be overwritten. This
1035   // method will be called during an exception unwind.
1036 
1037   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
1038   Handle exception(current, current->vm_result());
1039   assert(exception() != NULL, "vm result should be set");
1040   current->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
1041   if (!exception->is_a(vmClasses::ThreadDeath_klass())) {
1042     exception = get_preinitialized_exception(
1043                        vmClasses::IllegalMonitorStateException_klass(),
1044                        CATCH);
1045   }
1046   current->set_vm_result(exception());
1047 JRT_END
1048 
1049 
1050 //------------------------------------------------------------------------------------------------------------------------
1051 // Invokes
1052 
1053 JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* current, Method* method, address bcp))
1054   return method->orig_bytecode_at(method->bci_from(bcp));
1055 JRT_END
1056 
1057 JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* current, Method* method, address bcp, Bytecodes::Code new_code))
1058   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
1059 JRT_END
1060 
1061 JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* current, Method* method, address bcp))
1062   JvmtiExport::post_raw_breakpoint(current, method, bcp);
1063 JRT_END
1064 
1065 void InterpreterRuntime::resolve_invoke(JavaThread* current, Bytecodes::Code bytecode) {
1066   LastFrameAccessor last_frame(current);
1067   // extract receiver from the outgoing argument list if necessary
1068   Handle receiver(current, NULL);
1069   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
1070       bytecode == Bytecodes::_invokespecial) {
1071     ResourceMark rm(current);
1072     methodHandle m (current, last_frame.method());
1073     Bytecode_invoke call(m, last_frame.bci());
1074     Symbol* signature = call.signature();
1075     receiver = Handle(current, last_frame.callee_receiver(signature));
1076 
1077     assert(Universe::heap()->is_in_or_null(receiver()),
1078            "sanity check");
1079     assert(receiver.is_null() ||
1080            !Universe::heap()->is_in(receiver->klass()),
1081            "sanity check");
1082   }
1083 
1084   // resolve method
1085   CallInfo info;
1086   constantPoolHandle pool(current, last_frame.method()->constants());
1087 
1088   methodHandle resolved_method;
1089 
1090   {
1091     JvmtiHideSingleStepping jhss(current);
1092     JavaThread* THREAD = current; // For exception macros.
1093     LinkResolver::resolve_invoke(info, receiver, pool,
1094                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1095                                  THREAD);
1096 
1097     if (HAS_PENDING_EXCEPTION) {
1098       if (ProfileTraps && PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_NullPointerException()) {
1099         // Preserve the original exception across the call to note_trap()
1100         PreserveExceptionMark pm(current);
1101         // Recording the trap will help the compiler to potentially recognize this exception as "hot"
1102         note_trap(current, Deoptimization::Reason_null_check);
1103       }
1104       return;
1105     }
1106 
1107     if (JvmtiExport::can_hotswap_or_post_breakpoint() && info.resolved_method()->is_old()) {
1108       resolved_method = methodHandle(current, info.resolved_method()->get_new_method());
1109     } else {
1110       resolved_method = methodHandle(current, info.resolved_method());
1111     }
1112   } // end JvmtiHideSingleStepping
1113 
1114   // check if link resolution caused cpCache to be updated
1115   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1116   if (cp_cache_entry->is_resolved(bytecode)) return;
1117 
1118 #ifdef ASSERT
1119   if (bytecode == Bytecodes::_invokeinterface) {
1120     if (resolved_method->method_holder() == vmClasses::Object_klass()) {
1121       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
1122       // (see also CallInfo::set_interface for details)
1123       assert(info.call_kind() == CallInfo::vtable_call ||
1124              info.call_kind() == CallInfo::direct_call, "");
1125       assert(resolved_method->is_final() || info.has_vtable_index(),
1126              "should have been set already");
1127     } else if (!resolved_method->has_itable_index()) {
1128       // Resolved something like CharSequence.toString.  Use vtable not itable.
1129       assert(info.call_kind() != CallInfo::itable_call, "");
1130     } else {
1131       // Setup itable entry
1132       assert(info.call_kind() == CallInfo::itable_call, "");
1133       int index = resolved_method->itable_index();
1134       assert(info.itable_index() == index, "");
1135     }
1136   } else if (bytecode == Bytecodes::_invokespecial) {
1137     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
1138   } else {
1139     assert(info.call_kind() == CallInfo::direct_call ||
1140            info.call_kind() == CallInfo::vtable_call, "");
1141   }
1142 #endif
1143   // Get sender and only set cpCache entry to resolved if it is not an
1144   // interface.  The receiver for invokespecial calls within interface
1145   // methods must be checked for every call.
1146   InstanceKlass* sender = pool->pool_holder();
1147 
1148   switch (info.call_kind()) {
1149   case CallInfo::direct_call:
1150     cp_cache_entry->set_direct_call(
1151       bytecode,
1152       resolved_method,
1153       sender->is_interface());
1154     break;
1155   case CallInfo::vtable_call:
1156     cp_cache_entry->set_vtable_call(
1157       bytecode,
1158       resolved_method,
1159       info.vtable_index());
1160     break;
1161   case CallInfo::itable_call:
1162     cp_cache_entry->set_itable_call(
1163       bytecode,
1164       info.resolved_klass(),
1165       resolved_method,
1166       info.itable_index());
1167     break;
1168   default:  ShouldNotReachHere();
1169   }
1170 }
1171 
1172 
1173 // First time execution:  Resolve symbols, create a permanent MethodType object.
1174 void InterpreterRuntime::resolve_invokehandle(JavaThread* current) {
1175   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1176   LastFrameAccessor last_frame(current);
1177 
1178   // resolve method
1179   CallInfo info;
1180   constantPoolHandle pool(current, last_frame.method()->constants());
1181   {
1182     JvmtiHideSingleStepping jhss(current);
1183     JavaThread* THREAD = current; // For exception macros.
1184     LinkResolver::resolve_invoke(info, Handle(), pool,
1185                                  last_frame.get_index_u2_cpcache(bytecode), bytecode,
1186                                  CHECK);
1187   } // end JvmtiHideSingleStepping
1188 
1189   ConstantPoolCacheEntry* cp_cache_entry = last_frame.cache_entry();
1190   cp_cache_entry->set_method_handle(pool, info);
1191 }
1192 
1193 // First time execution:  Resolve symbols, create a permanent CallSite object.
1194 void InterpreterRuntime::resolve_invokedynamic(JavaThread* current) {
1195   LastFrameAccessor last_frame(current);
1196   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1197 
1198   // resolve method
1199   CallInfo info;
1200   constantPoolHandle pool(current, last_frame.method()->constants());
1201   int index = last_frame.get_index_u4(bytecode);
1202   {
1203     JvmtiHideSingleStepping jhss(current);
1204     JavaThread* THREAD = current; // For exception macros.
1205     LinkResolver::resolve_invoke(info, Handle(), pool,
1206                                  index, bytecode, CHECK);
1207   } // end JvmtiHideSingleStepping
1208 
1209   ConstantPoolCacheEntry* cp_cache_entry = pool->invokedynamic_cp_cache_entry_at(index);
1210   cp_cache_entry->set_dynamic_call(pool, info);
1211 }
1212 
1213 // This function is the interface to the assembly code. It returns the resolved
1214 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1215 // This function will check for redefinition!
1216 JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* current, Bytecodes::Code bytecode)) {
1217   switch (bytecode) {
1218   case Bytecodes::_getstatic:
1219   case Bytecodes::_putstatic:
1220   case Bytecodes::_getfield:
1221   case Bytecodes::_putfield:
1222   case Bytecodes::_withfield:
1223     resolve_get_put(current, bytecode);
1224     break;
1225   case Bytecodes::_invokevirtual:
1226   case Bytecodes::_invokespecial:
1227   case Bytecodes::_invokestatic:
1228   case Bytecodes::_invokeinterface:
1229     resolve_invoke(current, bytecode);
1230     break;
1231   case Bytecodes::_invokehandle:
1232     resolve_invokehandle(current);
1233     break;
1234   case Bytecodes::_invokedynamic:
1235     resolve_invokedynamic(current);
1236     break;
1237   default:
1238     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1239     break;
1240   }
1241 }
1242 JRT_END
1243 
1244 //------------------------------------------------------------------------------------------------------------------------
1245 // Miscellaneous
1246 
1247 
1248 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* current, address branch_bcp) {
1249   // Enable WXWrite: the function is called directly by interpreter.
1250   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1251 
1252   // frequency_counter_overflow_inner can throw async exception.
1253   nmethod* nm = frequency_counter_overflow_inner(current, branch_bcp);
1254   assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
1255   if (branch_bcp != NULL && nm != NULL) {
1256     // This was a successful request for an OSR nmethod.  Because
1257     // frequency_counter_overflow_inner ends with a safepoint check,
1258     // nm could have been unloaded so look it up again.  It's unsafe
1259     // to examine nm directly since it might have been freed and used
1260     // for something else.
1261     LastFrameAccessor last_frame(current);
1262     Method* method =  last_frame.method();
1263     int bci = method->bci_from(last_frame.bcp());
1264     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1265     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1266     if (nm != NULL && bs_nm != NULL) {
1267       // in case the transition passed a safepoint we need to barrier this again
1268       if (!bs_nm->nmethod_osr_entry_barrier(nm)) {
1269         nm = NULL;
1270       }
1271     }
1272   }
1273   if (nm != NULL && current->is_interp_only_mode()) {
1274     // Normally we never get an nm if is_interp_only_mode() is true, because
1275     // policy()->event has a check for this and won't compile the method when
1276     // true. However, it's possible for is_interp_only_mode() to become true
1277     // during the compilation. We don't want to return the nm in that case
1278     // because we want to continue to execute interpreted.
1279     nm = NULL;
1280   }
1281 #ifndef PRODUCT
1282   if (TraceOnStackReplacement) {
1283     if (nm != NULL) {
1284       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1285       nm->print();
1286     }
1287   }
1288 #endif
1289   return nm;
1290 }
1291 
1292 JRT_ENTRY(nmethod*,
1293           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* current, address branch_bcp))
1294   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1295   // flag, in case this method triggers classloading which will call into Java.
1296   UnlockFlagSaver fs(current);
1297 
1298   LastFrameAccessor last_frame(current);
1299   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1300   methodHandle method(current, last_frame.method());
1301   const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
1302   const int bci = branch_bcp != NULL ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1303 
1304   nmethod* osr_nm = CompilationPolicy::event(method, method, branch_bci, bci, CompLevel_none, NULL, CHECK_NULL);
1305 
1306   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1307   if (osr_nm != NULL && bs_nm != NULL) {
1308     if (!bs_nm->nmethod_osr_entry_barrier(osr_nm)) {
1309       osr_nm = NULL;
1310     }
1311   }
1312   return osr_nm;
1313 JRT_END
1314 
1315 JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1316   assert(ProfileInterpreter, "must be profiling interpreter");
1317   int bci = method->bci_from(cur_bcp);
1318   MethodData* mdo = method->method_data();
1319   if (mdo == NULL)  return 0;
1320   return mdo->bci_to_di(bci);
1321 JRT_END
1322 
1323 #ifdef ASSERT
1324 JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1325   assert(ProfileInterpreter, "must be profiling interpreter");
1326 
1327   MethodData* mdo = method->method_data();
1328   assert(mdo != NULL, "must not be null");
1329 
1330   int bci = method->bci_from(bcp);
1331 
1332   address mdp2 = mdo->bci_to_dp(bci);
1333   if (mdp != mdp2) {
1334     ResourceMark rm;
1335     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1336     int current_di = mdo->dp_to_di(mdp);
1337     int expected_di  = mdo->dp_to_di(mdp2);
1338     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1339     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1340     int approx_bci = -1;
1341     if (current_di >= 0) {
1342       approx_bci = mdo->data_at(current_di)->bci();
1343     }
1344     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1345     mdo->print_on(tty);
1346     method->print_codes();
1347   }
1348   assert(mdp == mdp2, "wrong mdp");
1349 JRT_END
1350 #endif // ASSERT
1351 
1352 JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* current, int return_bci))
1353   assert(ProfileInterpreter, "must be profiling interpreter");
1354   ResourceMark rm(current);
1355   LastFrameAccessor last_frame(current);
1356   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1357   MethodData* h_mdo = last_frame.method()->method_data();
1358 
1359   // Grab a lock to ensure atomic access to setting the return bci and
1360   // the displacement.  This can block and GC, invalidating all naked oops.
1361   MutexLocker ml(RetData_lock);
1362 
1363   // ProfileData is essentially a wrapper around a derived oop, so we
1364   // need to take the lock before making any ProfileData structures.
1365   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1366   guarantee(data != NULL, "profile data must be valid");
1367   RetData* rdata = data->as_RetData();
1368   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1369   last_frame.set_mdp(new_mdp);
1370 JRT_END
1371 
1372 JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* current, Method* m))
1373   return Method::build_method_counters(current, m);
1374 JRT_END
1375 
1376 
1377 JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* current))
1378   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
1379   // stack traversal automatically takes care of preserving arguments for invoke, so
1380   // this is no longer needed.
1381 
1382   // JRT_END does an implicit safepoint check, hence we are guaranteed to block
1383   // if this is called during a safepoint
1384 
1385   if (JvmtiExport::should_post_single_step()) {
1386     // This function is called by the interpreter when single stepping. Such single
1387     // stepping could unwind a frame. Then, it is important that we process any frames
1388     // that we might return into.
1389     StackWatermarkSet::before_unwind(current);
1390 
1391     // We are called during regular safepoints and when the VM is
1392     // single stepping. If any thread is marked for single stepping,
1393     // then we may have JVMTI work to do.
1394     LastFrameAccessor last_frame(current);
1395     JvmtiExport::at_single_stepping_point(current, last_frame.method(), last_frame.bcp());
1396   }
1397 JRT_END
1398 
1399 JRT_LEAF(void, InterpreterRuntime::at_unwind(JavaThread* current))
1400   // This function is called by the interpreter when the return poll found a reason
1401   // to call the VM. The reason could be that we are returning into a not yet safe
1402   // to access frame. We handle that below.
1403   // Note that this path does not check for single stepping, because we do not want
1404   // to single step when unwinding frames for an exception being thrown. Instead,
1405   // such single stepping code will use the safepoint table, which will use the
1406   // InterpreterRuntime::at_safepoint callback.
1407   StackWatermarkSet::before_unwind(current);
1408 JRT_END
1409 
1410 JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread* current, oopDesc* obj,
1411                                                       ConstantPoolCacheEntry *cp_entry))
1412 
1413   // check the access_flags for the field in the klass
1414 
1415   InstanceKlass* ik = InstanceKlass::cast(cp_entry->f1_as_klass());
1416   int index = cp_entry->field_index();
1417   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
1418 
1419   bool is_static = (obj == NULL);
1420   bool is_inlined = cp_entry->is_inlined();
1421   HandleMark hm(current);
1422 
1423   Handle h_obj;
1424   if (!is_static) {
1425     // non-static field accessors have an object, but we need a handle
1426     h_obj = Handle(current, obj);
1427   }
1428   InstanceKlass* cp_entry_f1 = InstanceKlass::cast(cp_entry->f1_as_klass());
1429   jfieldID fid = jfieldIDWorkaround::to_jfieldID(cp_entry_f1, cp_entry->f2_as_index(), is_static, is_inlined);
1430   LastFrameAccessor last_frame(current);
1431   JvmtiExport::post_field_access(current, last_frame.method(), last_frame.bcp(), cp_entry_f1, h_obj, fid);
1432 JRT_END
1433 
1434 JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread* current, oopDesc* obj,
1435                                                             ConstantPoolCacheEntry *cp_entry, jvalue *value))
1436 
1437   Klass* k = cp_entry->f1_as_klass();
1438 
1439   // check the access_flags for the field in the klass
1440   InstanceKlass* ik = InstanceKlass::cast(k);
1441   int index = cp_entry->field_index();
1442   // bail out if field modifications are not watched
1443   if ((ik->field_access_flags(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1444 
1445   char sig_type = '\0';
1446 
1447   switch(cp_entry->flag_state()) {
1448     case btos: sig_type = JVM_SIGNATURE_BYTE;    break;
1449     case ztos: sig_type = JVM_SIGNATURE_BOOLEAN; break;
1450     case ctos: sig_type = JVM_SIGNATURE_CHAR;    break;
1451     case stos: sig_type = JVM_SIGNATURE_SHORT;   break;
1452     case itos: sig_type = JVM_SIGNATURE_INT;     break;
1453     case ftos: sig_type = JVM_SIGNATURE_FLOAT;   break;
1454     case atos: sig_type = JVM_SIGNATURE_CLASS;   break;
1455     case ltos: sig_type = JVM_SIGNATURE_LONG;    break;
1456     case dtos: sig_type = JVM_SIGNATURE_DOUBLE;  break;
1457     default:  ShouldNotReachHere(); return;
1458   }
1459 
1460   // Both Q-signatures and L-signatures are mapped to atos
1461   if (cp_entry->flag_state() == atos && ik->field_signature(index)->is_Q_signature()) {
1462     sig_type = JVM_SIGNATURE_PRIMITIVE_OBJECT;
1463   }
1464 
1465   bool is_static = (obj == NULL);
1466   bool is_inlined = cp_entry->is_inlined();
1467 
1468   HandleMark hm(current);
1469   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, cp_entry->f2_as_index(), is_static, is_inlined);
1470   jvalue fvalue;
1471 #ifdef _LP64
1472   fvalue = *value;
1473 #else
1474   // Long/double values are stored unaligned and also noncontiguously with
1475   // tagged stacks.  We can't just do a simple assignment even in the non-
1476   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1477   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1478   // We assume that the two halves of longs/doubles are stored in interpreter
1479   // stack slots in platform-endian order.
1480   jlong_accessor u;
1481   jint* newval = (jint*)value;
1482   u.words[0] = newval[0];
1483   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1484   fvalue.j = u.long_value;
1485 #endif // _LP64
1486 
1487   Handle h_obj;
1488   if (!is_static) {
1489     // non-static field accessors have an object, but we need a handle
1490     h_obj = Handle(current, obj);
1491   }
1492 
1493   LastFrameAccessor last_frame(current);
1494   JvmtiExport::post_raw_field_modification(current, last_frame.method(), last_frame.bcp(), ik, h_obj,
1495                                            fid, sig_type, &fvalue);
1496 JRT_END
1497 
1498 JRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread* current))
1499   LastFrameAccessor last_frame(current);
1500   JvmtiExport::post_method_entry(current, last_frame.method(), last_frame.get_frame());
1501 JRT_END
1502 
1503 
1504 // This is a JRT_BLOCK_ENTRY because we have to stash away the return oop
1505 // before transitioning to VM, and restore it after transitioning back
1506 // to Java. The return oop at the top-of-stack, is not walked by the GC.
1507 JRT_BLOCK_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread* current))
1508   LastFrameAccessor last_frame(current);
1509   JvmtiExport::post_method_exit(current, last_frame.method(), last_frame.get_frame());
1510 JRT_END
1511 
1512 JRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1513 {
1514   return (Interpreter::contains(pc) ? 1 : 0);
1515 }
1516 JRT_END
1517 
1518 
1519 // Implementation of SignatureHandlerLibrary
1520 
1521 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1522 // Dummy definition (else normalization method is defined in CPU
1523 // dependant code)
1524 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1525   return fingerprint;
1526 }
1527 #endif
1528 
1529 address SignatureHandlerLibrary::set_handler_blob() {
1530   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1531   if (handler_blob == NULL) {
1532     return NULL;
1533   }
1534   address handler = handler_blob->code_begin();
1535   _handler_blob = handler_blob;
1536   _handler = handler;
1537   return handler;
1538 }
1539 
1540 void SignatureHandlerLibrary::initialize() {
1541   if (_fingerprints != NULL) {
1542     return;
1543   }
1544   if (set_handler_blob() == NULL) {
1545     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1546   }
1547 
1548   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1549                                       SignatureHandlerLibrary::buffer_size);
1550   _buffer = bb->code_begin();
1551 
1552   _fingerprints = new(ResourceObj::C_HEAP, mtCode)GrowableArray<uint64_t>(32, mtCode);
1553   _handlers     = new(ResourceObj::C_HEAP, mtCode)GrowableArray<address>(32, mtCode);
1554 }
1555 
1556 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1557   address handler   = _handler;
1558   int     insts_size = buffer->pure_insts_size();
1559   if (handler + insts_size > _handler_blob->code_end()) {
1560     // get a new handler blob
1561     handler = set_handler_blob();
1562   }
1563   if (handler != NULL) {
1564     memcpy(handler, buffer->insts_begin(), insts_size);
1565     pd_set_handler(handler);
1566     ICache::invalidate_range(handler, insts_size);
1567     _handler = handler + insts_size;
1568   }
1569   return handler;
1570 }
1571 
1572 void SignatureHandlerLibrary::add(const methodHandle& method) {
1573   if (method->signature_handler() == NULL) {
1574     // use slow signature handler if we can't do better
1575     int handler_index = -1;
1576     // check if we can use customized (fast) signature handler
1577     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::fp_max_size_of_parameters) {
1578       // use customized signature handler
1579       MutexLocker mu(SignatureHandlerLibrary_lock);
1580       // make sure data structure is initialized
1581       initialize();
1582       // lookup method signature's fingerprint
1583       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1584       // allow CPU dependant code to optimize the fingerprints for the fast handler
1585       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1586       handler_index = _fingerprints->find(fingerprint);
1587       // create handler if necessary
1588       if (handler_index < 0) {
1589         ResourceMark rm;
1590         ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer;
1591         CodeBuffer buffer((address)(_buffer + align_offset),
1592                           SignatureHandlerLibrary::buffer_size - align_offset);
1593         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1594         // copy into code heap
1595         address handler = set_handler(&buffer);
1596         if (handler == NULL) {
1597           // use slow signature handler (without memorizing it in the fingerprints)
1598         } else {
1599           // debugging suppport
1600           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1601             ttyLocker ttyl;
1602             tty->cr();
1603             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1604                           _handlers->length(),
1605                           (method->is_static() ? "static" : "receiver"),
1606                           method->name_and_sig_as_C_string(),
1607                           fingerprint,
1608                           buffer.insts_size());
1609             if (buffer.insts_size() > 0) {
1610               Disassembler::decode(handler, handler + buffer.insts_size(), tty
1611                                    NOT_PRODUCT(COMMA &buffer.asm_remarks()));
1612             }
1613 #ifndef PRODUCT
1614             address rh_begin = Interpreter::result_handler(method()->result_type());
1615             if (CodeCache::contains(rh_begin)) {
1616               // else it might be special platform dependent values
1617               tty->print_cr(" --- associated result handler ---");
1618               address rh_end = rh_begin;
1619               while (*(int*)rh_end != 0) {
1620                 rh_end += sizeof(int);
1621               }
1622               Disassembler::decode(rh_begin, rh_end);
1623             } else {
1624               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1625             }
1626 #endif
1627           }
1628           // add handler to library
1629           _fingerprints->append(fingerprint);
1630           _handlers->append(handler);
1631           // set handler index
1632           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1633           handler_index = _fingerprints->length() - 1;
1634         }
1635       }
1636       // Set handler under SignatureHandlerLibrary_lock
1637       if (handler_index < 0) {
1638         // use generic signature handler
1639         method->set_signature_handler(Interpreter::slow_signature_handler());
1640       } else {
1641         // set handler
1642         method->set_signature_handler(_handlers->at(handler_index));
1643       }
1644     } else {
1645       DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
1646       // use generic signature handler
1647       method->set_signature_handler(Interpreter::slow_signature_handler());
1648     }
1649   }
1650 #ifdef ASSERT
1651   int handler_index = -1;
1652   int fingerprint_index = -2;
1653   {
1654     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1655     // in any way if accessed from multiple threads. To avoid races with another
1656     // thread which may change the arrays in the above, mutex protected block, we
1657     // have to protect this read access here with the same mutex as well!
1658     MutexLocker mu(SignatureHandlerLibrary_lock);
1659     if (_handlers != NULL) {
1660       handler_index = _handlers->find(method->signature_handler());
1661       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1662       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1663       fingerprint_index = _fingerprints->find(fingerprint);
1664     }
1665   }
1666   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1667          handler_index == fingerprint_index, "sanity check");
1668 #endif // ASSERT
1669 }
1670 
1671 void SignatureHandlerLibrary::add(uint64_t fingerprint, address handler) {
1672   int handler_index = -1;
1673   // use customized signature handler
1674   MutexLocker mu(SignatureHandlerLibrary_lock);
1675   // make sure data structure is initialized
1676   initialize();
1677   fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1678   handler_index = _fingerprints->find(fingerprint);
1679   // create handler if necessary
1680   if (handler_index < 0) {
1681     if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1682       tty->cr();
1683       tty->print_cr("argument handler #%d at " PTR_FORMAT " for fingerprint " UINT64_FORMAT,
1684                     _handlers->length(),
1685                     p2i(handler),
1686                     fingerprint);
1687     }
1688     _fingerprints->append(fingerprint);
1689     _handlers->append(handler);
1690   } else {
1691     if (PrintSignatureHandlers) {
1692       tty->cr();
1693       tty->print_cr("duplicate argument handler #%d for fingerprint " UINT64_FORMAT "(old: " PTR_FORMAT ", new : " PTR_FORMAT ")",
1694                     _handlers->length(),
1695                     fingerprint,
1696                     p2i(_handlers->at(handler_index)),
1697                     p2i(handler));
1698     }
1699   }
1700 }
1701 
1702 
1703 BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1704 address                  SignatureHandlerLibrary::_handler      = NULL;
1705 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1706 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1707 address                  SignatureHandlerLibrary::_buffer       = NULL;
1708 
1709 
1710 JRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* current, Method* method))
1711   methodHandle m(current, method);
1712   assert(m->is_native(), "sanity check");
1713   // lookup native function entry point if it doesn't exist
1714   if (!m->has_native_function()) {
1715     NativeLookup::lookup(m, CHECK);
1716   }
1717   // make sure signature handler is installed
1718   SignatureHandlerLibrary::add(m);
1719   // The interpreter entry point checks the signature handler first,
1720   // before trying to fetch the native entry point and klass mirror.
1721   // We must set the signature handler last, so that multiple processors
1722   // preparing the same method will be sure to see non-null entry & mirror.
1723 JRT_END
1724 
1725 #if defined(IA32) || defined(AMD64) || defined(ARM)
1726 JRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* current, void* src_address, void* dest_address))
1727   if (src_address == dest_address) {
1728     return;
1729   }
1730   ResourceMark rm;
1731   LastFrameAccessor last_frame(current);
1732   assert(last_frame.is_interpreted_frame(), "");
1733   jint bci = last_frame.bci();
1734   methodHandle mh(current, last_frame.method());
1735   Bytecode_invoke invoke(mh, bci);
1736   ArgumentSizeComputer asc(invoke.signature());
1737   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1738   Copy::conjoint_jbytes(src_address, dest_address,
1739                        size_of_arguments * Interpreter::stackElementSize);
1740 JRT_END
1741 #endif
1742 
1743 #if INCLUDE_JVMTI
1744 // This is a support of the JVMTI PopFrame interface.
1745 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1746 // and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1747 // The member_name argument is a saved reference (in local#0) to the member_name.
1748 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1749 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1750 JRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* current, address member_name,
1751                                                             Method* method, address bcp))
1752   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1753   if (code != Bytecodes::_invokestatic) {
1754     return;
1755   }
1756   ConstantPool* cpool = method->constants();
1757   int cp_index = Bytes::get_native_u2(bcp + 1) + ConstantPool::CPCACHE_INDEX_TAG;
1758   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index));
1759   Symbol* mname = cpool->name_ref_at(cp_index);
1760 
1761   if (MethodHandles::has_member_arg(cname, mname)) {
1762     oop member_name_oop = cast_to_oop(member_name);
1763     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1764       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1765       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1766     }
1767     current->set_vm_result(member_name_oop);
1768   } else {
1769     current->set_vm_result(NULL);
1770   }
1771 JRT_END
1772 #endif // INCLUDE_JVMTI
1773 
1774 #ifndef PRODUCT
1775 // This must be a JRT_LEAF function because the interpreter must save registers on x86 to
1776 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1777 // The generated code still uses call_VM because that will set up the frame pointer for
1778 // bcp and method.
1779 JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* current, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1780   LastFrameAccessor last_frame(current);
1781   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1782   methodHandle mh(current, last_frame.method());
1783   BytecodeTracer::trace(mh, last_frame.bcp(), tos, tos2);
1784   return preserve_this_value;
1785 JRT_END
1786 #endif // !PRODUCT