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