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