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