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