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