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