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