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