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