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