1 /*
   2  * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "interpreter/oopMapCache.hpp"
  36 #include "interpreter/linkResolver.hpp"
  37 #include "jvm_io.h"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/universe.hpp"
  44 #include "oops/klass.inline.hpp"
  45 #include "oops/objArrayKlass.hpp"
  46 #include "oops/objArrayOop.inline.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/typeArrayOop.inline.hpp"
  49 #include "prims/methodHandles.hpp"
  50 #include "runtime/deoptimization.hpp"
  51 #include "runtime/fieldDescriptor.inline.hpp"
  52 #include "runtime/handles.inline.hpp"
  53 #include "runtime/interfaceSupport.inline.hpp"
  54 #include "runtime/javaCalls.hpp"
  55 #include "runtime/jniHandles.inline.hpp"
  56 #include "runtime/timerTrace.hpp"
  57 #include "runtime/reflection.hpp"
  58 #include "runtime/safepointVerifiers.hpp"
  59 #include "runtime/signature.hpp"
  60 #include "runtime/stubRoutines.hpp"
  61 #include "sanitizers/leak.hpp"
  62 #include "utilities/exceptions.hpp"
  63 
  64 
  65 /*
  66  * JSR 292 reference implementation: method handles
  67  * The JDK 7 reference implementation represented method handle
  68  * combinations as chains.  Each link in the chain had a "vmentry"
  69  * field which pointed at a bit of assembly code which performed
  70  * one transformation before dispatching to the next link in the chain.
  71  *
  72  * The current reference implementation pushes almost all code generation
  73  * responsibility to (trusted) Java code.  A method handle contains a
  74  * pointer to its "LambdaForm", which embodies all details of the method
  75  * handle's behavior.  The LambdaForm is a normal Java object, managed
  76  * by a runtime coded in Java.
  77  */
  78 
  79 bool MethodHandles::_enabled = false; // set true after successful native linkage
  80 MethodHandlesAdapterBlob* MethodHandles::_adapter_code = nullptr;
  81 
  82 /**
  83  * Generates method handle adapters. Returns 'false' if memory allocation
  84  * failed and true otherwise.
  85  */
  86 void MethodHandles::generate_adapters() {
  87   assert(vmClasses::MethodHandle_klass() != nullptr, "should be present");
  88   assert(_adapter_code == nullptr, "generate only once");
  89 
  90   ResourceMark rm;
  91   TraceTime timer("MethodHandles adapters generation", TRACETIME_LOG(Info, startuptime));
  92   // The adapter entry is required to be aligned to CodeEntryAlignment.
  93   // So we need additional bytes due to alignment.
  94   int adapter_num = (int)Interpreter::method_handle_invoke_LAST - (int)Interpreter::method_handle_invoke_FIRST + 1;
  95   int max_aligned_bytes = adapter_num * CodeEntryAlignment;
  96   _adapter_code = MethodHandlesAdapterBlob::create(adapter_code_size + max_aligned_bytes);
  97   CodeBuffer code(_adapter_code);
  98   MethodHandlesAdapterGenerator g(&code);
  99   g.generate();
 100   code.log_section_sizes("MethodHandlesAdapterBlob");
 101 }
 102 
 103 //------------------------------------------------------------------------------
 104 // MethodHandlesAdapterGenerator::generate
 105 //
 106 void MethodHandlesAdapterGenerator::generate() {
 107   // Generate generic method handle adapters.
 108   // Generate interpreter entries
 109   for (Interpreter::MethodKind mk = Interpreter::method_handle_invoke_FIRST;
 110        mk <= Interpreter::method_handle_invoke_LAST;
 111        mk = Interpreter::MethodKind(1 + (int)mk)) {
 112     vmIntrinsics::ID iid = Interpreter::method_handle_intrinsic(mk);
 113     StubCodeMark mark(this, "MethodHandle::interpreter_entry", vmIntrinsics::name_at(iid));
 114     address entry = MethodHandles::generate_method_handle_interpreter_entry(_masm, iid);
 115     if (entry != nullptr) {
 116       Interpreter::set_entry_for_kind(mk, entry);
 117     }
 118     // If the entry is not set, it will throw AbstractMethodError.
 119   }
 120 }
 121 
 122 void MethodHandles::set_enabled(bool z) {
 123   if (_enabled != z) {
 124     guarantee(z, "can only enable once");
 125     _enabled = z;
 126   }
 127 }
 128 
 129 // MemberName support
 130 
 131 // import java_lang_invoke_MemberName.*
 132 enum {
 133   IS_METHOD             = java_lang_invoke_MemberName::MN_IS_METHOD,
 134   IS_OBJECT_CONSTRUCTOR = java_lang_invoke_MemberName::MN_IS_OBJECT_CONSTRUCTOR,
 135   IS_FIELD              = java_lang_invoke_MemberName::MN_IS_FIELD,
 136   IS_TYPE               = java_lang_invoke_MemberName::MN_IS_TYPE,
 137   CALLER_SENSITIVE      = java_lang_invoke_MemberName::MN_CALLER_SENSITIVE,
 138   TRUSTED_FINAL         = java_lang_invoke_MemberName::MN_TRUSTED_FINAL,
 139   HIDDEN_MEMBER        = java_lang_invoke_MemberName::MN_HIDDEN_MEMBER,
 140   FLAT_FIELD            = java_lang_invoke_MemberName::MN_FLAT_FIELD,
 141   NULL_RESTRICTED       = java_lang_invoke_MemberName::MN_NULL_RESTRICTED_FIELD,
 142   REFERENCE_KIND_SHIFT  = java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT,
 143   REFERENCE_KIND_MASK   = java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK,
 144   LM_UNCONDITIONAL      = java_lang_invoke_MemberName::MN_UNCONDITIONAL_MODE,
 145   LM_MODULE             = java_lang_invoke_MemberName::MN_MODULE_MODE,
 146   LM_TRUSTED            = java_lang_invoke_MemberName::MN_TRUSTED_MODE,
 147   ALL_KINDS      = IS_METHOD | IS_OBJECT_CONSTRUCTOR | IS_FIELD | IS_TYPE
 148 };
 149 
 150 int MethodHandles::ref_kind_to_flags(int ref_kind) {
 151   assert(ref_kind_is_valid(ref_kind), "%d", ref_kind);
 152   int flags = (ref_kind << REFERENCE_KIND_SHIFT);
 153   if (ref_kind_is_field(ref_kind)) {
 154     flags |= IS_FIELD;
 155   } else if (ref_kind_is_method(ref_kind)) {
 156     flags |= IS_METHOD;
 157   } else if (ref_kind == JVM_REF_newInvokeSpecial) {
 158     flags |= IS_OBJECT_CONSTRUCTOR;
 159   }
 160   return flags;
 161 }
 162 
 163 Handle MethodHandles::resolve_MemberName_type(Handle mname, Klass* caller, TRAPS) {
 164   Handle empty;
 165   Handle type(THREAD, java_lang_invoke_MemberName::type(mname()));
 166   if (!java_lang_String::is_instance(type())) {
 167     return type; // already resolved
 168   }
 169   Symbol* signature = java_lang_String::as_symbol_or_null(type());
 170   if (signature == nullptr) {
 171     return empty;  // no such signature exists in the VM
 172   }
 173   Handle resolved;
 174   int flags = java_lang_invoke_MemberName::flags(mname());
 175   switch (flags & ALL_KINDS) {
 176     case IS_METHOD:
 177     case IS_OBJECT_CONSTRUCTOR:
 178       resolved = SystemDictionary::find_method_handle_type(signature, caller, CHECK_(empty));
 179       break;
 180     case IS_FIELD:
 181       resolved = SystemDictionary::find_field_handle_type(signature, caller, CHECK_(empty));
 182       break;
 183     default:
 184       THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format", empty);
 185   }
 186   if (resolved.is_null()) {
 187     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MemberName type", empty);
 188   }
 189   return resolved;
 190 }
 191 
 192 oop MethodHandles::init_MemberName(Handle mname, Handle target, TRAPS) {
 193   // This method is used from java.lang.invoke.MemberName constructors.
 194   // It fills in the new MemberName from a java.lang.reflect.Member.
 195   oop target_oop = target();
 196   Klass* target_klass = target_oop->klass();
 197   if (target_klass == vmClasses::reflect_Field_klass()) {
 198     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
 199     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
 200     Klass* k = java_lang_Class::as_Klass(clazz);
 201     if (k != nullptr && k->is_instance_klass()) {
 202       fieldDescriptor fd(InstanceKlass::cast(k), slot);
 203       oop mname2 = init_field_MemberName(mname, fd);
 204       if (mname2 != nullptr) {
 205         // Since we have the reified name and type handy, add them to the result.
 206         if (java_lang_invoke_MemberName::name(mname2) == nullptr)
 207           java_lang_invoke_MemberName::set_name(mname2, java_lang_reflect_Field::name(target_oop));
 208         if (java_lang_invoke_MemberName::type(mname2) == nullptr)
 209           java_lang_invoke_MemberName::set_type(mname2, java_lang_reflect_Field::type(target_oop));
 210       }
 211       return mname2;
 212     }
 213   } else if (target_klass == vmClasses::reflect_Method_klass()) {
 214     oop clazz  = java_lang_reflect_Method::clazz(target_oop);
 215     int slot   = java_lang_reflect_Method::slot(target_oop);
 216     Klass* k = java_lang_Class::as_Klass(clazz);
 217     if (k != nullptr && k->is_instance_klass()) {
 218       Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
 219       if (m == nullptr || is_signature_polymorphic(m->intrinsic_id()))
 220         return nullptr;            // do not resolve unless there is a concrete signature
 221       CallInfo info(m, k, CHECK_NULL);
 222       return init_method_MemberName(mname, info);
 223     }
 224   } else if (target_klass == vmClasses::reflect_Constructor_klass()) {
 225     oop clazz  = java_lang_reflect_Constructor::clazz(target_oop);
 226     int slot   = java_lang_reflect_Constructor::slot(target_oop);
 227     Klass* k = java_lang_Class::as_Klass(clazz);
 228     if (k != nullptr && k->is_instance_klass()) {
 229       Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
 230       if (m == nullptr)  return nullptr;
 231       CallInfo info(m, k, CHECK_NULL);
 232       return init_method_MemberName(mname, info);
 233     }
 234   }
 235   return nullptr;
 236 }
 237 
 238 oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info) {
 239   assert(info.resolved_appendix().is_null(), "only normal methods here");
 240   methodHandle m(Thread::current(), info.resolved_method());
 241   assert(m.not_null(), "null method handle");
 242   InstanceKlass* m_klass = m->method_holder();
 243   assert(m_klass != nullptr, "null holder for method handle");
 244   int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
 245   int vmindex = Method::invalid_vtable_index;
 246   LogTarget(Debug, methodhandles, indy) lt_indy;
 247 
 248   switch (info.call_kind()) {
 249   case CallInfo::itable_call:
 250     vmindex = info.itable_index();
 251     // More importantly, the itable index only works with the method holder.
 252     assert(m_klass->verify_itable_index(vmindex), "");
 253     flags |= IS_METHOD | (JVM_REF_invokeInterface << REFERENCE_KIND_SHIFT);
 254     if (lt_indy.is_enabled()) {
 255       ResourceMark rm;
 256       LogStream ls(lt_indy);
 257       ls.print_cr("memberName: invokeinterface method_holder::method: %s, itableindex: %d, access_flags:",
 258                   Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 259                   vmindex);
 260        m->access_flags().print_on(&ls);
 261        if (!m->is_abstract()) {
 262          if (!m->is_private()) {
 263            ls.print("default");
 264          }
 265          else {
 266            ls.print("private-intf");
 267          }
 268        }
 269        ls.cr();
 270     }
 271     break;
 272 
 273   case CallInfo::vtable_call:
 274     vmindex = info.vtable_index();
 275     flags |= IS_METHOD | (JVM_REF_invokeVirtual << REFERENCE_KIND_SHIFT);
 276     assert(info.resolved_klass()->is_subtype_of(m_klass), "virtual call must be type-safe");
 277     if (m_klass->is_interface()) {
 278       // This is a vtable call to an interface method (abstract "miranda method" or default method).
 279       // The vtable index is meaningless without a class (not interface) receiver type, so get one.
 280       // (LinkResolver should help us figure this out.)
 281       assert(info.resolved_klass()->is_instance_klass(), "subtype of interface must be an instance klass");
 282       InstanceKlass* m_klass_non_interface = InstanceKlass::cast(info.resolved_klass());
 283       if (m_klass_non_interface->is_interface()) {
 284         m_klass_non_interface = vmClasses::Object_klass();
 285 #ifdef ASSERT
 286         { ResourceMark rm;
 287           Method* m2 = m_klass_non_interface->vtable().method_at(vmindex);
 288           assert(m->name() == m2->name() && m->signature() == m2->signature(),
 289                  "at %d, %s != %s", vmindex,
 290                  m->name_and_sig_as_C_string(), m2->name_and_sig_as_C_string());
 291         }
 292 #endif //ASSERT
 293       }
 294       if (!m->is_public()) {
 295         assert(m->is_public(), "virtual call must be to public interface method");
 296         return nullptr;  // elicit an error later in product build
 297       }
 298       assert(info.resolved_klass()->is_subtype_of(m_klass_non_interface), "virtual call must be type-safe");
 299       m_klass = m_klass_non_interface;
 300     }
 301     if (lt_indy.is_enabled()) {
 302       ResourceMark rm;
 303       LogStream ls(lt_indy);
 304       ls.print_cr("memberName: invokevirtual method_holder::method: %s, receiver: %s, vtableindex: %d, access_flags:",
 305                   Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 306                   m_klass->internal_name(), vmindex);
 307        m->access_flags().print_on(&ls);
 308        if (m->is_default_method()) {
 309          ls.print("default");
 310        }
 311        ls.cr();
 312     }
 313     break;
 314 
 315   case CallInfo::direct_call:
 316     vmindex = Method::nonvirtual_vtable_index;
 317     if (m->is_static()) {
 318       assert(!m->is_class_initializer(), "Cannot be static initializer");
 319       flags |= IS_METHOD      | (JVM_REF_invokeStatic  << REFERENCE_KIND_SHIFT);
 320     } else if (m->is_object_constructor()) {
 321       flags |= IS_OBJECT_CONSTRUCTOR | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 322     } else {
 323       // "special" reflects that this is a direct call, not that it
 324       // necessarily originates from an invokespecial. We can also do
 325       // direct calls for private and/or final non-static methods.
 326       flags |= IS_METHOD      | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 327     }
 328     break;
 329 
 330   default:  assert(false, "bad CallInfo");  return nullptr;
 331   }
 332 
 333   // @CallerSensitive annotation detected
 334   if (m->caller_sensitive()) {
 335     flags |= CALLER_SENSITIVE;
 336   }
 337 
 338   Handle resolved_method = info.resolved_method_name();
 339   assert(java_lang_invoke_ResolvedMethodName::vmtarget(resolved_method()) == m() || m->is_old(),
 340          "Should not change after link resolution");
 341 
 342   oop mname_oop = mname();
 343   java_lang_invoke_MemberName::set_flags  (mname_oop, flags);
 344   java_lang_invoke_MemberName::set_method (mname_oop, resolved_method());
 345   java_lang_invoke_MemberName::set_vmindex(mname_oop, vmindex);   // vtable/itable index
 346   java_lang_invoke_MemberName::set_clazz  (mname_oop, m_klass->java_mirror());
 347   // Note:  name and type can be lazily computed by resolve_MemberName,
 348   // if Java code needs them as resolved String and MethodType objects.
 349   // If relevant, the vtable or itable value is stored as vmindex.
 350   // This is done eagerly, since it is readily available without
 351   // constructing any new objects.
 352   return mname();
 353 }
 354 
 355 oop MethodHandles::init_field_MemberName(Handle mname, fieldDescriptor& fd, bool is_setter) {
 356   InstanceKlass* ik = fd.field_holder();
 357   int flags = (jushort)( fd.access_flags().as_short());
 358   flags |= IS_FIELD | ((fd.is_static() ? JVM_REF_getStatic : JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 359   if (fd.is_trusted_final()) flags |= TRUSTED_FINAL;
 360   if (fd.is_flat()) flags |= FLAT_FIELD;
 361   if (fd.is_null_free_inline_type()) flags |= NULL_RESTRICTED;
 362   if (is_setter)  flags += ((JVM_REF_putField - JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 363   int vmindex        = fd.offset();  // determines the field uniquely when combined with static bit
 364 
 365   oop mname_oop = mname();
 366   java_lang_invoke_MemberName::set_flags  (mname_oop, flags);
 367   java_lang_invoke_MemberName::set_method (mname_oop, nullptr);
 368   java_lang_invoke_MemberName::set_vmindex(mname_oop, vmindex);
 369   java_lang_invoke_MemberName::set_clazz  (mname_oop, ik->java_mirror());
 370 
 371   oop type = field_signature_type_or_null(fd.signature());
 372   oop name = field_name_or_null(fd.name());
 373   if (name != nullptr)
 374     java_lang_invoke_MemberName::set_name(mname_oop,   name);
 375   if (type != nullptr)
 376     java_lang_invoke_MemberName::set_type(mname_oop,   type);
 377   // Note:  name and type can be lazily computed by resolve_MemberName,
 378   // if Java code needs them as resolved String and Class objects.
 379   // Note that the incoming type oop might be pre-resolved (non-null).
 380   // The base clazz and field offset (vmindex) must be eagerly stored,
 381   // because they unambiguously identify the field.
 382   // Although the fieldDescriptor::_index would also identify the field,
 383   // we do not use it, because it is harder to decode.
 384   // TO DO: maybe intern mname_oop
 385   return mname();
 386 }
 387 
 388 // JVM 2.9 Special Methods:
 389 // A method is signature polymorphic if and only if all of the following conditions hold :
 390 // * It is declared in the java.lang.invoke.MethodHandle/VarHandle classes.
 391 // * It has a single formal parameter of type Object[].
 392 // * It has a return type of Object for a polymorphic return type, otherwise a fixed return type.
 393 // * It has the ACC_VARARGS and ACC_NATIVE flags set.
 394 bool MethodHandles::is_method_handle_invoke_name(Klass* klass, Symbol* name) {
 395   if (klass == nullptr)
 396     return false;
 397   // The following test will fail spuriously during bootstrap of MethodHandle itself:
 398   //    if (klass != vmClasses::MethodHandle_klass())
 399   // Test the name instead:
 400   if (klass->name() != vmSymbols::java_lang_invoke_MethodHandle() &&
 401       klass->name() != vmSymbols::java_lang_invoke_VarHandle()) {
 402     return false;
 403   }
 404 
 405   // Look up signature polymorphic method with polymorphic return type
 406   Symbol* poly_sig = vmSymbols::object_array_object_signature();
 407   InstanceKlass* iklass = InstanceKlass::cast(klass);
 408   Method* m = iklass->find_method(name, poly_sig);
 409   if (m != nullptr) {
 410     int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS;
 411     int flags = m->access_flags().as_int();
 412     if ((flags & required) == required) {
 413       return true;
 414     }
 415   }
 416 
 417   // Look up signature polymorphic method with non-polymorphic (non Object) return type
 418   int me;
 419   int ms = iklass->find_method_by_name(name, &me);
 420   if (ms == -1) return false;
 421   for (; ms < me; ms++) {
 422     Method* m = iklass->methods()->at(ms);
 423     int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS;
 424     int flags = m->access_flags().as_int();
 425     if ((flags & required) == required && ArgumentCount(m->signature()).size() == 1) {
 426       return true;
 427     }
 428   }
 429   return false;
 430 }
 431 
 432 
 433 Symbol* MethodHandles::signature_polymorphic_intrinsic_name(vmIntrinsics::ID iid) {
 434   assert(is_signature_polymorphic_intrinsic(iid), "%d %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
 435   switch (iid) {
 436   case vmIntrinsics::_invokeBasic:      return vmSymbols::invokeBasic_name();
 437   case vmIntrinsics::_linkToVirtual:    return vmSymbols::linkToVirtual_name();
 438   case vmIntrinsics::_linkToStatic:     return vmSymbols::linkToStatic_name();
 439   case vmIntrinsics::_linkToSpecial:    return vmSymbols::linkToSpecial_name();
 440   case vmIntrinsics::_linkToInterface:  return vmSymbols::linkToInterface_name();
 441   case vmIntrinsics::_linkToNative:     return vmSymbols::linkToNative_name();
 442   default:
 443     fatal("unexpected intrinsic id: %d %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
 444   }
 445 }
 446 
 447 Bytecodes::Code MethodHandles::signature_polymorphic_intrinsic_bytecode(vmIntrinsics::ID id) {
 448   switch(id) {
 449     case vmIntrinsics::_linkToVirtual:   return Bytecodes::_invokevirtual;
 450     case vmIntrinsics::_linkToInterface: return Bytecodes::_invokeinterface;
 451     case vmIntrinsics::_linkToStatic:    return Bytecodes::_invokestatic;
 452     case vmIntrinsics::_linkToSpecial:   return Bytecodes::_invokespecial;
 453     case vmIntrinsics::_invokeBasic:     return Bytecodes::_invokehandle;
 454     default:
 455       fatal("unexpected id: (%d) %s", (uint)id, vmIntrinsics::name_at(id));
 456   }
 457 }
 458 
 459 int MethodHandles::signature_polymorphic_intrinsic_ref_kind(vmIntrinsics::ID iid) {
 460   switch (iid) {
 461   case vmIntrinsics::_invokeBasic:      return 0;
 462   case vmIntrinsics::_linkToNative:     return 0;
 463   case vmIntrinsics::_linkToVirtual:    return JVM_REF_invokeVirtual;
 464   case vmIntrinsics::_linkToStatic:     return JVM_REF_invokeStatic;
 465   case vmIntrinsics::_linkToSpecial:    return JVM_REF_invokeSpecial;
 466   case vmIntrinsics::_linkToInterface:  return JVM_REF_invokeInterface;
 467   default:
 468     fatal("unexpected intrinsic id: %d %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
 469   }
 470 }
 471 
 472 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Symbol* name) {
 473   vmSymbolID name_id = vmSymbols::find_sid(name);
 474   switch (name_id) {
 475   // The ID _invokeGeneric stands for all non-static signature-polymorphic methods, except built-ins.
 476   case VM_SYMBOL_ENUM_NAME(invoke_name):           return vmIntrinsics::_invokeGeneric;
 477   // The only built-in non-static signature-polymorphic method is MethodHandle.invokeBasic:
 478   case VM_SYMBOL_ENUM_NAME(invokeBasic_name):      return vmIntrinsics::_invokeBasic;
 479 
 480   // There is one static signature-polymorphic method for each JVM invocation mode.
 481   case VM_SYMBOL_ENUM_NAME(linkToVirtual_name):    return vmIntrinsics::_linkToVirtual;
 482   case VM_SYMBOL_ENUM_NAME(linkToStatic_name):     return vmIntrinsics::_linkToStatic;
 483   case VM_SYMBOL_ENUM_NAME(linkToSpecial_name):    return vmIntrinsics::_linkToSpecial;
 484   case VM_SYMBOL_ENUM_NAME(linkToInterface_name):  return vmIntrinsics::_linkToInterface;
 485   case VM_SYMBOL_ENUM_NAME(linkToNative_name):     return vmIntrinsics::_linkToNative;
 486   default:                                                    break;
 487   }
 488 
 489   // Cover the case of invokeExact and any future variants of invokeFoo.
 490   Klass* mh_klass = vmClasses::klass_at(VM_CLASS_ID(MethodHandle_klass));
 491   if (mh_klass != nullptr && is_method_handle_invoke_name(mh_klass, name)) {
 492     return vmIntrinsics::_invokeGeneric;
 493   }
 494 
 495   // Cover the case of methods on VarHandle.
 496   Klass* vh_klass = vmClasses::klass_at(VM_CLASS_ID(VarHandle_klass));
 497   if (vh_klass != nullptr && is_method_handle_invoke_name(vh_klass, name)) {
 498     return vmIntrinsics::_invokeGeneric;
 499   }
 500 
 501   // Note: The pseudo-intrinsic _compiledLambdaForm is never linked against.
 502   // Instead it is used to mark lambda forms bound to invokehandle or invokedynamic.
 503   return vmIntrinsics::_none;
 504 }
 505 
 506 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Klass* klass, Symbol* name) {
 507   if (klass != nullptr &&
 508       (klass->name() == vmSymbols::java_lang_invoke_MethodHandle() ||
 509        klass->name() == vmSymbols::java_lang_invoke_VarHandle())) {
 510     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 511     if (iid != vmIntrinsics::_none)
 512       return iid;
 513     if (is_method_handle_invoke_name(klass, name))
 514       return vmIntrinsics::_invokeGeneric;
 515   }
 516   return vmIntrinsics::_none;
 517 }
 518 
 519 // Returns true if method is signature polymorphic and public
 520 bool MethodHandles::is_signature_polymorphic_public_name(Klass* klass, Symbol* name) {
 521   if (is_signature_polymorphic_name(klass, name)) {
 522     InstanceKlass* iklass = InstanceKlass::cast(klass);
 523     int me;
 524     int ms = iklass->find_method_by_name(name, &me);
 525     assert(ms != -1, "");
 526     for (; ms < me; ms++) {
 527       Method* m = iklass->methods()->at(ms);
 528       int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS | JVM_ACC_PUBLIC;
 529       int flags = m->access_flags().as_int();
 530       if ((flags & required) == required && ArgumentCount(m->signature()).size() == 1) {
 531         return true;
 532       }
 533     }
 534   }
 535   return false;
 536 }
 537 
 538 // convert the external string or reflective type to an internal signature
 539 Symbol* MethodHandles::lookup_signature(oop type_str, bool intern_if_not_found, TRAPS) {
 540   if (java_lang_invoke_MethodType::is_instance(type_str)) {
 541     return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found);
 542   } else if (java_lang_Class::is_instance(type_str)) {
 543     return java_lang_Class::as_signature(type_str, false);
 544   } else if (java_lang_String::is_instance(type_str)) {
 545     if (intern_if_not_found) {
 546       return java_lang_String::as_symbol(type_str);
 547     } else {
 548       return java_lang_String::as_symbol_or_null(type_str);
 549     }
 550   } else {
 551     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", nullptr);
 552   }
 553 }
 554 
 555 static const char OBJ_SIG[] = "Ljava/lang/Object;";
 556 enum { OBJ_SIG_LEN = 18 };
 557 
 558 bool MethodHandles::is_basic_type_signature(Symbol* sig) {
 559   assert(vmSymbols::object_signature()->utf8_length() == (int)OBJ_SIG_LEN, "");
 560   assert(vmSymbols::object_signature()->equals(OBJ_SIG), "");
 561   for (SignatureStream ss(sig, sig->starts_with(JVM_SIGNATURE_FUNC)); !ss.is_done(); ss.next()) {
 562     switch (ss.type()) {
 563     case T_OBJECT:
 564       // only java/lang/Object is valid here
 565       if (strncmp((char*) ss.raw_bytes(), OBJ_SIG, OBJ_SIG_LEN) != 0)
 566         return false;
 567       break;
 568     case T_VOID:
 569     case T_INT:
 570     case T_LONG:
 571     case T_FLOAT:
 572     case T_DOUBLE:
 573       break;
 574     default:
 575       // subword types (T_BYTE etc.), Q-descriptors, arrays
 576       return false;
 577     }
 578   }
 579   return true;
 580 }
 581 
 582 Symbol* MethodHandles::lookup_basic_type_signature(Symbol* sig, bool keep_last_arg) {
 583   Symbol* bsig = nullptr;
 584   if (sig == nullptr) {
 585     return sig;
 586   } else if (is_basic_type_signature(sig)) {
 587     sig->increment_refcount();
 588     return sig;  // that was easy
 589   } else if (!sig->starts_with(JVM_SIGNATURE_FUNC)) {
 590     BasicType bt = Signature::basic_type(sig);
 591     if (is_subword_type(bt)) {
 592       bsig = vmSymbols::int_signature();
 593     } else {
 594       assert(is_reference_type(bt), "is_basic_type_signature was false");
 595       bsig = vmSymbols::object_signature();
 596     }
 597   } else {
 598     ResourceMark rm;
 599     stringStream buffer(128);
 600     buffer.put(JVM_SIGNATURE_FUNC);
 601     int arg_pos = 0, keep_arg_pos = -1;
 602     if (keep_last_arg)
 603       keep_arg_pos = ArgumentCount(sig).size() - 1;
 604     for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
 605       BasicType bt = ss.type();
 606       size_t this_arg_pos = buffer.size();
 607       if (ss.at_return_type()) {
 608         buffer.put(JVM_SIGNATURE_ENDFUNC);
 609       }
 610       if (arg_pos == keep_arg_pos) {
 611         buffer.write((char*) ss.raw_bytes(),
 612                      (int)   ss.raw_length());
 613       } else if (is_reference_type(bt)) {
 614         buffer.write(OBJ_SIG, OBJ_SIG_LEN);
 615       } else {
 616         if (is_subword_type(bt))
 617           bt = T_INT;
 618         buffer.put(type2char(bt));
 619       }
 620       arg_pos++;
 621     }
 622     const char* sigstr =       buffer.base();
 623     int         siglen = (int) buffer.size();
 624     bsig = SymbolTable::new_symbol(sigstr, siglen);
 625   }
 626   assert(is_basic_type_signature(bsig) ||
 627          // detune assert in case the injected argument is not a basic type:
 628          keep_last_arg, "");
 629   return bsig;
 630 }
 631 
 632 void MethodHandles::print_as_basic_type_signature_on(outputStream* st,
 633                                                      Symbol* sig) {
 634   st = st ? st : tty;
 635   bool prev_type = false;
 636   bool is_method = (sig->char_at(0) == JVM_SIGNATURE_FUNC);
 637   if (is_method)  st->put(JVM_SIGNATURE_FUNC);
 638   for (SignatureStream ss(sig, is_method); !ss.is_done(); ss.next()) {
 639     if (ss.at_return_type())
 640       st->put(JVM_SIGNATURE_ENDFUNC);
 641     else if (prev_type)
 642       st->put(',');
 643     const char* cp = (const char*) ss.raw_bytes();
 644     if (ss.is_array()) {
 645       st->put(JVM_SIGNATURE_ARRAY);
 646       if (ss.array_prefix_length() == 1)
 647         st->put(cp[1]);
 648       else
 649         st->put(JVM_SIGNATURE_CLASS);
 650     } else {
 651       st->put(cp[0]);
 652     }
 653   }
 654 }
 655 
 656 
 657 
 658 static oop object_java_mirror() {
 659   return vmClasses::Object_klass()->java_mirror();
 660 }
 661 
 662 oop MethodHandles::field_name_or_null(Symbol* s) {
 663   if (s == nullptr)  return nullptr;
 664   return StringTable::lookup(s);
 665 }
 666 
 667 oop MethodHandles::field_signature_type_or_null(Symbol* s) {
 668   if (s == nullptr)  return nullptr;
 669   BasicType bt = Signature::basic_type(s);
 670   if (is_java_primitive(bt)) {
 671     assert(s->utf8_length() == 1, "");
 672     return java_lang_Class::primitive_mirror(bt);
 673   }
 674   // Here are some more short cuts for common types.
 675   // They are optional, since reference types can be resolved lazily.
 676   if (bt == T_OBJECT) {
 677     if (s == vmSymbols::object_signature()) {
 678       return object_java_mirror();
 679     } else if (s == vmSymbols::class_signature()) {
 680       return vmClasses::Class_klass()->java_mirror();
 681     } else if (s == vmSymbols::string_signature()) {
 682       return vmClasses::String_klass()->java_mirror();
 683     }
 684   }
 685   return nullptr;
 686 }
 687 
 688 // An unresolved member name is a mere symbolic reference.
 689 // Resolving it plants a vmtarget/vmindex in it,
 690 // which refers directly to JVM internals.
 691 Handle MethodHandles::resolve_MemberName(Handle mname, Klass* caller, int lookup_mode,
 692                                          bool speculative_resolve, TRAPS) {
 693   Handle empty;
 694   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 695 
 696   if (java_lang_invoke_MemberName::vmtarget(mname()) != nullptr) {
 697     // Already resolved.
 698     DEBUG_ONLY(intptr_t vmindex = java_lang_invoke_MemberName::vmindex(mname()));
 699     assert(vmindex >= Method::nonvirtual_vtable_index, "");
 700     return mname;
 701   }
 702 
 703   Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
 704   Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
 705   Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
 706   int    flags    =       java_lang_invoke_MemberName::flags(mname());
 707   int    ref_kind =       (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
 708   if (!ref_kind_is_valid(ref_kind)) {
 709     THROW_MSG_(vmSymbols::java_lang_InternalError(), "obsolete MemberName format", empty);
 710   }
 711 
 712   DEBUG_ONLY(intptr_t old_vmindex);
 713   assert((old_vmindex = java_lang_invoke_MemberName::vmindex(mname())) == 0, "clean input");
 714 
 715   if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
 716     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve", empty);
 717   }
 718 
 719   InstanceKlass* defc = nullptr;
 720   {
 721     Klass* defc_klass = java_lang_Class::as_Klass(defc_oop());
 722     if (defc_klass == nullptr)  return empty;  // a primitive; no resolution possible
 723     if (!defc_klass->is_instance_klass()) {
 724       if (!defc_klass->is_array_klass())  return empty;
 725       defc_klass = vmClasses::Object_klass();
 726     }
 727     defc = InstanceKlass::cast(defc_klass);
 728   }
 729   if (defc == nullptr) {
 730     THROW_MSG_(vmSymbols::java_lang_InternalError(), "primitive class", empty);
 731   }
 732   defc->link_class(CHECK_(empty));  // possible safepoint
 733 
 734   // convert the external string name to an internal symbol
 735   TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
 736   if (name == nullptr)  return empty;  // no such name
 737   if (name == vmSymbols::class_initializer_name())
 738     return empty; // illegal name
 739 
 740   vmIntrinsics::ID mh_invoke_id = vmIntrinsics::_none;
 741   if ((flags & ALL_KINDS) == IS_METHOD &&
 742       (defc == vmClasses::MethodHandle_klass() || defc == vmClasses::VarHandle_klass()) &&
 743       (ref_kind == JVM_REF_invokeVirtual ||
 744        ref_kind == JVM_REF_invokeSpecial ||
 745        // static invocation mode is required for _linkToVirtual, etc.:
 746        ref_kind == JVM_REF_invokeStatic)) {
 747     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 748     if (iid != vmIntrinsics::_none &&
 749         ((ref_kind == JVM_REF_invokeStatic) == is_signature_polymorphic_static(iid))) {
 750       // Virtual methods invoke and invokeExact, plus internal invokers like _invokeBasic.
 751       // For a static reference it could an internal linkage routine like _linkToVirtual, etc.
 752       mh_invoke_id = iid;
 753     }
 754   }
 755 
 756   // convert the external string or reflective type to an internal signature
 757   TempNewSymbol type = lookup_signature(type_str(), (mh_invoke_id != vmIntrinsics::_none), CHECK_(empty));
 758   if (type == nullptr)  return empty;  // no such signature exists in the VM
 759 
 760   // skip access check if it's trusted lookup
 761   LinkInfo::AccessCheck access_check = caller != nullptr ?
 762                                               LinkInfo::AccessCheck::required :
 763                                               LinkInfo::AccessCheck::skip;
 764   // skip loader constraints if it's trusted lookup or a public lookup
 765   LinkInfo::LoaderConstraintCheck loader_constraint_check = (caller != nullptr && (lookup_mode & LM_UNCONDITIONAL) == 0) ?
 766                                               LinkInfo::LoaderConstraintCheck::required :
 767                                               LinkInfo::LoaderConstraintCheck::skip;
 768 
 769   // Time to do the lookup.
 770   switch (flags & ALL_KINDS) {
 771   case IS_METHOD:
 772     {
 773       CallInfo result;
 774       LinkInfo link_info(defc, name, type, caller, access_check, loader_constraint_check);
 775       {
 776         assert(!HAS_PENDING_EXCEPTION, "");
 777         if (ref_kind == JVM_REF_invokeStatic) {
 778           LinkResolver::resolve_static_call(result,
 779                         link_info, false, THREAD);
 780         } else if (ref_kind == JVM_REF_invokeInterface) {
 781           LinkResolver::resolve_interface_call(result, Handle(), defc,
 782                         link_info, false, THREAD);
 783         } else if (mh_invoke_id != vmIntrinsics::_none) {
 784           assert(!is_signature_polymorphic_static(mh_invoke_id), "");
 785           LinkResolver::resolve_handle_call(result, link_info, THREAD);
 786         } else if (ref_kind == JVM_REF_invokeSpecial) {
 787           LinkResolver::resolve_special_call(result, Handle(),
 788                         link_info, THREAD);
 789         } else if (ref_kind == JVM_REF_invokeVirtual) {
 790           LinkResolver::resolve_virtual_call(result, Handle(), defc,
 791                         link_info, false, THREAD);
 792         } else {
 793           assert(false, "ref_kind=%d", ref_kind);
 794         }
 795         if (HAS_PENDING_EXCEPTION) {
 796           if (speculative_resolve) {
 797             CLEAR_PENDING_EXCEPTION;
 798           }
 799           return empty;
 800         }
 801       }
 802       if (result.resolved_appendix().not_null()) {
 803         // The resolved MemberName must not be accompanied by an appendix argument,
 804         // since there is no way to bind this value into the MemberName.
 805         // Caller is responsible to prevent this from happening.
 806         THROW_MSG_(vmSymbols::java_lang_InternalError(), "appendix", empty);
 807       }
 808       result.set_resolved_method_name(CHECK_(empty));
 809       oop mname2 = init_method_MemberName(mname, result);
 810       return Handle(THREAD, mname2);
 811     }
 812   case IS_OBJECT_CONSTRUCTOR:
 813     {
 814       CallInfo result;
 815       LinkInfo link_info(defc, name, type, caller, access_check, loader_constraint_check);
 816       {
 817         assert(!HAS_PENDING_EXCEPTION, "");
 818         if (name == vmSymbols::object_initializer_name() && type->is_void_method_signature()) {
 819           LinkResolver::resolve_special_call(result, Handle(), link_info, THREAD);
 820         } else {
 821           break;                // will throw after end of switch
 822         }
 823         if (HAS_PENDING_EXCEPTION) {
 824           if (speculative_resolve) {
 825             CLEAR_PENDING_EXCEPTION;
 826           }
 827           return empty;
 828         }
 829       }
 830       assert(result.is_statically_bound(), "");
 831       result.set_resolved_method_name(CHECK_(empty));
 832       oop mname2 = init_method_MemberName(mname, result);
 833       return Handle(THREAD, mname2);
 834     }
 835   case IS_FIELD:
 836     {
 837       fieldDescriptor result; // find_field initializes fd if found
 838       {
 839         assert(!HAS_PENDING_EXCEPTION, "");
 840         LinkInfo link_info(defc, name, type, caller, LinkInfo::AccessCheck::skip, loader_constraint_check);
 841         LinkResolver::resolve_field(result, link_info, Bytecodes::_nop, false, THREAD);
 842         if (HAS_PENDING_EXCEPTION) {
 843           if (speculative_resolve) {
 844             CLEAR_PENDING_EXCEPTION;
 845           }
 846           return empty;
 847         }
 848       }
 849       oop mname2 = init_field_MemberName(mname, result, ref_kind_is_setter(ref_kind));
 850       return Handle(THREAD, mname2);
 851     }
 852   default:
 853     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format", empty);
 854   }
 855 
 856   return empty;
 857 }
 858 
 859 // Conversely, a member name which is only initialized from JVM internals
 860 // may have null defc, name, and type fields.
 861 // Resolving it plants a vmtarget/vmindex in it,
 862 // which refers directly to JVM internals.
 863 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
 864   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 865 
 866   bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != nullptr);
 867   bool have_name = (java_lang_invoke_MemberName::name(mname()) != nullptr);
 868   bool have_type = (java_lang_invoke_MemberName::type(mname()) != nullptr);
 869   int flags      = java_lang_invoke_MemberName::flags(mname());
 870 
 871   if (suppress != 0) {
 872     if (suppress & _suppress_defc)  have_defc = true;
 873     if (suppress & _suppress_name)  have_name = true;
 874     if (suppress & _suppress_type)  have_type = true;
 875   }
 876 
 877   if (have_defc && have_name && have_type)  return;  // nothing needed
 878 
 879   switch (flags & ALL_KINDS) {
 880   case IS_METHOD:
 881   case IS_OBJECT_CONSTRUCTOR:
 882     {
 883       Method* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
 884       if (vmtarget == nullptr) {
 885         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
 886       }
 887       methodHandle m(THREAD, vmtarget);
 888       DEBUG_ONLY(vmtarget = nullptr);  // safety
 889       if (!have_defc) {
 890         InstanceKlass* defc = m->method_holder();
 891         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 892       }
 893       if (!have_name) {
 894         //not java_lang_String::create_from_symbol; let's intern member names
 895         oop name = StringTable::intern(m->name(), CHECK);
 896         java_lang_invoke_MemberName::set_name(mname(), name);
 897       }
 898       if (!have_type) {
 899         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
 900         java_lang_invoke_MemberName::set_type(mname(), type());
 901       }
 902       return;
 903     }
 904   case IS_FIELD:
 905     {
 906       oop clazz = java_lang_invoke_MemberName::clazz(mname());
 907       if (clazz == nullptr) {
 908         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand (as field)");
 909       }
 910       InstanceKlass* defc = InstanceKlass::cast(java_lang_Class::as_Klass(clazz));
 911       DEBUG_ONLY(clazz = nullptr);  // safety
 912       intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
 913       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
 914       fieldDescriptor fd; // find_field initializes fd if found
 915       if (!defc->find_field_from_offset(checked_cast<int>(vmindex), is_static, &fd))
 916         break;                  // cannot expand
 917       if (!have_name) {
 918         //not java_lang_String::create_from_symbol; let's intern member names
 919         oop name = StringTable::intern(fd.name(), CHECK);
 920         java_lang_invoke_MemberName::set_name(mname(), name);
 921       }
 922       if (!have_type) {
 923         // If it is a primitive field type, don't mess with short strings like "I".
 924         Handle type (THREAD, field_signature_type_or_null(fd.signature()));
 925         if (type.is_null()) {
 926           type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
 927         }
 928         java_lang_invoke_MemberName::set_type(mname(), type());
 929       }
 930       return;
 931     }
 932   }
 933   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 934 }
 935 
 936 void MethodHandles::add_dependent_nmethod(oop call_site, nmethod* nm) {
 937   assert_locked_or_safepoint(CodeCache_lock);
 938 
 939   oop context = java_lang_invoke_CallSite::context_no_keepalive(call_site);
 940   DependencyContext deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 941   // Try to purge stale entries on updates.
 942   // Since GC doesn't clean dependency contexts rooted at CallSiteContext objects,
 943   // in order to avoid memory leak, stale entries are purged whenever a dependency list
 944   // is changed (both on addition and removal). Though memory reclamation is delayed,
 945   // it avoids indefinite memory usage growth.
 946   deps.add_dependent_nmethod(nm);
 947 }
 948 
 949 void MethodHandles::clean_dependency_context(oop call_site) {
 950   oop context = java_lang_invoke_CallSite::context_no_keepalive(call_site);
 951   DependencyContext deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 952   deps.clean_unloading_dependents();
 953 }
 954 
 955 void MethodHandles::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, Handle call_site, Handle target) {
 956   assert_lock_strong(Compile_lock);
 957 
 958   CallSiteDepChange changes(call_site, target);
 959   {
 960     NoSafepointVerifier nsv;
 961     MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 962 
 963     oop context = java_lang_invoke_CallSite::context_no_keepalive(call_site());
 964     DependencyContext deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 965     deps.mark_dependent_nmethods(deopt_scope, changes);
 966   }
 967 }
 968 
 969 void MethodHandles::trace_method_handle_interpreter_entry(MacroAssembler* _masm, vmIntrinsics::ID iid) {
 970   if (log_is_enabled(Info, methodhandles)) {
 971     const char* name = vmIntrinsics::name_at(iid);
 972     if (*name == '_')  name += 1;
 973     const size_t len = strlen(name) + 50;
 974     char* qname = NEW_C_HEAP_ARRAY(char, len, mtInternal);
 975     const char* suffix = "";
 976     if (is_signature_polymorphic(iid)) {
 977       if (is_signature_polymorphic_static(iid))
 978         suffix = "/static";
 979       else
 980         suffix = "/private";
 981     }
 982     jio_snprintf(qname, len, "MethodHandle::interpreter_entry::%s%s", name, suffix);
 983     trace_method_handle(_masm, qname);
 984     // LSan appears unable to keep track of qname, ignore it.
 985     LSAN_IGNORE_OBJECT(qname);
 986     // Note:  Don't free the allocated char array because it's used
 987     // during runtime.
 988   }
 989 }
 990 
 991 //
 992 // Here are the native methods in java.lang.invoke.MethodHandleNatives
 993 // They are the private interface between this JVM and the HotSpot-specific
 994 // Java code that implements JSR 292 method handles.
 995 //
 996 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
 997 // that intrinsic (non-JNI) native methods are defined in HotSpot.
 998 //
 999 
1000 #ifndef PRODUCT
1001 #define EACH_NAMED_CON(template, requirement) \
1002     template(java_lang_invoke_MemberName,MN_IS_METHOD) \
1003     template(java_lang_invoke_MemberName,MN_IS_OBJECT_CONSTRUCTOR) \
1004     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
1005     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
1006     template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
1007     template(java_lang_invoke_MemberName,MN_TRUSTED_FINAL) \
1008     template(java_lang_invoke_MemberName,MN_HIDDEN_MEMBER) \
1009     template(java_lang_invoke_MemberName,MN_FLAT_FIELD) \
1010     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
1011     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_MASK) \
1012     template(java_lang_invoke_MemberName,MN_NESTMATE_CLASS) \
1013     template(java_lang_invoke_MemberName,MN_HIDDEN_CLASS) \
1014     template(java_lang_invoke_MemberName,MN_STRONG_LOADER_LINK) \
1015     template(java_lang_invoke_MemberName,MN_ACCESS_VM_ANNOTATIONS) \
1016     template(java_lang_invoke_MemberName,MN_MODULE_MODE) \
1017     template(java_lang_invoke_MemberName,MN_UNCONDITIONAL_MODE) \
1018     template(java_lang_invoke_MemberName,MN_TRUSTED_MODE) \
1019     /*end*/
1020 
1021 #define IGNORE_REQ(req_expr) /* req_expr */
1022 #define ONE_PLUS(scope,value) 1+
1023 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS, IGNORE_REQ) 0;
1024 #define VALUE_COMMA(scope,value) scope::value,
1025 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA, IGNORE_REQ) 0 };
1026 #define STRING_NULL(scope,value) #value "\0"
1027 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL, IGNORE_REQ) };
1028 
1029 static bool advertise_con_value(int which) {
1030   if (which < 0)  return false;
1031   bool ok = true;
1032   int count = 0;
1033 #define INC_COUNT(scope,value) \
1034   ++count;
1035 #define CHECK_REQ(req_expr) \
1036   if (which < count)  return ok; \
1037   ok = (req_expr);
1038   EACH_NAMED_CON(INC_COUNT, CHECK_REQ);
1039 #undef INC_COUNT
1040 #undef CHECK_REQ
1041   assert(count == con_value_count, "");
1042   if (which < count)  return ok;
1043   return false;
1044 }
1045 
1046 #undef ONE_PLUS
1047 #undef VALUE_COMMA
1048 #undef STRING_NULL
1049 #undef EACH_NAMED_CON
1050 #endif // PRODUCT
1051 
1052 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
1053 #ifndef PRODUCT
1054   if (advertise_con_value(which)) {
1055     assert(which >= 0 && which < con_value_count, "");
1056     int con = con_values[which];
1057     objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
1058     if (box.not_null() && box->klass() == Universe::objectArrayKlass() && box->length() > 0) {
1059       const char* str = &con_names[0];
1060       for (int i = 0; i < which; i++)
1061         str += strlen(str) + 1;   // skip name and null
1062       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
1063       box->obj_at_put(0, name);
1064     }
1065     return con;
1066   }
1067 #endif
1068   return 0;
1069 }
1070 JVM_END
1071 
1072 // void init(MemberName self, AccessibleObject ref)
1073 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
1074   if (mname_jh == nullptr) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1075   if (target_jh == nullptr) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
1076   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1077   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
1078   MethodHandles::init_MemberName(mname, target, CHECK);
1079 }
1080 JVM_END
1081 
1082 // void expand(MemberName self)
1083 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1084   if (mname_jh == nullptr) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1085   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1086   MethodHandles::expand_MemberName(mname, 0, CHECK);
1087 }
1088 JVM_END
1089 
1090 // void resolve(MemberName self, Class<?> caller)
1091 JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh,
1092     jint lookup_mode, jboolean speculative_resolve)) {
1093   if (mname_jh == nullptr) { THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "mname is null"); }
1094   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1095 
1096   // The trusted Java code that calls this method should already have performed
1097   // access checks on behalf of the given caller.  But, we can verify this.
1098   // This only verifies from the context of the lookup class.  It does not
1099   // verify the lookup context for a Lookup object teleported from one module
1100   // to another. Such Lookup object can only access the intersection of the set
1101   // of accessible classes from both lookup class and previous lookup class.
1102   if (VerifyMethodHandles && (lookup_mode & LM_TRUSTED) == LM_TRUSTED && caller_jh != nullptr &&
1103       java_lang_invoke_MemberName::clazz(mname()) != nullptr) {
1104     Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname()));
1105     if (reference_klass != nullptr && reference_klass->is_objArray_klass()) {
1106       reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass();
1107     }
1108 
1109     // Reflection::verify_class_access can only handle instance classes.
1110     if (reference_klass != nullptr && reference_klass->is_instance_klass()) {
1111       // Emulate LinkResolver::check_klass_accessability.
1112       Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
1113       // access check on behalf of the caller if this is not a public lookup
1114       // i.e. lookup mode is not UNCONDITIONAL
1115       if ((lookup_mode & LM_UNCONDITIONAL) == 0
1116           && Reflection::verify_class_access(caller,
1117                                              InstanceKlass::cast(reference_klass),
1118                                              true) != Reflection::ACCESS_OK) {
1119         ResourceMark rm(THREAD);
1120         stringStream ss;
1121         ss.print("caller %s tried to access %s", caller->class_in_module_of_loader(),
1122                  reference_klass->class_in_module_of_loader());
1123         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), ss.as_string());
1124       }
1125     }
1126   }
1127 
1128   Klass* caller = caller_jh == nullptr ? nullptr :
1129                      java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
1130   Handle resolved = MethodHandles::resolve_MemberName(mname, caller, lookup_mode,
1131                                                       speculative_resolve == JNI_TRUE,
1132                                                       CHECK_NULL);
1133 
1134   if (resolved.is_null()) {
1135     int flags = java_lang_invoke_MemberName::flags(mname());
1136     int ref_kind = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
1137     if (!MethodHandles::ref_kind_is_valid(ref_kind)) {
1138       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "obsolete MemberName format");
1139     }
1140     if (speculative_resolve) {
1141       assert(!HAS_PENDING_EXCEPTION, "No exceptions expected when resolving speculatively");
1142       return nullptr;
1143     }
1144     if ((flags & ALL_KINDS) == IS_FIELD) {
1145       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchFieldError(), "field resolution failed");
1146     } else if ((flags & ALL_KINDS) == IS_METHOD ||
1147                (flags & ALL_KINDS) == IS_OBJECT_CONSTRUCTOR) {
1148       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), "method resolution failed");
1149     } else {
1150       THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "resolution failed");
1151     }
1152   }
1153 
1154   return JNIHandles::make_local(THREAD, resolved());
1155 }
1156 JVM_END
1157 
1158 static jlong find_member_field_offset(oop mname, bool must_be_static, TRAPS) {
1159   if (mname == nullptr ||
1160       java_lang_invoke_MemberName::clazz(mname) == nullptr) {
1161     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "mname not resolved");
1162   } else {
1163     int flags = java_lang_invoke_MemberName::flags(mname);
1164     if ((flags & IS_FIELD) != 0 &&
1165         (must_be_static
1166          ? (flags & JVM_ACC_STATIC) != 0
1167          : (flags & JVM_ACC_STATIC) == 0)) {
1168       intptr_t vmindex = java_lang_invoke_MemberName::vmindex(mname);
1169       return (jlong) vmindex;
1170     }
1171   }
1172   const char* msg = (must_be_static ? "static field required" : "non-static field required");
1173   THROW_MSG_0(vmSymbols::java_lang_InternalError(), msg);
1174   return 0;
1175 }
1176 
1177 JVM_ENTRY(jlong, MHN_objectFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1178   return find_member_field_offset(JNIHandles::resolve(mname_jh), false, THREAD);
1179 }
1180 JVM_END
1181 
1182 JVM_ENTRY(jlong, MHN_staticFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1183   return find_member_field_offset(JNIHandles::resolve(mname_jh), true, THREAD);
1184 }
1185 JVM_END
1186 
1187 JVM_ENTRY(jobject, MHN_staticFieldBase(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1188   // use the other function to perform sanity checks:
1189   jlong ignore = find_member_field_offset(JNIHandles::resolve(mname_jh), true, CHECK_NULL);
1190   oop clazz = java_lang_invoke_MemberName::clazz(JNIHandles::resolve_non_null(mname_jh));
1191   return JNIHandles::make_local(THREAD, clazz);
1192 }
1193 JVM_END
1194 
1195 JVM_ENTRY(jobject, MHN_getMemberVMInfo(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1196   if (mname_jh == nullptr)  return nullptr;
1197   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1198   intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
1199   objArrayHandle result = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 2, CHECK_NULL);
1200   jvalue vmindex_value; vmindex_value.j = (long)vmindex;
1201   oop x = java_lang_boxing_object::create(T_LONG, &vmindex_value, CHECK_NULL);
1202   result->obj_at_put(0, x);
1203 
1204   int flags = java_lang_invoke_MemberName::flags(mname());
1205   if ((flags & IS_FIELD) != 0) {
1206     x = java_lang_invoke_MemberName::clazz(mname());
1207   } else {
1208     Method* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
1209     assert(vmtarget != nullptr && vmtarget->is_method(), "vmtarget is only method");
1210     x = mname();
1211   }
1212   result->obj_at_put(1, x);
1213   return JNIHandles::make_local(THREAD, result());
1214 }
1215 JVM_END
1216 
1217 JVM_ENTRY(void, MHN_setCallSiteTargetNormal(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1218   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1219   Handle target   (THREAD, JNIHandles::resolve_non_null(target_jh));
1220   DeoptimizationScope deopt_scope;
1221   {
1222     // Walk all nmethods depending on this call site.
1223     MutexLocker mu(thread, Compile_lock);
1224     MethodHandles::mark_dependent_nmethods(&deopt_scope, call_site, target);
1225     java_lang_invoke_CallSite::set_target(call_site(), target());
1226     // This is assumed to be an 'atomic' operation by verification.
1227     // So keep it under lock for now.
1228     deopt_scope.deoptimize_marked();
1229   }
1230 }
1231 JVM_END
1232 
1233 JVM_ENTRY(void, MHN_setCallSiteTargetVolatile(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1234   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1235   Handle target   (THREAD, JNIHandles::resolve_non_null(target_jh));
1236   DeoptimizationScope deopt_scope;
1237   {
1238     // Walk all nmethods depending on this call site.
1239     MutexLocker mu(thread, Compile_lock);
1240     MethodHandles::mark_dependent_nmethods(&deopt_scope, call_site, target);
1241     java_lang_invoke_CallSite::set_target_volatile(call_site(), target());
1242     // This is assumed to be an 'atomic' operation by verification.
1243     // So keep it under lock for now.
1244     deopt_scope.deoptimize_marked();
1245   }
1246 }
1247 JVM_END
1248 
1249 JVM_ENTRY(void, MHN_copyOutBootstrapArguments(JNIEnv* env, jobject igcls,
1250                                               jobject caller_jh, jintArray index_info_jh,
1251                                               jint start, jint end,
1252                                               jobjectArray buf_jh, jint pos,
1253                                               jboolean resolve, jobject ifna_jh)) {
1254   Klass* caller_k = java_lang_Class::as_Klass(JNIHandles::resolve(caller_jh));
1255   if (caller_k == nullptr || !caller_k->is_instance_klass()) {
1256       THROW_MSG(vmSymbols::java_lang_InternalError(), "bad caller");
1257   }
1258   InstanceKlass* caller = InstanceKlass::cast(caller_k);
1259   typeArrayOop index_info_oop = (typeArrayOop) JNIHandles::resolve(index_info_jh);
1260   if (index_info_oop == nullptr ||
1261       index_info_oop->klass() != Universe::intArrayKlass() ||
1262       typeArrayOop(index_info_oop)->length() < 2) {
1263       THROW_MSG(vmSymbols::java_lang_InternalError(), "bad index info (0)");
1264   }
1265   typeArrayHandle index_info(THREAD, index_info_oop);
1266   int bss_index_in_pool = index_info->int_at(1);
1267   // While we are here, take a quick look at the index info:
1268   if (bss_index_in_pool <= 0 ||
1269       bss_index_in_pool >= caller->constants()->length() ||
1270       index_info->int_at(0)
1271       != caller->constants()->bootstrap_argument_count_at(bss_index_in_pool)) {
1272       THROW_MSG(vmSymbols::java_lang_InternalError(), "bad index info (1)");
1273   }
1274   objArrayHandle buf(THREAD, (objArrayOop) JNIHandles::resolve(buf_jh));
1275   if (start < 0) {
1276     for (int pseudo_index = -4; pseudo_index < 0; pseudo_index++) {
1277       if (start == pseudo_index) {
1278         if (start >= end || 0 > pos || pos >= buf->length())  break;
1279         oop pseudo_arg = nullptr;
1280         switch (pseudo_index) {
1281         case -4:  // bootstrap method
1282           {
1283             int bsm_index = caller->constants()->bootstrap_method_ref_index_at(bss_index_in_pool);
1284             pseudo_arg = caller->constants()->resolve_possibly_cached_constant_at(bsm_index, CHECK);
1285             break;
1286           }
1287         case -3:  // name
1288           {
1289             Symbol* name = caller->constants()->name_ref_at(bss_index_in_pool, Bytecodes::_invokedynamic);
1290             Handle str = java_lang_String::create_from_symbol(name, CHECK);
1291             pseudo_arg = str();
1292             break;
1293           }
1294         case -2:  // type
1295           {
1296             Symbol* type = caller->constants()->signature_ref_at(bss_index_in_pool, Bytecodes::_invokedynamic);
1297             Handle th;
1298             if (type->char_at(0) == JVM_SIGNATURE_FUNC) {
1299               th = SystemDictionary::find_method_handle_type(type, caller, CHECK);
1300             } else {
1301               th = SystemDictionary::find_java_mirror_for_type(type, caller, SignatureStream::NCDFError, CHECK);
1302             }
1303             pseudo_arg = th();
1304             break;
1305           }
1306         case -1:  // argument count
1307           {
1308             int argc = caller->constants()->bootstrap_argument_count_at(bss_index_in_pool);
1309             jvalue argc_value; argc_value.i = (jint)argc;
1310             pseudo_arg = java_lang_boxing_object::create(T_INT, &argc_value, CHECK);
1311             break;
1312           }
1313         }
1314 
1315         // Store the pseudo-argument, and advance the pointers.
1316         buf->obj_at_put(pos++, pseudo_arg);
1317         ++start;
1318       }
1319     }
1320     // When we are done with this there may be regular arguments to process too.
1321   }
1322   Handle ifna(THREAD, JNIHandles::resolve(ifna_jh));
1323   caller->constants()->
1324     copy_bootstrap_arguments_at(bss_index_in_pool,
1325                                 start, end, buf, pos,
1326                                 (resolve == JNI_TRUE), ifna, CHECK);
1327 }
1328 JVM_END
1329 
1330 // It is called by a Cleaner object which ensures that dropped CallSites properly
1331 // deallocate their dependency information.
1332 JVM_ENTRY(void, MHN_clearCallSiteContext(JNIEnv* env, jobject igcls, jobject context_jh)) {
1333   Handle context(THREAD, JNIHandles::resolve_non_null(context_jh));
1334   DeoptimizationScope deopt_scope;
1335   {
1336     NoSafepointVerifier nsv;
1337     MutexLocker ml(THREAD, CodeCache_lock, Mutex::_no_safepoint_check_flag);
1338     DependencyContext deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context());
1339     deps.remove_and_mark_for_deoptimization_all_dependents(&deopt_scope);
1340     // This is assumed to be an 'atomic' operation by verification.
1341     // So keep it under lock for now.
1342     deopt_scope.deoptimize_marked();
1343   }
1344 }
1345 JVM_END
1346 
1347 /**
1348  * Throws a java/lang/UnsupportedOperationException unconditionally.
1349  * This is required by the specification of MethodHandle.invoke if
1350  * invoked directly.
1351  */
1352 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1353   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
1354   return nullptr;
1355 }
1356 JVM_END
1357 
1358 /**
1359  * Throws a java/lang/UnsupportedOperationException unconditionally.
1360  * This is required by the specification of MethodHandle.invokeExact if
1361  * invoked directly.
1362  */
1363 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1364   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
1365   return nullptr;
1366 }
1367 JVM_END
1368 
1369 /**
1370  * Throws a java/lang/UnsupportedOperationException unconditionally.
1371  * This is required by the specification of VarHandle.{access-mode} if
1372  * invoked directly.
1373  */
1374 JVM_ENTRY(jobject, VH_UOE(JNIEnv* env, jobject vh, jobjectArray args)) {
1375   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "VarHandle access mode methods cannot be invoked reflectively");
1376   return nullptr;
1377 }
1378 JVM_END
1379 
1380 
1381 /// JVM_RegisterMethodHandleMethods
1382 
1383 #define LANG "Ljava/lang/"
1384 #define JLINV "Ljava/lang/invoke/"
1385 
1386 #define OBJ   LANG "Object;"
1387 #define CLS   LANG "Class;"
1388 #define STRG  LANG "String;"
1389 #define CS    JLINV "CallSite;"
1390 #define MT    JLINV "MethodType;"
1391 #define MH    JLINV "MethodHandle;"
1392 #define MEM   JLINV "MemberName;"
1393 #define CTX   JLINV "MethodHandleNatives$CallSiteContext;"
1394 
1395 #define CC (char*)  /*cast a literal from (const char*)*/
1396 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1397 
1398 // These are the native methods on java.lang.invoke.MethodHandleNatives.
1399 static JNINativeMethod MHN_methods[] = {
1400   {CC "init",                      CC "(" MEM "" OBJ ")V",                   FN_PTR(MHN_init_Mem)},
1401   {CC "expand",                    CC "(" MEM ")V",                          FN_PTR(MHN_expand_Mem)},
1402   {CC "resolve",                   CC "(" MEM "" CLS "IZ)" MEM,              FN_PTR(MHN_resolve_Mem)},
1403   //  static native int getNamedCon(int which, Object[] name)
1404   {CC "getNamedCon",               CC "(I[" OBJ ")I",                        FN_PTR(MHN_getNamedCon)},
1405   {CC "objectFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_objectFieldOffset)},
1406   {CC "setCallSiteTargetNormal",   CC "(" CS "" MH ")V",                     FN_PTR(MHN_setCallSiteTargetNormal)},
1407   {CC "setCallSiteTargetVolatile", CC "(" CS "" MH ")V",                     FN_PTR(MHN_setCallSiteTargetVolatile)},
1408   {CC "copyOutBootstrapArguments", CC "(" CLS "[III[" OBJ "IZ" OBJ ")V",     FN_PTR(MHN_copyOutBootstrapArguments)},
1409   {CC "clearCallSiteContext",      CC "(" CTX ")V",                          FN_PTR(MHN_clearCallSiteContext)},
1410   {CC "staticFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_staticFieldOffset)},
1411   {CC "staticFieldBase",           CC "(" MEM ")" OBJ,                        FN_PTR(MHN_staticFieldBase)},
1412   {CC "getMemberVMInfo",           CC "(" MEM ")" OBJ,                       FN_PTR(MHN_getMemberVMInfo)}
1413 };
1414 
1415 static JNINativeMethod MH_methods[] = {
1416   // UnsupportedOperationException throwers
1417   {CC "invoke",                    CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invoke_UOE)},
1418   {CC "invokeExact",               CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invokeExact_UOE)}
1419 };
1420 static JNINativeMethod VH_methods[] = {
1421   // UnsupportedOperationException throwers
1422   {CC "get",                        CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1423   {CC "set",                        CC "([" OBJ ")V",       FN_PTR(VH_UOE)},
1424   {CC "getVolatile",                CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1425   {CC "setVolatile",                CC "([" OBJ ")V",       FN_PTR(VH_UOE)},
1426   {CC "getAcquire",                 CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1427   {CC "setRelease",                 CC "([" OBJ ")V",       FN_PTR(VH_UOE)},
1428   {CC "getOpaque",                  CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1429   {CC "setOpaque",                  CC "([" OBJ ")V",       FN_PTR(VH_UOE)},
1430   {CC "compareAndSet",              CC "([" OBJ ")Z",       FN_PTR(VH_UOE)},
1431   {CC "compareAndExchange",         CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1432   {CC "compareAndExchangeAcquire",  CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1433   {CC "compareAndExchangeRelease",  CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1434   {CC "weakCompareAndSetPlain",     CC "([" OBJ ")Z",       FN_PTR(VH_UOE)},
1435   {CC "weakCompareAndSet",          CC "([" OBJ ")Z",       FN_PTR(VH_UOE)},
1436   {CC "weakCompareAndSetAcquire",   CC "([" OBJ ")Z",       FN_PTR(VH_UOE)},
1437   {CC "weakCompareAndSetRelease",   CC "([" OBJ ")Z",       FN_PTR(VH_UOE)},
1438   {CC "getAndSet",                  CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1439   {CC "getAndSetAcquire",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1440   {CC "getAndSetRelease",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1441   {CC "getAndAdd",                  CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1442   {CC "getAndAddAcquire",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1443   {CC "getAndAddRelease",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1444   {CC "getAndBitwiseOr",            CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1445   {CC "getAndBitwiseOrAcquire",     CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1446   {CC "getAndBitwiseOrRelease",     CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1447   {CC "getAndBitwiseAnd",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1448   {CC "getAndBitwiseAndAcquire",    CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1449   {CC "getAndBitwiseAndRelease",    CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1450   {CC "getAndBitwiseXor",           CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1451   {CC "getAndBitwiseXorAcquire",    CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)},
1452   {CC "getAndBitwiseXorRelease",    CC "([" OBJ ")" OBJ,    FN_PTR(VH_UOE)}
1453 };
1454 
1455 /**
1456  * This one function is exported, used by NativeLookup.
1457  */
1458 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
1459   assert(!MethodHandles::enabled(), "must not be enabled");
1460   assert(vmClasses::MethodHandle_klass() != nullptr, "should be present");
1461   assert(vmClasses::VarHandle_klass() != nullptr, "should be present");
1462 
1463   oop mh_mirror = vmClasses::MethodHandle_klass()->java_mirror();
1464   oop vh_mirror = vmClasses::VarHandle_klass()->java_mirror();
1465   jclass MH_class = (jclass) JNIHandles::make_local(THREAD, mh_mirror);
1466   jclass VH_class = (jclass) JNIHandles::make_local(THREAD, vh_mirror);
1467 
1468   {
1469     ThreadToNativeFromVM ttnfv(thread);
1470 
1471     int status = env->RegisterNatives(MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
1472     guarantee(status == JNI_OK && !env->ExceptionOccurred(),
1473               "register java.lang.invoke.MethodHandleNative natives");
1474 
1475     status = env->RegisterNatives(MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
1476     guarantee(status == JNI_OK && !env->ExceptionOccurred(),
1477               "register java.lang.invoke.MethodHandle natives");
1478 
1479     status = env->RegisterNatives(VH_class, VH_methods, sizeof(VH_methods)/sizeof(JNINativeMethod));
1480     guarantee(status == JNI_OK && !env->ExceptionOccurred(),
1481               "register java.lang.invoke.VarHandle natives");
1482   }
1483 
1484   log_debug(methodhandles, indy)("MethodHandle support loaded (using LambdaForms)");
1485 
1486   MethodHandles::set_enabled(true);
1487 }
1488 JVM_END