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