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