src/share/vm/prims/methodHandles.cpp

Sat, 07 Nov 2020 10:30:02 +0800

author
aoqi
date
Sat, 07 Nov 2020 10:30:02 +0800
changeset 10026
8c95980d0b66
parent 9931
fd44df5e3bc3
permissions
-rw-r--r--

Added tag mips-jdk8u275-b01 for changeset d3b4d62f391f

     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  */
    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"
    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  */
    55 bool MethodHandles::_enabled = false; // set true after successful native linkage
    56 MethodHandlesAdapterBlob* MethodHandles::_adapter_code = NULL;
    58 //------------------------------------------------------------------------------
    59 // MethodHandles::generate_adapters
    60 //
    61 void MethodHandles::generate_adapters() {
    62   if (!EnableInvokeDynamic || SystemDictionary::MethodHandle_klass() == NULL)  return;
    64   assert(_adapter_code == NULL, "generate only once");
    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 }
    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 }
    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 }
   106 // MemberName support
   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 };
   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 }
   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 }
   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;
   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;
   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;
   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;
   255   default:  assert(false, "bad CallInfo");  return NULL;
   256   }
   258   // @CallerSensitive annotation detected
   259   if (m->caller_sensitive()) {
   260     flags |= CALLER_SENSITIVE;
   261   }
   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 }
   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 }
   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 }
   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 }
   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 }
   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;
   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   }
   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;
   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 }
   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 }
   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 }
   410 static const char OBJ_SIG[] = "Ljava/lang/Object;";
   411 enum { OBJ_SIG_LEN = 18 };
   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 }
   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 }
   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 }
   557 static oop object_java_mirror() {
   558   return SystemDictionary::Object_klass()->java_mirror();
   559 }
   561 oop MethodHandles::field_name_or_null(Symbol* s) {
   562   if (s == NULL)  return NULL;
   563   return StringTable::lookup(s);
   564 }
   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 }
   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()), "");
   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   }
   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   }
   611   DEBUG_ONLY(int old_vmindex);
   612   assert((old_vmindex = java_lang_invoke_MemberName::vmindex(mname())) == 0, "clean input");
   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   }
   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
   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
   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   }
   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
   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   }
   734   return empty;
   735 }
   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   }
   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());
   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   }
   760   if (have_defc && have_name && have_type)  return;  // nothing needed
   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 }
   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!
   823   Thread* thread = Thread::current();
   825   if (k.is_null() || !k->oop_is_instance())  return -1;
   827   int rfill = 0, rlimit = results->length(), rskip = skip;
   828   // overflow measurement:
   829   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
   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;
   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   }
   848   if ((match_flags & IS_TYPE) != 0) {
   849     // NYI, and Core Reflection works quite well for this query
   850   }
   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   }
   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   }
   927   // return number of elements we at leasted wanted to initialize
   928   return rfill + overflow;
   929 }
   931 //------------------------------------------------------------------------------
   932 // MemberNameTable
   933 //
   935 MemberNameTable::MemberNameTable(int methods_cnt)
   936                   : GrowableArray<jweak>(methods_cnt, true) {
   937   assert_locked_or_safepoint(MemberNameTable_lock);
   938 }
   940 MemberNameTable::~MemberNameTable() {
   941   assert_locked_or_safepoint(MemberNameTable_lock);
   942   int len = this->length();
   944   for (int idx = 0; idx < len; idx++) {
   945     jweak ref = this->at(idx);
   946     JNIHandles::destroy_weak_global(ref);
   947   }
   948 }
   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 }
   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);
   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   // Not found, push the new one, or reuse empty slot
   976   this->at_put_grow(new_index, mem_name_wref);
   977   return new_mem_name;
   978 }
   980 #if INCLUDE_JVMTI
   981 // It is called at safepoint only for RedefineClasses
   982 void MemberNameTable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
   983   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
   984   // For each redefined method
   985   for (int idx = 0; idx < length(); idx++) {
   986     oop mem_name = JNIHandles::resolve(this->at(idx));
   987     if (mem_name == NULL) {
   988       continue;
   989     }
   990     Method* old_method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name);
   992     if (old_method == NULL || !old_method->is_old()) {
   993       continue; // skip uninteresting entries
   994     }
   995     if (old_method->is_deleted()) {
   996       // skip entries with deleted methods
   997       continue;
   998     }
   999     Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
  1001     assert(new_method != NULL, "method_with_idnum() should not be NULL");
  1002     assert(old_method != new_method, "sanity check");
  1004     java_lang_invoke_MemberName::set_vmtarget(mem_name, new_method);
  1006     if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
  1007       if (!(*trace_name_printed)) {
  1008         // RC_TRACE_MESG macro has an embedded ResourceMark
  1009         RC_TRACE_MESG(("adjust: name=%s",
  1010                        old_method->method_holder()->external_name()));
  1011         *trace_name_printed = true;
  1013       // RC_TRACE macro has an embedded ResourceMark
  1014       RC_TRACE(0x00400000, ("MemberName method update: %s(%s)",
  1015                             new_method->name()->as_C_string(),
  1016                             new_method->signature()->as_C_string()));
  1020 #endif // INCLUDE_JVMTI
  1022 //
  1023 // Here are the native methods in java.lang.invoke.MethodHandleNatives
  1024 // They are the private interface between this JVM and the HotSpot-specific
  1025 // Java code that implements JSR 292 method handles.
  1026 //
  1027 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
  1028 // that intrinsic (non-JNI) native methods are defined in HotSpot.
  1029 //
  1031 JVM_ENTRY(jint, MHN_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  1032   switch (which) {
  1033   case MethodHandles::GC_COUNT_GWT:
  1034 #ifdef COMPILER2
  1035     return true;
  1036 #else
  1037     return false;
  1038 #endif
  1040   return 0;
  1042 JVM_END
  1044 #ifndef PRODUCT
  1045 #define EACH_NAMED_CON(template, requirement) \
  1046     template(MethodHandles,GC_COUNT_GWT) \
  1047     template(java_lang_invoke_MemberName,MN_IS_METHOD) \
  1048     template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
  1049     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
  1050     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
  1051     template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
  1052     template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
  1053     template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
  1054     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
  1055     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_MASK) \
  1056     template(MethodHandles,GC_LAMBDA_SUPPORT) \
  1057     /*end*/
  1059 #define IGNORE_REQ(req_expr) /* req_expr */
  1060 #define ONE_PLUS(scope,value) 1+
  1061 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS, IGNORE_REQ) 0;
  1062 #define VALUE_COMMA(scope,value) scope::value,
  1063 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA, IGNORE_REQ) 0 };
  1064 #define STRING_NULL(scope,value) #value "\0"
  1065 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL, IGNORE_REQ) };
  1067 static bool advertise_con_value(int which) {
  1068   if (which < 0)  return false;
  1069   bool ok = true;
  1070   int count = 0;
  1071 #define INC_COUNT(scope,value) \
  1072   ++count;
  1073 #define CHECK_REQ(req_expr) \
  1074   if (which < count)  return ok; \
  1075   ok = (req_expr);
  1076   EACH_NAMED_CON(INC_COUNT, CHECK_REQ);
  1077 #undef INC_COUNT
  1078 #undef CHECK_REQ
  1079   assert(count == con_value_count, "");
  1080   if (which < count)  return ok;
  1081   return false;
  1084 #undef ONE_PLUS
  1085 #undef VALUE_COMMA
  1086 #undef STRING_NULL
  1087 #undef EACH_NAMED_CON
  1088 #endif // PRODUCT
  1090 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
  1091 #ifndef PRODUCT
  1092   if (advertise_con_value(which)) {
  1093     assert(which >= 0 && which < con_value_count, "");
  1094     int con = con_values[which];
  1095     objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
  1096     if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
  1097       const char* str = &con_names[0];
  1098       for (int i = 0; i < which; i++)
  1099         str += strlen(str) + 1;   // skip name and null
  1100       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
  1101       box->obj_at_put(0, name);
  1103     return con;
  1105 #endif
  1106   return 0;
  1108 JVM_END
  1110 // void init(MemberName self, AccessibleObject ref)
  1111 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
  1112   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
  1113   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
  1114   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  1115   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  1116   MethodHandles::init_MemberName(mname, target);
  1118 JVM_END
  1120 // void expand(MemberName self)
  1121 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  1122   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
  1123   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  1124   MethodHandles::expand_MemberName(mname, 0, CHECK);
  1126 JVM_END
  1128 // void resolve(MemberName self, Class<?> caller)
  1129 JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  1130   if (mname_jh == NULL) { THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "mname is null"); }
  1131   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  1133   // The trusted Java code that calls this method should already have performed
  1134   // access checks on behalf of the given caller.  But, we can verify this.
  1135   if (VerifyMethodHandles && caller_jh != NULL &&
  1136       java_lang_invoke_MemberName::clazz(mname()) != NULL) {
  1137     Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname()));
  1138     if (reference_klass != NULL && reference_klass->oop_is_objArray()) {
  1139       reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass();
  1142     // Reflection::verify_class_access can only handle instance classes.
  1143     if (reference_klass != NULL && reference_klass->oop_is_instance()) {
  1144       // Emulate LinkResolver::check_klass_accessability.
  1145       Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
  1146       if (!Reflection::verify_class_access(caller,
  1147                                            reference_klass,
  1148                                            true)) {
  1149         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), reference_klass->external_name());
  1154   KlassHandle caller(THREAD,
  1155                      caller_jh == NULL ? (Klass*) NULL :
  1156                      java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh)));
  1157   Handle resolved = MethodHandles::resolve_MemberName(mname, caller, CHECK_NULL);
  1159   if (resolved.is_null()) {
  1160     int flags = java_lang_invoke_MemberName::flags(mname());
  1161     int ref_kind = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
  1162     if (!MethodHandles::ref_kind_is_valid(ref_kind)) {
  1163       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "obsolete MemberName format");
  1165     if ((flags & ALL_KINDS) == IS_FIELD) {
  1166       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), "field resolution failed");
  1167     } else if ((flags & ALL_KINDS) == IS_METHOD ||
  1168                (flags & ALL_KINDS) == IS_CONSTRUCTOR) {
  1169       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchFieldError(), "method resolution failed");
  1170     } else {
  1171       THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "resolution failed");
  1175   return JNIHandles::make_local(THREAD, resolved());
  1177 JVM_END
  1179 static jlong find_member_field_offset(oop mname, bool must_be_static, TRAPS) {
  1180   if (mname == NULL ||
  1181       java_lang_invoke_MemberName::vmtarget(mname) == NULL) {
  1182     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "mname not resolved");
  1183   } else {
  1184     int flags = java_lang_invoke_MemberName::flags(mname);
  1185     if ((flags & IS_FIELD) != 0 &&
  1186         (must_be_static
  1187          ? (flags & JVM_ACC_STATIC) != 0
  1188          : (flags & JVM_ACC_STATIC) == 0)) {
  1189       int vmindex = java_lang_invoke_MemberName::vmindex(mname);
  1190       return (jlong) vmindex;
  1193   const char* msg = (must_be_static ? "static field required" : "non-static field required");
  1194   THROW_MSG_0(vmSymbols::java_lang_InternalError(), msg);
  1195   return 0;
  1198 JVM_ENTRY(jlong, MHN_objectFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  1199   return find_member_field_offset(JNIHandles::resolve(mname_jh), false, THREAD);
  1201 JVM_END
  1203 JVM_ENTRY(jlong, MHN_staticFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  1204   return find_member_field_offset(JNIHandles::resolve(mname_jh), true, THREAD);
  1206 JVM_END
  1208 JVM_ENTRY(jobject, MHN_staticFieldBase(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  1209   // use the other function to perform sanity checks:
  1210   jlong ignore = find_member_field_offset(JNIHandles::resolve(mname_jh), true, CHECK_NULL);
  1211   oop clazz = java_lang_invoke_MemberName::clazz(JNIHandles::resolve_non_null(mname_jh));
  1212   return JNIHandles::make_local(THREAD, clazz);
  1214 JVM_END
  1216 JVM_ENTRY(jobject, MHN_getMemberVMInfo(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  1217   if (mname_jh == NULL)  return NULL;
  1218   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  1219   intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
  1220   Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
  1221   objArrayHandle result = oopFactory::new_objArray(SystemDictionary::Object_klass(), 2, CHECK_NULL);
  1222   jvalue vmindex_value; vmindex_value.j = (long)vmindex;
  1223   oop x = java_lang_boxing_object::create(T_LONG, &vmindex_value, CHECK_NULL);
  1224   result->obj_at_put(0, x);
  1225   x = NULL;
  1226   if (vmtarget == NULL) {
  1227     x = NULL;
  1228   } else if (vmtarget->is_klass()) {
  1229     x = ((Klass*) vmtarget)->java_mirror();
  1230   } else if (vmtarget->is_method()) {
  1231     x = mname();
  1233   result->obj_at_put(1, x);
  1234   return JNIHandles::make_local(env, result());
  1236 JVM_END
  1240 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  1241 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  1242 JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
  1243                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
  1244                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  1245   if (clazz_jh == NULL || results_jh == NULL)  return -1;
  1246   KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz_jh)));
  1248   objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
  1249   if (results.is_null() || !results->is_objArray())  return -1;
  1251   TempNewSymbol name = NULL;
  1252   TempNewSymbol sig = NULL;
  1253   if (name_jh != NULL) {
  1254     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
  1255     if (name == NULL)  return 0; // a match is not possible
  1257   if (sig_jh != NULL) {
  1258     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
  1259     if (sig == NULL)  return 0; // a match is not possible
  1262   KlassHandle caller;
  1263   if (caller_jh != NULL) {
  1264     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
  1265     if (!java_lang_Class::is_instance(caller_oop))  return -1;
  1266     caller = KlassHandle(THREAD, java_lang_Class::as_Klass(caller_oop));
  1269   if (name != NULL && sig != NULL && results.not_null()) {
  1270     // try a direct resolve
  1271     // %%% TO DO
  1274   int res = MethodHandles::find_MemberNames(k, name, sig, mflags,
  1275                                             caller, skip, results);
  1276   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  1277   return res;
  1279 JVM_END
  1281 JVM_ENTRY(void, MHN_setCallSiteTargetNormal(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
  1282   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
  1283   Handle target   (THREAD, JNIHandles::resolve(target_jh));
  1285     // Walk all nmethods depending on this call site.
  1286     MutexLocker mu(Compile_lock, thread);
  1287     Universe::flush_dependents_on(call_site, target);
  1288     java_lang_invoke_CallSite::set_target(call_site(), target());
  1291 JVM_END
  1293 JVM_ENTRY(void, MHN_setCallSiteTargetVolatile(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
  1294   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
  1295   Handle target   (THREAD, JNIHandles::resolve(target_jh));
  1297     // Walk all nmethods depending on this call site.
  1298     MutexLocker mu(Compile_lock, thread);
  1299     Universe::flush_dependents_on(call_site, target);
  1300     java_lang_invoke_CallSite::set_target_volatile(call_site(), target());
  1303 JVM_END
  1305 /**
  1306  * Throws a java/lang/UnsupportedOperationException unconditionally.
  1307  * This is required by the specification of MethodHandle.invoke if
  1308  * invoked directly.
  1309  */
  1310 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
  1311   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
  1312   return NULL;
  1314 JVM_END
  1316 /**
  1317  * Throws a java/lang/UnsupportedOperationException unconditionally.
  1318  * This is required by the specification of MethodHandle.invokeExact if
  1319  * invoked directly.
  1320  */
  1321 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
  1322   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
  1323   return NULL;
  1325 JVM_END
  1327 /// JVM_RegisterMethodHandleMethods
  1329 #undef CS  // Solaris builds complain
  1331 #define LANG "Ljava/lang/"
  1332 #define JLINV "Ljava/lang/invoke/"
  1334 #define OBJ   LANG "Object;"
  1335 #define CLS   LANG "Class;"
  1336 #define STRG  LANG "String;"
  1337 #define CS    JLINV "CallSite;"
  1338 #define MT    JLINV "MethodType;"
  1339 #define MH    JLINV "MethodHandle;"
  1340 #define MEM   JLINV "MemberName;"
  1342 #define CC (char*)  /*cast a literal from (const char*)*/
  1343 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
  1345 // These are the native methods on java.lang.invoke.MethodHandleNatives.
  1346 static JNINativeMethod MHN_methods[] = {
  1347   {CC "init",                      CC "(" MEM "" OBJ ")V",                     FN_PTR(MHN_init_Mem)},
  1348   {CC"expand",                     CC "(" MEM ")V",                          FN_PTR(MHN_expand_Mem)},
  1349   {CC "resolve",                   CC "(" MEM "" CLS ")" MEM,                   FN_PTR(MHN_resolve_Mem)},
  1350   {CC "getConstant",               CC "(I)I",                              FN_PTR(MHN_getConstant)},
  1351   //  static native int getNamedCon(int which, Object[] name)
  1352   {CC "getNamedCon",               CC "(I[" OBJ ")I",                        FN_PTR(MHN_getNamedCon)},
  1353   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  1354   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  1355   {CC "getMembers",                CC "(" CLS "" STRG "" STRG "I" CLS "I[" MEM ")I", FN_PTR(MHN_getMembers)},
  1356   {CC "objectFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_objectFieldOffset)},
  1357   {CC "setCallSiteTargetNormal",   CC "(" CS "" MH ")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
  1358   {CC "setCallSiteTargetVolatile", CC "(" CS "" MH ")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
  1359   {CC "staticFieldOffset",         CC "(" MEM ")J",                          FN_PTR(MHN_staticFieldOffset)},
  1360   {CC "staticFieldBase",           CC "(" MEM ")" OBJ,                        FN_PTR(MHN_staticFieldBase)},
  1361   {CC "getMemberVMInfo",           CC "(" MEM ")" OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
  1362 };
  1364 static JNINativeMethod MH_methods[] = {
  1365   // UnsupportedOperationException throwers
  1366   {CC "invoke",                    CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invoke_UOE)},
  1367   {CC "invokeExact",               CC "([" OBJ ")" OBJ,                       FN_PTR(MH_invokeExact_UOE)}
  1368 };
  1370 /**
  1371  * Helper method to register native methods.
  1372  */
  1373 static bool register_natives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
  1374   int status = env->RegisterNatives(clazz, methods, nMethods);
  1375   if (status != JNI_OK || env->ExceptionOccurred()) {
  1376     warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  1377     env->ExceptionClear();
  1378     return false;
  1380   return true;
  1383 /**
  1384  * This one function is exported, used by NativeLookup.
  1385  */
  1386 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
  1387   if (!EnableInvokeDynamic) {
  1388     warning("JSR 292 is disabled in this JVM.  Use -XX:+UnlockDiagnosticVMOptions -XX:+EnableInvokeDynamic to enable.");
  1389     return;  // bind nothing
  1392   assert(!MethodHandles::enabled(), "must not be enabled");
  1393   bool enable_MH = true;
  1395   jclass MH_class = NULL;
  1396   if (SystemDictionary::MethodHandle_klass() == NULL) {
  1397     enable_MH = false;
  1398   } else {
  1399     oop mirror = SystemDictionary::MethodHandle_klass()->java_mirror();
  1400     MH_class = (jclass) JNIHandles::make_local(env, mirror);
  1403   if (enable_MH) {
  1404     ThreadToNativeFromVM ttnfv(thread);
  1406     if (enable_MH) {
  1407       enable_MH = register_natives(env, MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
  1409     if (enable_MH) {
  1410       enable_MH = register_natives(env, MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
  1414   if (TraceInvokeDynamic) {
  1415     tty->print_cr("MethodHandle support loaded (using LambdaForms)");
  1418   if (enable_MH) {
  1419     MethodHandles::generate_adapters();
  1420     MethodHandles::set_enabled(true);
  1423 JVM_END

mercurial