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