src/share/vm/prims/methodHandles.cpp

Sat, 01 May 2010 02:42:18 -0700

author
jrose
date
Sat, 01 May 2010 02:42:18 -0700
changeset 1862
cd5dbf694d45
parent 1734
9eba43136cb5
child 1863
2ffde6cfe049
permissions
-rw-r--r--

6939134: JSR 292 adjustments to method handle invocation
Summary: split MethodHandle.invoke into invokeExact and invokeGeneric; also clean up JVM-to-Java interfaces
Reviewed-by: twisti

     1 /*
     2  * Copyright 2008-2010 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 /*
    26  * JSR 292 reference implementation: method handles
    27  */
    29 #include "incls/_precompiled.incl"
    30 #include "incls/_methodHandles.cpp.incl"
    32 bool MethodHandles::_enabled = false; // set true after successful native linkage
    34 MethodHandleEntry* MethodHandles::_entries[MethodHandles::_EK_LIMIT] = {NULL};
    35 const char*        MethodHandles::_entry_names[_EK_LIMIT+1] = {
    36   "raise_exception",
    37   "invokestatic",               // how a MH emulates invokestatic
    38   "invokespecial",              // ditto for the other invokes...
    39   "invokevirtual",
    40   "invokeinterface",
    41   "bound_ref",                  // these are for BMH...
    42   "bound_int",
    43   "bound_long",
    44   "bound_ref_direct",           // (direct versions have a direct methodOop)
    45   "bound_int_direct",
    46   "bound_long_direct",
    48   // starting at _adapter_mh_first:
    49   "adapter_retype_only",       // these are for AMH...
    50   "adapter_retype_raw",
    51   "adapter_check_cast",
    52   "adapter_prim_to_prim",
    53   "adapter_ref_to_prim",
    54   "adapter_prim_to_ref",
    55   "adapter_swap_args",
    56   "adapter_rot_args",
    57   "adapter_dup_args",
    58   "adapter_drop_args",
    59   "adapter_collect_args",
    60   "adapter_spread_args",
    61   "adapter_flyby",
    62   "adapter_ricochet",
    64   // optimized adapter types:
    65   "adapter_swap_args/1",
    66   "adapter_swap_args/2",
    67   "adapter_rot_args/1,up",
    68   "adapter_rot_args/1,down",
    69   "adapter_rot_args/2,up",
    70   "adapter_rot_args/2,down",
    71   "adapter_prim_to_prim/i2i",
    72   "adapter_prim_to_prim/l2i",
    73   "adapter_prim_to_prim/d2f",
    74   "adapter_prim_to_prim/i2l",
    75   "adapter_prim_to_prim/f2d",
    76   "adapter_ref_to_prim/unboxi",
    77   "adapter_ref_to_prim/unboxl",
    78   "adapter_spread_args/0",
    79   "adapter_spread_args/1",
    80   "adapter_spread_args/more",
    82   NULL
    83 };
    85 // Adapters.
    86 MethodHandlesAdapterBlob* MethodHandles::_adapter_code      = NULL;
    87 int                       MethodHandles::_adapter_code_size = StubRoutines::method_handles_adapters_code_size;
    89 jobject MethodHandles::_raise_exception_method;
    91 #ifdef ASSERT
    92 bool MethodHandles::spot_check_entry_names() {
    93   assert(!strcmp(entry_name(_invokestatic_mh), "invokestatic"), "");
    94   assert(!strcmp(entry_name(_bound_ref_mh), "bound_ref"), "");
    95   assert(!strcmp(entry_name(_adapter_retype_only), "adapter_retype_only"), "");
    96   assert(!strcmp(entry_name(_adapter_ricochet), "adapter_ricochet"), "");
    97   assert(!strcmp(entry_name(_adapter_opt_unboxi), "adapter_ref_to_prim/unboxi"), "");
    98   return true;
    99 }
   100 #endif
   103 //------------------------------------------------------------------------------
   104 // MethodHandles::generate_adapters
   105 //
   106 void MethodHandles::generate_adapters() {
   107   if (!EnableMethodHandles || SystemDictionary::MethodHandle_klass() == NULL)  return;
   109   assert(_adapter_code == NULL, "generate only once");
   111   ResourceMark rm;
   112   TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
   113   _adapter_code = MethodHandlesAdapterBlob::create(_adapter_code_size);
   114   if (_adapter_code == NULL)
   115     vm_exit_out_of_memory(_adapter_code_size, "CodeCache: no room for MethodHandles adapters");
   116   CodeBuffer code(_adapter_code->instructions_begin(), _adapter_code->instructions_size());
   118   MethodHandlesAdapterGenerator g(&code);
   119   g.generate();
   120 }
   123 //------------------------------------------------------------------------------
   124 // MethodHandlesAdapterGenerator::generate
   125 //
   126 void MethodHandlesAdapterGenerator::generate() {
   127   // Generate generic method handle adapters.
   128   for (MethodHandles::EntryKind ek = MethodHandles::_EK_FIRST;
   129        ek < MethodHandles::_EK_LIMIT;
   130        ek = MethodHandles::EntryKind(1 + (int)ek)) {
   131     StubCodeMark mark(this, "MethodHandle", MethodHandles::entry_name(ek));
   132     MethodHandles::generate_method_handle_stub(_masm, ek);
   133   }
   134 }
   137 void MethodHandles::set_enabled(bool z) {
   138   if (_enabled != z) {
   139     guarantee(z && EnableMethodHandles, "can only enable once, and only if -XX:+EnableMethodHandles");
   140     _enabled = z;
   141   }
   142 }
   144 // Note: A method which does not have a TRAPS argument cannot block in the GC
   145 // or throw exceptions.  Such methods are used in this file to do something quick
   146 // and local, like parse a data structure.  For speed, such methods work on plain
   147 // oops, not handles.  Trapping methods uniformly operate on handles.
   149 methodOop MethodHandles::decode_vmtarget(oop vmtarget, int vmindex, oop mtype,
   150                                          klassOop& receiver_limit_result, int& decode_flags_result) {
   151   if (vmtarget == NULL)  return NULL;
   152   assert(methodOopDesc::nonvirtual_vtable_index < 0, "encoding");
   153   if (vmindex < 0) {
   154     // this DMH performs no dispatch; it is directly bound to a methodOop
   155     // A MemberName may either be directly bound to a methodOop,
   156     // or it may use the klass/index form; both forms mean the same thing.
   157     methodOop m = decode_methodOop(methodOop(vmtarget), decode_flags_result);
   158     if ((decode_flags_result & _dmf_has_receiver) != 0
   159         && java_dyn_MethodType::is_instance(mtype)) {
   160       // Extract receiver type restriction from mtype.ptypes[0].
   161       objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype);
   162       oop ptype0 = (ptypes == NULL || ptypes->length() < 1) ? oop(NULL) : ptypes->obj_at(0);
   163       if (java_lang_Class::is_instance(ptype0))
   164         receiver_limit_result = java_lang_Class::as_klassOop(ptype0);
   165     }
   166     if (vmindex == methodOopDesc::nonvirtual_vtable_index) {
   167       // this DMH can be an "invokespecial" version
   168       decode_flags_result &= ~_dmf_does_dispatch;
   169     } else {
   170       assert(vmindex == methodOopDesc::invalid_vtable_index, "random vmindex?");
   171     }
   172     return m;
   173   } else {
   174     assert(vmtarget->is_klass(), "must be class or interface");
   175     decode_flags_result |= MethodHandles::_dmf_does_dispatch;
   176     decode_flags_result |= MethodHandles::_dmf_has_receiver;
   177     receiver_limit_result = (klassOop)vmtarget;
   178     Klass* tk = Klass::cast((klassOop)vmtarget);
   179     if (tk->is_interface()) {
   180       // an itable linkage is <interface, itable index>
   181       decode_flags_result |= MethodHandles::_dmf_from_interface;
   182       return klassItable::method_for_itable_index((klassOop)vmtarget, vmindex);
   183     } else {
   184       if (!tk->oop_is_instance())
   185         tk = instanceKlass::cast(SystemDictionary::Object_klass());
   186       return ((instanceKlass*)tk)->method_at_vtable(vmindex);
   187     }
   188   }
   189 }
   191 // MemberName and DirectMethodHandle have the same linkage to the JVM internals.
   192 // (MemberName is the non-operational name used for queries and setup.)
   194 methodOop MethodHandles::decode_DirectMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   195   oop vmtarget = sun_dyn_DirectMethodHandle::vmtarget(mh);
   196   int vmindex  = sun_dyn_DirectMethodHandle::vmindex(mh);
   197   oop mtype    = sun_dyn_DirectMethodHandle::type(mh);
   198   return decode_vmtarget(vmtarget, vmindex, mtype, receiver_limit_result, decode_flags_result);
   199 }
   201 methodOop MethodHandles::decode_BoundMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   202   assert(sun_dyn_BoundMethodHandle::is_instance(mh), "");
   203   assert(mh->klass() != SystemDictionary::AdapterMethodHandle_klass(), "");
   204   for (oop bmh = mh;;) {
   205     // Bound MHs can be stacked to bind several arguments.
   206     oop target = java_dyn_MethodHandle::vmtarget(bmh);
   207     if (target == NULL)  return NULL;
   208     decode_flags_result |= MethodHandles::_dmf_binds_argument;
   209     klassOop tk = target->klass();
   210     if (tk == SystemDictionary::BoundMethodHandle_klass()) {
   211       bmh = target;
   212       continue;
   213     } else {
   214       if (java_dyn_MethodHandle::is_subclass(tk)) {
   215         //assert(tk == SystemDictionary::DirectMethodHandle_klass(), "end of BMH chain must be DMH");
   216         return decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   217       } else {
   218         // Optimized case:  binding a receiver to a non-dispatched DMH
   219         // short-circuits directly to the methodOop.
   220         // (It might be another argument besides a receiver also.)
   221         assert(target->is_method(), "must be a simple method");
   222         decode_flags_result |= MethodHandles::_dmf_binds_method;
   223         methodOop m = (methodOop) target;
   224         if (!m->is_static())
   225           decode_flags_result |= MethodHandles::_dmf_has_receiver;
   226         return m;
   227       }
   228     }
   229   }
   230 }
   232 methodOop MethodHandles::decode_AdapterMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   233   assert(mh->klass() == SystemDictionary::AdapterMethodHandle_klass(), "");
   234   for (oop amh = mh;;) {
   235     // Adapter MHs can be stacked to convert several arguments.
   236     int conv_op = adapter_conversion_op(sun_dyn_AdapterMethodHandle::conversion(amh));
   237     decode_flags_result |= (_dmf_adapter_lsb << conv_op) & _DMF_ADAPTER_MASK;
   238     oop target = java_dyn_MethodHandle::vmtarget(amh);
   239     if (target == NULL)  return NULL;
   240     klassOop tk = target->klass();
   241     if (tk == SystemDictionary::AdapterMethodHandle_klass()) {
   242       amh = target;
   243       continue;
   244     } else {
   245       // must be a BMH (which will bind some more arguments) or a DMH (for the final call)
   246       return MethodHandles::decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   247     }
   248   }
   249 }
   251 methodOop MethodHandles::decode_MethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   252   if (mh == NULL)  return NULL;
   253   klassOop mhk = mh->klass();
   254   assert(java_dyn_MethodHandle::is_subclass(mhk), "must be a MethodHandle");
   255   if (mhk == SystemDictionary::DirectMethodHandle_klass()) {
   256     return decode_DirectMethodHandle(mh, receiver_limit_result, decode_flags_result);
   257   } else if (mhk == SystemDictionary::BoundMethodHandle_klass()) {
   258     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   259   } else if (mhk == SystemDictionary::AdapterMethodHandle_klass()) {
   260     return decode_AdapterMethodHandle(mh, receiver_limit_result, decode_flags_result);
   261   } else if (sun_dyn_BoundMethodHandle::is_subclass(mhk)) {
   262     // could be a JavaMethodHandle (but not an adapter MH)
   263     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   264   } else {
   265     assert(false, "cannot parse this MH");
   266     return NULL;              // random MH?
   267   }
   268 }
   270 methodOop MethodHandles::decode_methodOop(methodOop m, int& decode_flags_result) {
   271   assert(m->is_method(), "");
   272   if (m->is_static()) {
   273     // check that signature begins '(L' or '([' (not '(I', '()', etc.)
   274     symbolOop sig = m->signature();
   275     BasicType recv_bt = char2type(sig->byte_at(1));
   276     // Note: recv_bt might be T_ILLEGAL if byte_at(2) is ')'
   277     assert(sig->byte_at(0) == '(', "must be method sig");
   278 //     if (recv_bt == T_OBJECT || recv_bt == T_ARRAY)
   279 //       decode_flags_result |= _dmf_has_receiver;
   280   } else {
   281     // non-static method
   282     decode_flags_result |= _dmf_has_receiver;
   283     if (!m->can_be_statically_bound() && !m->is_initializer()) {
   284       decode_flags_result |= _dmf_does_dispatch;
   285       if (Klass::cast(m->method_holder())->is_interface())
   286         decode_flags_result |= _dmf_from_interface;
   287     }
   288   }
   289   return m;
   290 }
   293 // A trusted party is handing us a cookie to determine a method.
   294 // Let's boil it down to the method oop they really want.
   295 methodOop MethodHandles::decode_method(oop x, klassOop& receiver_limit_result, int& decode_flags_result) {
   296   decode_flags_result = 0;
   297   receiver_limit_result = NULL;
   298   klassOop xk = x->klass();
   299   if (xk == Universe::methodKlassObj()) {
   300     return decode_methodOop((methodOop) x, decode_flags_result);
   301   } else if (xk == SystemDictionary::MemberName_klass()) {
   302     // Note: This only works if the MemberName has already been resolved.
   303     return decode_MemberName(x, receiver_limit_result, decode_flags_result);
   304   } else if (java_dyn_MethodHandle::is_subclass(xk)) {
   305     return decode_MethodHandle(x, receiver_limit_result, decode_flags_result);
   306   } else if (xk == SystemDictionary::reflect_Method_klass()) {
   307     oop clazz  = java_lang_reflect_Method::clazz(x);
   308     int slot   = java_lang_reflect_Method::slot(x);
   309     klassOop k = java_lang_Class::as_klassOop(clazz);
   310     if (k != NULL && Klass::cast(k)->oop_is_instance())
   311       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   312                               decode_flags_result);
   313   } else if (xk == SystemDictionary::reflect_Constructor_klass()) {
   314     oop clazz  = java_lang_reflect_Constructor::clazz(x);
   315     int slot   = java_lang_reflect_Constructor::slot(x);
   316     klassOop k = java_lang_Class::as_klassOop(clazz);
   317     if (k != NULL && Klass::cast(k)->oop_is_instance())
   318       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   319                               decode_flags_result);
   320   } else {
   321     // unrecognized object
   322     assert(!x->is_method(), "already checked");
   323     assert(!sun_dyn_MemberName::is_instance(x), "already checked");
   324   }
   325   return NULL;
   326 }
   329 int MethodHandles::decode_MethodHandle_stack_pushes(oop mh) {
   330   if (mh->klass() == SystemDictionary::DirectMethodHandle_klass())
   331     return 0;                   // no push/pop
   332   int this_vmslots = java_dyn_MethodHandle::vmslots(mh);
   333   int last_vmslots = 0;
   334   oop last_mh = mh;
   335   for (;;) {
   336     oop target = java_dyn_MethodHandle::vmtarget(last_mh);
   337     if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   338       last_vmslots = java_dyn_MethodHandle::vmslots(target);
   339       break;
   340     } else if (!java_dyn_MethodHandle::is_instance(target)) {
   341       // might be klass or method
   342       assert(target->is_method(), "must get here with a direct ref to method");
   343       last_vmslots = methodOop(target)->size_of_parameters();
   344       break;
   345     }
   346     last_mh = target;
   347   }
   348   // If I am called with fewer VM slots than my ultimate callee,
   349   // it must be that I push the additionally needed slots.
   350   // Likewise if am called with more VM slots, I will pop them.
   351   return (last_vmslots - this_vmslots);
   352 }
   355 // MemberName support
   357 // import sun_dyn_MemberName.*
   358 enum {
   359   IS_METHOD      = sun_dyn_MemberName::MN_IS_METHOD,
   360   IS_CONSTRUCTOR = sun_dyn_MemberName::MN_IS_CONSTRUCTOR,
   361   IS_FIELD       = sun_dyn_MemberName::MN_IS_FIELD,
   362   IS_TYPE        = sun_dyn_MemberName::MN_IS_TYPE,
   363   SEARCH_SUPERCLASSES = sun_dyn_MemberName::MN_SEARCH_SUPERCLASSES,
   364   SEARCH_INTERFACES   = sun_dyn_MemberName::MN_SEARCH_INTERFACES,
   365   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE,
   366   VM_INDEX_UNINITIALIZED = sun_dyn_MemberName::VM_INDEX_UNINITIALIZED
   367 };
   369 Handle MethodHandles::new_MemberName(TRAPS) {
   370   Handle empty;
   371   instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
   372   if (!k->is_initialized())  k->initialize(CHECK_(empty));
   373   return Handle(THREAD, k->allocate_instance(THREAD));
   374 }
   376 void MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
   377   if (target_oop->klass() == SystemDictionary::reflect_Field_klass()) {
   378     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
   379     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
   380     int mods  = java_lang_reflect_Field::modifiers(target_oop);
   381     klassOop k = java_lang_Class::as_klassOop(clazz);
   382     int offset = instanceKlass::cast(k)->offset_from_fields(slot);
   383     init_MemberName(mname_oop, k, accessFlags_from(mods), offset);
   384   } else {
   385     int decode_flags = 0; klassOop receiver_limit = NULL;
   386     methodOop m = MethodHandles::decode_method(target_oop,
   387                                                receiver_limit, decode_flags);
   388     bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   389     init_MemberName(mname_oop, m, do_dispatch);
   390   }
   391 }
   393 void MethodHandles::init_MemberName(oop mname_oop, methodOop m, bool do_dispatch) {
   394   int flags = ((m->is_initializer() ? IS_CONSTRUCTOR : IS_METHOD)
   395                | (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS ));
   396   oop vmtarget = m;
   397   int vmindex  = methodOopDesc::invalid_vtable_index;  // implies no info yet
   398   if (!do_dispatch || (flags & IS_CONSTRUCTOR) || m->can_be_statically_bound())
   399     vmindex = methodOopDesc::nonvirtual_vtable_index; // implies never any dispatch
   400   assert(vmindex != VM_INDEX_UNINITIALIZED, "Java sentinel value");
   401   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   402   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   403   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   404   sun_dyn_MemberName::set_clazz(mname_oop,    Klass::cast(m->method_holder())->java_mirror());
   405 }
   407 void MethodHandles::init_MemberName(oop mname_oop, klassOop field_holder, AccessFlags mods, int offset) {
   408   int flags = (IS_FIELD | (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS ));
   409   oop vmtarget = field_holder;
   410   int vmindex  = offset;  // determines the field uniquely when combined with static bit
   411   assert(vmindex != VM_INDEX_UNINITIALIZED, "bad alias on vmindex");
   412   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   413   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   414   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   415   sun_dyn_MemberName::set_clazz(mname_oop,    Klass::cast(field_holder)->java_mirror());
   416 }
   419 methodOop MethodHandles::decode_MemberName(oop mname, klassOop& receiver_limit_result, int& decode_flags_result) {
   420   int flags  = sun_dyn_MemberName::flags(mname);
   421   if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) == 0)  return NULL;  // not invocable
   422   oop vmtarget = sun_dyn_MemberName::vmtarget(mname);
   423   int vmindex  = sun_dyn_MemberName::vmindex(mname);
   424   if (vmindex == VM_INDEX_UNINITIALIZED)  return NULL; // not resolved
   425   methodOop m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit_result, decode_flags_result);
   426   oop clazz = sun_dyn_MemberName::clazz(mname);
   427   if (clazz != NULL && java_lang_Class::is_instance(clazz)) {
   428     klassOop klass = java_lang_Class::as_klassOop(clazz);
   429     if (klass != NULL)  receiver_limit_result = klass;
   430   }
   431   return m;
   432 }
   434 // An unresolved member name is a mere symbolic reference.
   435 // Resolving it plants a vmtarget/vmindex in it,
   436 // which refers dirctly to JVM internals.
   437 void MethodHandles::resolve_MemberName(Handle mname, TRAPS) {
   438   assert(sun_dyn_MemberName::is_instance(mname()), "");
   439 #ifdef ASSERT
   440   // If this assert throws, renegotiate the sentinel value used by the Java code,
   441   // so that it is distinct from any valid vtable index value, and any special
   442   // values defined in methodOopDesc::VtableIndexFlag.
   443   // The point of the slop is to give the Java code and the JVM some room
   444   // to independently specify sentinel values.
   445   const int sentinel_slop  = 10;
   446   const int sentinel_limit = methodOopDesc::highest_unused_vtable_index_value - sentinel_slop;
   447   assert(VM_INDEX_UNINITIALIZED < sentinel_limit, "Java sentinel != JVM sentinels");
   448 #endif
   449   if (sun_dyn_MemberName::vmindex(mname()) != VM_INDEX_UNINITIALIZED)
   450     return;  // already resolved
   451   oop defc_oop = sun_dyn_MemberName::clazz(mname());
   452   oop name_str = sun_dyn_MemberName::name(mname());
   453   oop type_str = sun_dyn_MemberName::type(mname());
   454   int flags    = sun_dyn_MemberName::flags(mname());
   456   if (defc_oop == NULL || name_str == NULL || type_str == NULL) {
   457     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve");
   458   }
   459   klassOop defc_klassOop = java_lang_Class::as_klassOop(defc_oop);
   460   defc_oop = NULL;  // safety
   461   if (defc_klassOop == NULL)  return;  // a primitive; no resolution possible
   462   if (!Klass::cast(defc_klassOop)->oop_is_instance()) {
   463     if (!Klass::cast(defc_klassOop)->oop_is_array())  return;
   464     defc_klassOop = SystemDictionary::Object_klass();
   465   }
   466   instanceKlassHandle defc(THREAD, defc_klassOop);
   467   defc_klassOop = NULL;  // safety
   468   if (defc.is_null()) {
   469     THROW_MSG(vmSymbols::java_lang_InternalError(), "primitive class");
   470   }
   471   defc->link_class(CHECK);
   473   // convert the external string name to an internal symbol
   474   symbolHandle name(THREAD, java_lang_String::as_symbol_or_null(name_str));
   475   if (name.is_null())  return;  // no such name
   476   name_str = NULL;  // safety
   478   // convert the external string or reflective type to an internal signature
   479   bool force_signature = methodOopDesc::is_method_handle_invoke_name(name());
   480   symbolHandle type; {
   481     symbolOop type_sym = NULL;
   482     if (java_dyn_MethodType::is_instance(type_str)) {
   483       type_sym = java_dyn_MethodType::as_signature(type_str, force_signature, CHECK);
   484     } else if (java_lang_Class::is_instance(type_str)) {
   485       type_sym = java_lang_Class::as_signature(type_str, force_signature, CHECK);
   486     } else if (java_lang_String::is_instance(type_str)) {
   487       if (force_signature) {
   488         type     = java_lang_String::as_symbol(type_str, CHECK);
   489       } else {
   490         type_sym = java_lang_String::as_symbol_or_null(type_str);
   491       }
   492     } else {
   493       THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized type");
   494     }
   495     if (type_sym != NULL)
   496       type = symbolHandle(THREAD, type_sym);
   497   }
   498   if (type.is_null())  return;  // no such signature exists in the VM
   499   type_str = NULL; // safety
   501   // Time to do the lookup.
   502   switch (flags & ALL_KINDS) {
   503   case IS_METHOD:
   504     {
   505       CallInfo result;
   506       {
   507         EXCEPTION_MARK;
   508         if ((flags & JVM_ACC_STATIC) != 0) {
   509           LinkResolver::resolve_static_call(result,
   510                         defc, name, type, KlassHandle(), false, false, THREAD);
   511         } else if (defc->is_interface()) {
   512           LinkResolver::resolve_interface_call(result, Handle(), defc,
   513                         defc, name, type, KlassHandle(), false, false, THREAD);
   514         } else {
   515           LinkResolver::resolve_virtual_call(result, Handle(), defc,
   516                         defc, name, type, KlassHandle(), false, false, THREAD);
   517         }
   518         if (HAS_PENDING_EXCEPTION) {
   519           CLEAR_PENDING_EXCEPTION;
   520           return;
   521         }
   522       }
   523       methodHandle m = result.resolved_method();
   524       oop vmtarget = NULL;
   525       int vmindex = methodOopDesc::nonvirtual_vtable_index;
   526       if (defc->is_interface()) {
   527         vmindex = klassItable::compute_itable_index(m());
   528         assert(vmindex >= 0, "");
   529       } else if (result.has_vtable_index()) {
   530         vmindex = result.vtable_index();
   531         assert(vmindex >= 0, "");
   532       }
   533       assert(vmindex != VM_INDEX_UNINITIALIZED, "");
   534       if (vmindex < 0) {
   535         assert(result.is_statically_bound(), "");
   536         vmtarget = m();
   537       } else {
   538         vmtarget = result.resolved_klass()->as_klassOop();
   539       }
   540       int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   541       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   542       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   543       sun_dyn_MemberName::set_modifiers(mname(), mods);
   544       DEBUG_ONLY(int junk; klassOop junk2);
   545       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   546              "properly stored for later decoding");
   547       return;
   548     }
   549   case IS_CONSTRUCTOR:
   550     {
   551       CallInfo result;
   552       {
   553         EXCEPTION_MARK;
   554         if (name() == vmSymbols::object_initializer_name()) {
   555           LinkResolver::resolve_special_call(result,
   556                         defc, name, type, KlassHandle(), false, THREAD);
   557         } else {
   558           break;                // will throw after end of switch
   559         }
   560         if (HAS_PENDING_EXCEPTION) {
   561           CLEAR_PENDING_EXCEPTION;
   562           return;
   563         }
   564       }
   565       assert(result.is_statically_bound(), "");
   566       methodHandle m = result.resolved_method();
   567       oop vmtarget = m();
   568       int vmindex  = methodOopDesc::nonvirtual_vtable_index;
   569       int mods     = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   570       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   571       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   572       sun_dyn_MemberName::set_modifiers(mname(), mods);
   573       DEBUG_ONLY(int junk; klassOop junk2);
   574       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   575              "properly stored for later decoding");
   576       return;
   577     }
   578   case IS_FIELD:
   579     {
   580       // This is taken from LinkResolver::resolve_field, sans access checks.
   581       fieldDescriptor fd; // find_field initializes fd if found
   582       KlassHandle sel_klass(THREAD, instanceKlass::cast(defc())->find_field(name(), type(), &fd));
   583       // check if field exists; i.e., if a klass containing the field def has been selected
   584       if (sel_klass.is_null())  return;
   585       oop vmtarget = sel_klass->as_klassOop();
   586       int vmindex  = fd.offset();
   587       int mods     = (fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS);
   588       if (vmindex == VM_INDEX_UNINITIALIZED)  break;  // should not happen
   589       sun_dyn_MemberName::set_vmtarget(mname(),  vmtarget);
   590       sun_dyn_MemberName::set_vmindex(mname(),   vmindex);
   591       sun_dyn_MemberName::set_modifiers(mname(), mods);
   592       return;
   593     }
   594   }
   595   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   596 }
   598 // Conversely, a member name which is only initialized from JVM internals
   599 // may have null defc, name, and type fields.
   600 // Resolving it plants a vmtarget/vmindex in it,
   601 // which refers directly to JVM internals.
   602 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
   603   assert(sun_dyn_MemberName::is_instance(mname()), "");
   604   oop vmtarget = sun_dyn_MemberName::vmtarget(mname());
   605   int vmindex  = sun_dyn_MemberName::vmindex(mname());
   606   if (vmtarget == NULL || vmindex == VM_INDEX_UNINITIALIZED) {
   607     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
   608   }
   610   bool have_defc = (sun_dyn_MemberName::clazz(mname()) != NULL);
   611   bool have_name = (sun_dyn_MemberName::name(mname()) != NULL);
   612   bool have_type = (sun_dyn_MemberName::type(mname()) != NULL);
   613   int flags      = sun_dyn_MemberName::flags(mname());
   615   if (suppress != 0) {
   616     if (suppress & _suppress_defc)  have_defc = true;
   617     if (suppress & _suppress_name)  have_name = true;
   618     if (suppress & _suppress_type)  have_type = true;
   619   }
   621   if (have_defc && have_name && have_type)  return;  // nothing needed
   623   switch (flags & ALL_KINDS) {
   624   case IS_METHOD:
   625   case IS_CONSTRUCTOR:
   626     {
   627       klassOop receiver_limit = NULL;
   628       int      decode_flags   = 0;
   629       methodHandle m(THREAD, decode_vmtarget(vmtarget, vmindex, NULL,
   630                                              receiver_limit, decode_flags));
   631       if (m.is_null())  break;
   632       if (!have_defc) {
   633         klassOop defc = m->method_holder();
   634         if (receiver_limit != NULL && receiver_limit != defc
   635             && Klass::cast(receiver_limit)->is_subtype_of(defc))
   636           defc = receiver_limit;
   637         sun_dyn_MemberName::set_clazz(mname(), Klass::cast(defc)->java_mirror());
   638       }
   639       if (!have_name) {
   640         //not java_lang_String::create_from_symbol; let's intern member names
   641         Handle name = StringTable::intern(m->name(), CHECK);
   642         sun_dyn_MemberName::set_name(mname(), name());
   643       }
   644       if (!have_type) {
   645         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
   646         sun_dyn_MemberName::set_type(mname(), type());
   647       }
   648       return;
   649     }
   650   case IS_FIELD:
   651     {
   652       // This is taken from LinkResolver::resolve_field, sans access checks.
   653       if (!vmtarget->is_klass())  break;
   654       if (!Klass::cast((klassOop) vmtarget)->oop_is_instance())  break;
   655       instanceKlassHandle defc(THREAD, (klassOop) vmtarget);
   656       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
   657       fieldDescriptor fd; // find_field initializes fd if found
   658       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
   659         break;                  // cannot expand
   660       if (!have_defc) {
   661         sun_dyn_MemberName::set_clazz(mname(), defc->java_mirror());
   662       }
   663       if (!have_name) {
   664         //not java_lang_String::create_from_symbol; let's intern member names
   665         Handle name = StringTable::intern(fd.name(), CHECK);
   666         sun_dyn_MemberName::set_name(mname(), name());
   667       }
   668       if (!have_type) {
   669         Handle type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
   670         sun_dyn_MemberName::set_type(mname(), type());
   671       }
   672       return;
   673     }
   674   }
   675   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   676 }
   678 int MethodHandles::find_MemberNames(klassOop k,
   679                                     symbolOop name, symbolOop sig,
   680                                     int mflags, klassOop caller,
   681                                     int skip, objArrayOop results) {
   682   DEBUG_ONLY(No_Safepoint_Verifier nsv);
   683   // this code contains no safepoints!
   685   // %%% take caller into account!
   687   if (k == NULL || !Klass::cast(k)->oop_is_instance())  return -1;
   689   int rfill = 0, rlimit = results->length(), rskip = skip;
   690   // overflow measurement:
   691   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
   693   int match_flags = mflags;
   694   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
   695   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
   696   bool local_only = !(search_superc | search_intfc);
   697   bool classes_only = false;
   699   if (name != NULL) {
   700     if (name->utf8_length() == 0)  return 0; // a match is not possible
   701   }
   702   if (sig != NULL) {
   703     if (sig->utf8_length() == 0)  return 0; // a match is not possible
   704     if (sig->byte_at(0) == '(')
   705       match_flags &= ~(IS_FIELD | IS_TYPE);
   706     else
   707       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
   708   }
   710   if ((match_flags & IS_TYPE) != 0) {
   711     // NYI, and Core Reflection works quite well for this query
   712   }
   714   if ((match_flags & IS_FIELD) != 0) {
   715     for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   716       if (name != NULL && st.name() != name)
   717           continue;
   718       if (sig != NULL && st.signature() != sig)
   719         continue;
   720       // passed the filters
   721       if (rskip > 0) {
   722         --rskip;
   723       } else if (rfill < rlimit) {
   724         oop result = results->obj_at(rfill++);
   725         if (!sun_dyn_MemberName::is_instance(result))
   726           return -99;  // caller bug!
   727         MethodHandles::init_MemberName(result, st.klass()->as_klassOop(), st.access_flags(), st.offset());
   728       } else if (++overflow >= overflow_limit) {
   729         match_flags = 0; break; // got tired of looking at overflow
   730       }
   731     }
   732   }
   734   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
   735     // watch out for these guys:
   736     symbolOop init_name   = vmSymbols::object_initializer_name();
   737     symbolOop clinit_name = vmSymbols::class_initializer_name();
   738     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
   739     bool negate_name_test = false;
   740     // fix name so that it captures the intention of IS_CONSTRUCTOR
   741     if (!(match_flags & IS_METHOD)) {
   742       // constructors only
   743       if (name == NULL) {
   744         name = init_name;
   745       } else if (name != init_name) {
   746         return 0;               // no constructors of this method name
   747       }
   748     } else if (!(match_flags & IS_CONSTRUCTOR)) {
   749       // methods only
   750       if (name == NULL) {
   751         name = init_name;
   752         negate_name_test = true; // if we see the name, we *omit* the entry
   753       } else if (name == init_name) {
   754         return 0;               // no methods of this constructor name
   755       }
   756     } else {
   757       // caller will accept either sort; no need to adjust name
   758     }
   759     for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   760       methodOop m = st.method();
   761       symbolOop m_name = m->name();
   762       if (m_name == clinit_name)
   763         continue;
   764       if (name != NULL && ((m_name != name) ^ negate_name_test))
   765           continue;
   766       if (sig != NULL && m->signature() != sig)
   767         continue;
   768       // passed the filters
   769       if (rskip > 0) {
   770         --rskip;
   771       } else if (rfill < rlimit) {
   772         oop result = results->obj_at(rfill++);
   773         if (!sun_dyn_MemberName::is_instance(result))
   774           return -99;  // caller bug!
   775         MethodHandles::init_MemberName(result, m, true);
   776       } else if (++overflow >= overflow_limit) {
   777         match_flags = 0; break; // got tired of looking at overflow
   778       }
   779     }
   780   }
   782   // return number of elements we at leasted wanted to initialize
   783   return rfill + overflow;
   784 }
   787 // Decode this java.lang.Class object into an instanceKlass, if possible.
   788 // Throw IAE if not
   789 instanceKlassHandle MethodHandles::resolve_instance_klass(oop java_mirror_oop, TRAPS) {
   790   instanceKlassHandle empty;
   791   klassOop caller = NULL;
   792   if (java_lang_Class::is_instance(java_mirror_oop)) {
   793     caller = java_lang_Class::as_klassOop(java_mirror_oop);
   794   }
   795   if (caller == NULL || !Klass::cast(caller)->oop_is_instance()) {
   796     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not a class", empty);
   797   }
   798   return instanceKlassHandle(THREAD, caller);
   799 }
   803 // Decode the vmtarget field of a method handle.
   804 // Sanitize out methodOops, klassOops, and any other non-Java data.
   805 // This is for debugging and reflection.
   806 oop MethodHandles::encode_target(Handle mh, int format, TRAPS) {
   807   assert(java_dyn_MethodHandle::is_instance(mh()), "must be a MH");
   808   if (format == ETF_HANDLE_OR_METHOD_NAME) {
   809     oop target = java_dyn_MethodHandle::vmtarget(mh());
   810     if (target == NULL) {
   811       return NULL;                // unformed MH
   812     }
   813     klassOop tklass = target->klass();
   814     if (Klass::cast(tklass)->is_subclass_of(SystemDictionary::Object_klass())) {
   815       return target;              // target is another MH (or something else?)
   816     }
   817   }
   818   if (format == ETF_DIRECT_HANDLE) {
   819     oop target = mh();
   820     for (;;) {
   821       if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   822         return target;
   823       }
   824       if (!java_dyn_MethodHandle::is_instance(target)){
   825         return NULL;                // unformed MH
   826       }
   827       target = java_dyn_MethodHandle::vmtarget(target);
   828     }
   829   }
   830   // cases of metadata in MH.vmtarget:
   831   // - AMH can have methodOop for static invoke with bound receiver
   832   // - DMH can have methodOop for static invoke (on variable receiver)
   833   // - DMH can have klassOop for dispatched (non-static) invoke
   834   klassOop receiver_limit = NULL;
   835   int decode_flags = 0;
   836   methodOop m = decode_MethodHandle(mh(), receiver_limit, decode_flags);
   837   if (m == NULL)  return NULL;
   838   switch (format) {
   839   case ETF_REFLECT_METHOD:
   840     // same as jni_ToReflectedMethod:
   841     if (m->is_initializer()) {
   842       return Reflection::new_constructor(m, THREAD);
   843     } else {
   844       return Reflection::new_method(m, UseNewReflection, false, THREAD);
   845     }
   847   case ETF_HANDLE_OR_METHOD_NAME:   // method, not handle
   848   case ETF_METHOD_NAME:
   849     {
   850       if (SystemDictionary::MemberName_klass() == NULL)  break;
   851       instanceKlassHandle mname_klass(THREAD, SystemDictionary::MemberName_klass());
   852       mname_klass->initialize(CHECK_NULL);
   853       Handle mname = mname_klass->allocate_instance_handle(CHECK_NULL);
   854       sun_dyn_MemberName::set_vmindex(mname(), VM_INDEX_UNINITIALIZED);
   855       bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   856       init_MemberName(mname(), m, do_dispatch);
   857       expand_MemberName(mname, 0, CHECK_NULL);
   858       return mname();
   859     }
   860   }
   862   // Unknown format code.
   863   char msg[50];
   864   jio_snprintf(msg, sizeof(msg), "unknown getTarget format=%d", format);
   865   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), msg);
   866 }
   868 static const char* always_null_names[] = {
   869   "java/lang/Void",
   870   "java/lang/Null",
   871   //"java/lang/Nothing",
   872   "sun/dyn/empty/Empty",
   873   NULL
   874 };
   876 static bool is_always_null_type(klassOop klass) {
   877   if (!Klass::cast(klass)->oop_is_instance())  return false;
   878   instanceKlass* ik = instanceKlass::cast(klass);
   879   // Must be on the boot class path:
   880   if (ik->class_loader() != NULL)  return false;
   881   // Check the name.
   882   symbolOop name = ik->name();
   883   for (int i = 0; ; i++) {
   884     const char* test_name = always_null_names[i];
   885     if (test_name == NULL)  break;
   886     if (name->equals(test_name))
   887       return true;
   888   }
   889   return false;
   890 }
   892 bool MethodHandles::class_cast_needed(klassOop src, klassOop dst) {
   893   if (src == dst || dst == SystemDictionary::Object_klass())
   894     return false;                               // quickest checks
   895   Klass* srck = Klass::cast(src);
   896   Klass* dstk = Klass::cast(dst);
   897   if (dstk->is_interface()) {
   898     // interface receivers can safely be viewed as untyped,
   899     // because interface calls always include a dynamic check
   900     //dstk = Klass::cast(SystemDictionary::Object_klass());
   901     return false;
   902   }
   903   if (srck->is_interface()) {
   904     // interface arguments must be viewed as untyped
   905     //srck = Klass::cast(SystemDictionary::Object_klass());
   906     return true;
   907   }
   908   if (is_always_null_type(src)) {
   909     // some source types are known to be never instantiated;
   910     // they represent references which are always null
   911     // such null references never fail to convert safely
   912     return false;
   913   }
   914   return !srck->is_subclass_of(dstk->as_klassOop());
   915 }
   917 static oop object_java_mirror() {
   918   return Klass::cast(SystemDictionary::Object_klass())->java_mirror();
   919 }
   921 bool MethodHandles::same_basic_type_for_arguments(BasicType src,
   922                                                   BasicType dst,
   923                                                   bool raw,
   924                                                   bool for_return) {
   925   if (for_return) {
   926     // return values can always be forgotten:
   927     if (dst == T_VOID)  return true;
   928     if (src == T_VOID)  return raw && (dst == T_INT);
   929     // We allow caller to receive a garbage int, which is harmless.
   930     // This trick is pulled by trusted code (see VerifyType.canPassRaw).
   931   }
   932   assert(src != T_VOID && dst != T_VOID, "should not be here");
   933   if (src == dst)  return true;
   934   if (type2size[src] != type2size[dst])  return false;
   935   // allow reinterpretation casts for integral widening
   936   if (is_subword_type(src)) { // subwords can fit in int or other subwords
   937     if (dst == T_INT)         // any subword fits in an int
   938       return true;
   939     if (src == T_BOOLEAN)     // boolean fits in any subword
   940       return is_subword_type(dst);
   941     if (src == T_BYTE && dst == T_SHORT)
   942       return true;            // remaining case: byte fits in short
   943   }
   944   // allow float/fixed reinterpretation casts
   945   if (src == T_FLOAT)   return dst == T_INT;
   946   if (src == T_INT)     return dst == T_FLOAT;
   947   if (src == T_DOUBLE)  return dst == T_LONG;
   948   if (src == T_LONG)    return dst == T_DOUBLE;
   949   return false;
   950 }
   952 const char* MethodHandles::check_method_receiver(methodOop m,
   953                                                  klassOop passed_recv_type) {
   954   assert(!m->is_static(), "caller resp.");
   955   if (passed_recv_type == NULL)
   956     return "receiver type is primitive";
   957   if (class_cast_needed(passed_recv_type, m->method_holder())) {
   958     Klass* formal = Klass::cast(m->method_holder());
   959     return SharedRuntime::generate_class_cast_message("receiver type",
   960                                                       formal->external_name());
   961   }
   962   return NULL;                  // checks passed
   963 }
   965 // Verify that m's signature can be called type-safely by a method handle
   966 // of the given method type 'mtype'.
   967 // It takes a TRAPS argument because it must perform symbol lookups.
   968 void MethodHandles::verify_method_signature(methodHandle m,
   969                                             Handle mtype,
   970                                             int first_ptype_pos,
   971                                             KlassHandle insert_ptype,
   972                                             TRAPS) {
   973   objArrayHandle ptypes(THREAD, java_dyn_MethodType::ptypes(mtype()));
   974   int pnum = first_ptype_pos;
   975   int pmax = ptypes->length();
   976   int mnum = 0;                 // method argument
   977   const char* err = NULL;
   978   for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
   979     oop ptype_oop = NULL;
   980     if (ss.at_return_type()) {
   981       if (pnum != pmax)
   982         { err = "too many arguments"; break; }
   983       ptype_oop = java_dyn_MethodType::rtype(mtype());
   984     } else {
   985       if (pnum >= pmax)
   986         { err = "not enough arguments"; break; }
   987       if (pnum >= 0)
   988         ptype_oop = ptypes->obj_at(pnum);
   989       else if (insert_ptype.is_null())
   990         ptype_oop = NULL;
   991       else
   992         ptype_oop = insert_ptype->java_mirror();
   993       pnum += 1;
   994       mnum += 1;
   995     }
   996     klassOop  mklass = NULL;
   997     BasicType mtype  = ss.type();
   998     if (mtype == T_ARRAY)  mtype = T_OBJECT; // fold all refs to T_OBJECT
   999     if (mtype == T_OBJECT) {
  1000       if (ptype_oop == NULL) {
  1001         // null matches any reference
  1002         continue;
  1004       // If we fail to resolve types at this point, we will throw an error.
  1005       symbolOop    name_oop = ss.as_symbol(CHECK);
  1006       symbolHandle name(THREAD, name_oop);
  1007       instanceKlass* mk = instanceKlass::cast(m->method_holder());
  1008       Handle loader(THREAD, mk->class_loader());
  1009       Handle domain(THREAD, mk->protection_domain());
  1010       mklass = SystemDictionary::resolve_or_fail(name, loader, domain,
  1011                                                  true, CHECK);
  1013     if (ptype_oop == NULL) {
  1014       // null does not match any non-reference; use Object to report the error
  1015       ptype_oop = object_java_mirror();
  1017     klassOop  pklass = NULL;
  1018     BasicType ptype  = java_lang_Class::as_BasicType(ptype_oop, &pklass);
  1019     if (!ss.at_return_type()) {
  1020       err = check_argument_type_change(ptype, pklass, mtype, mklass, mnum);
  1021     } else {
  1022       err = check_return_type_change(mtype, mklass, ptype, pklass); // note reversal!
  1024     if (err != NULL)  break;
  1027   if (err != NULL) {
  1028     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1032 // Main routine for verifying the MethodHandle.type of a proposed
  1033 // direct or bound-direct method handle.
  1034 void MethodHandles::verify_method_type(methodHandle m,
  1035                                        Handle mtype,
  1036                                        bool has_bound_recv,
  1037                                        KlassHandle bound_recv_type,
  1038                                        TRAPS) {
  1039   bool m_needs_receiver = !m->is_static();
  1041   const char* err = NULL;
  1043   int first_ptype_pos = m_needs_receiver ? 1 : 0;
  1044   if (has_bound_recv) {
  1045     first_ptype_pos -= 1;  // ptypes do not include the bound argument; start earlier in them
  1046     if (m_needs_receiver && bound_recv_type.is_null())
  1047       { err = "bound receiver is not an object"; goto die; }
  1050   if (m_needs_receiver && err == NULL) {
  1051     objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype());
  1052     if (ptypes->length() < first_ptype_pos)
  1053       { err = "receiver argument is missing"; goto die; }
  1054     if (has_bound_recv)
  1055       err = check_method_receiver(m(), bound_recv_type->as_klassOop());
  1056     else
  1057       err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
  1058     if (err != NULL)  goto die;
  1061   // Check the other arguments for mistypes.
  1062   verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
  1063   return;
  1065  die:
  1066   THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1069 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
  1070   // Verify vmslots.
  1071   int check_slots = argument_slot_count(java_dyn_MethodHandle::type(mh()));
  1072   if (java_dyn_MethodHandle::vmslots(mh()) != check_slots) {
  1073     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
  1077 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
  1078   // Verify that argslot points at the given argnum.
  1079   int check_slot = argument_slot(java_dyn_MethodHandle::type(mh()), argnum);
  1080   if (argslot != check_slot || argslot < 0) {
  1081     const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
  1082     size_t msglen = strlen(fmt) + 3*11 + 1;
  1083     char* msg = NEW_RESOURCE_ARRAY(char, msglen);
  1084     jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
  1085     THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
  1089 // Verify the correspondence between two method types.
  1090 // Apart from the advertised changes, caller method type X must
  1091 // be able to invoke the callee method Y type with no violations
  1092 // of type integrity.
  1093 // Return NULL if all is well, else a short error message.
  1094 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
  1095                                                     int insert_argnum, oop insert_type,
  1096                                                     int change_argnum, oop change_type,
  1097                                                     int delete_argnum,
  1098                                                     oop dst_mtype, int dst_beg, int dst_end,
  1099                                                     bool raw) {
  1100   objArrayOop src_ptypes = java_dyn_MethodType::ptypes(src_mtype);
  1101   objArrayOop dst_ptypes = java_dyn_MethodType::ptypes(dst_mtype);
  1103   int src_max = src_ptypes->length();
  1104   int dst_max = dst_ptypes->length();
  1106   if (src_end == -1)  src_end = src_max;
  1107   if (dst_end == -1)  dst_end = dst_max;
  1109   assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
  1110   assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
  1112   // pending actions; set to -1 when done:
  1113   int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
  1115   const char* err = NULL;
  1117   // Walk along each array of parameter types, including a virtual
  1118   // NULL end marker at the end of each.
  1119   for (int src_idx = src_beg, dst_idx = dst_beg;
  1120        (src_idx <= src_end && dst_idx <= dst_end);
  1121        src_idx++, dst_idx++) {
  1122     oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
  1123     oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
  1124     bool fix_null_src_type = false;
  1126     // Perform requested edits.
  1127     if (ins_idx == src_idx) {
  1128       // note that the inserted guy is never affected by a change or deletion
  1129       ins_idx = -1;
  1130       src_type = insert_type;
  1131       fix_null_src_type = true;
  1132       --src_idx;                // back up to process src type on next loop
  1133       src_idx = src_end;
  1134     } else {
  1135       // note that the changed guy can be immediately deleted
  1136       if (chg_idx == src_idx) {
  1137         chg_idx = -1;
  1138         assert(src_idx < src_end, "oob");
  1139         src_type = change_type;
  1140         fix_null_src_type = true;
  1142       if (del_idx == src_idx) {
  1143         del_idx = -1;
  1144         assert(src_idx < src_end, "oob");
  1145         --dst_idx;
  1146         continue;               // rerun loop after skipping this position
  1150     if (src_type == NULL && fix_null_src_type)
  1151       // explicit null in this case matches any dest reference
  1152       src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
  1154     // Compare the two argument types.
  1155     if (src_type != dst_type) {
  1156       if (src_type == NULL)  return "not enough arguments";
  1157       if (dst_type == NULL)  return "too many arguments";
  1158       err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
  1159       if (err != NULL)  return err;
  1163   // Now compare return types also.
  1164   oop src_rtype = java_dyn_MethodType::rtype(src_mtype);
  1165   oop dst_rtype = java_dyn_MethodType::rtype(dst_mtype);
  1166   if (src_rtype != dst_rtype) {
  1167     err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
  1168     if (err != NULL)  return err;
  1171   assert(err == NULL, "");
  1172   return NULL;  // all is well
  1176 const char* MethodHandles::check_argument_type_change(BasicType src_type,
  1177                                                       klassOop src_klass,
  1178                                                       BasicType dst_type,
  1179                                                       klassOop dst_klass,
  1180                                                       int argnum,
  1181                                                       bool raw) {
  1182   const char* err = NULL;
  1183   bool for_return = (argnum < 0);
  1185   // just in case:
  1186   if (src_type == T_ARRAY)  src_type = T_OBJECT;
  1187   if (dst_type == T_ARRAY)  dst_type = T_OBJECT;
  1189   // Produce some nice messages if VerifyMethodHandles is turned on:
  1190   if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
  1191     if (src_type == T_OBJECT) {
  1192       if (raw && dst_type == T_INT && is_always_null_type(src_klass))
  1193         return NULL;    // OK to convert a null pointer to a garbage int
  1194       err = ((argnum >= 0)
  1195              ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
  1196              : "type mismatch: returning a %s, but caller expects primitive %s");
  1197     } else if (dst_type == T_OBJECT) {
  1198       err = ((argnum >= 0)
  1199              ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
  1200              : "type mismatch: returning a primitive %s, but caller expects %s");
  1201     } else {
  1202       err = ((argnum >= 0)
  1203              ? "type mismatch: passing a %s for method argument #%d, which expects %s"
  1204              : "type mismatch: returning a %s, but caller expects %s");
  1206   } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
  1207              class_cast_needed(src_klass, dst_klass)) {
  1208     if (!class_cast_needed(dst_klass, src_klass)) {
  1209       if (raw)
  1210         return NULL;    // reverse cast is OK; the MH target is trusted to enforce it
  1211       err = ((argnum >= 0)
  1212              ? "cast required: passing a %s for method argument #%d, which expects %s"
  1213              : "cast required: returning a %s, but caller expects %s");
  1214     } else {
  1215       err = ((argnum >= 0)
  1216              ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
  1217              : "reference mismatch: returning a %s, but caller expects %s");
  1219   } else {
  1220     // passed the obstacle course
  1221     return NULL;
  1224   // format, format, format
  1225   const char* src_name = type2name(src_type);
  1226   const char* dst_name = type2name(dst_type);
  1227   if (src_type == T_OBJECT)  src_name = Klass::cast(src_klass)->external_name();
  1228   if (dst_type == T_OBJECT)  dst_name = Klass::cast(dst_klass)->external_name();
  1229   if (src_name == NULL)  src_name = "unknown type";
  1230   if (dst_name == NULL)  dst_name = "unknown type";
  1232   size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
  1233   char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
  1234   if (argnum >= 0) {
  1235     assert(strstr(err, "%d") != NULL, "");
  1236     jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
  1237   } else {
  1238     assert(strstr(err, "%d") == NULL, "");
  1239     jio_snprintf(msg, msglen, err, src_name,         dst_name);
  1241   return msg;
  1244 // Compute the depth within the stack of the given argument, i.e.,
  1245 // the combined size of arguments to the right of the given argument.
  1246 // For the last argument (ptypes.length-1) this will be zero.
  1247 // For the first argument (0) this will be the size of all
  1248 // arguments but that one.  For the special number -1, this
  1249 // will be the size of all arguments, including the first.
  1250 // If the argument is neither -1 nor a valid argument index,
  1251 // then return a negative number.  Otherwise, the result
  1252 // is in the range [0..vmslots] inclusive.
  1253 int MethodHandles::argument_slot(oop method_type, int arg) {
  1254   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1255   int argslot = 0;
  1256   int len = ptypes->length();
  1257   if (arg < -1 || arg >= len)  return -99;
  1258   for (int i = len-1; i > arg; i--) {
  1259     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1260     argslot += type2size[bt];
  1262   assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
  1263   return argslot;
  1266 // Given a slot number, return the argument number.
  1267 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
  1268   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1269   int argslot = 0;
  1270   int len = ptypes->length();
  1271   for (int i = len-1; i >= 0; i--) {
  1272     if (query_argslot == argslot)  return i;
  1273     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1274     argslot += type2size[bt];
  1276   // return pseudo-arg deepest in stack:
  1277   if (query_argslot == argslot)  return -1;
  1278   return -99;                   // oob slot, or splitting a double-slot arg
  1281 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
  1282                                                     KlassHandle receiver_limit,
  1283                                                     int decode_flags,
  1284                                                     KlassHandle receiver_klass,
  1285                                                     TRAPS) {
  1286   assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
  1287   assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
  1289   if (!m->is_static() &&
  1290       (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
  1291     // given type does not match class of method, or receiver is null!
  1292     // caller should have checked this, but let's be extra careful...
  1293     return methodHandle();
  1295   if (receiver_limit.not_null() &&
  1296       (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
  1297     // given type is not limited to the receiver type
  1298     // note that a null receiver can match any reference value, for a static method
  1299     return methodHandle();
  1301   if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
  1302     // pre-dispatched or static method (null receiver is OK for static)
  1303     return m;
  1305   } else if (receiver_klass.is_null()) {
  1306     // null receiver value; cannot dispatch
  1307     return methodHandle();
  1309   } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
  1310     // perform virtual dispatch
  1311     int vtable_index = m->vtable_index();
  1312     guarantee(vtable_index >= 0, "valid vtable index");
  1314     // receiver_klass might be an arrayKlassOop but all vtables start at
  1315     // the same place. The cast is to avoid virtual call and assertion.
  1316     // See also LinkResolver::runtime_resolve_virtual_method.
  1317     instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
  1318     DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
  1319     methodOop m_oop = inst->method_at_vtable(vtable_index);
  1320     return methodHandle(THREAD, m_oop);
  1322   } else {
  1323     // perform interface dispatch
  1324     int itable_index = klassItable::compute_itable_index(m());
  1325     guarantee(itable_index >= 0, "valid itable index");
  1326     instanceKlass* inst = instanceKlass::cast(receiver_klass());
  1327     methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
  1328     return methodHandle(THREAD, m_oop);
  1332 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
  1333   // Verify type.
  1334   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1335   verify_method_type(m, mtype, false, KlassHandle(), CHECK);
  1337   // Verify vmslots.
  1338   if (java_dyn_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
  1339     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
  1343 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
  1344   // Check arguments.
  1345   if (mh.is_null() || m.is_null() ||
  1346       (!do_dispatch && m->is_abstract())) {
  1347     THROW(vmSymbols::java_lang_InternalError());
  1350   java_dyn_MethodHandle::init_vmslots(mh());
  1352   if (VerifyMethodHandles) {
  1353     // The privileged code which invokes this routine should not make
  1354     // a mistake about types, but it's better to verify.
  1355     verify_DirectMethodHandle(mh, m, CHECK);
  1358   // Finally, after safety checks are done, link to the target method.
  1359   // We will follow the same path as the latter part of
  1360   // InterpreterRuntime::resolve_invoke(), which first finds the method
  1361   // and then decides how to populate the constant pool cache entry
  1362   // that links the interpreter calls to the method.  We need the same
  1363   // bits, and will use the same calling sequence code.
  1365   int vmindex = methodOopDesc::garbage_vtable_index;
  1366   oop vmtarget = NULL;
  1368   instanceKlass::cast(m->method_holder())->link_class(CHECK);
  1370   MethodHandleEntry* me = NULL;
  1371   if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
  1372     // We are simulating an invokeinterface instruction.
  1373     // (We might also be simulating an invokevirtual on a miranda method,
  1374     // but it is safe to treat it as an invokeinterface.)
  1375     assert(!m->can_be_statically_bound(), "no final methods on interfaces");
  1376     vmindex = klassItable::compute_itable_index(m());
  1377     assert(vmindex >= 0, "(>=0) == do_dispatch");
  1378     // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
  1379     vmtarget = m->method_holder(); // the interface
  1380     me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
  1381   } else if (!do_dispatch || m->can_be_statically_bound()) {
  1382     // We are simulating an invokestatic or invokespecial instruction.
  1383     // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
  1384     vmtarget = m();
  1385     // this does not help dispatch, but it will make it possible to parse this MH:
  1386     vmindex  = methodOopDesc::nonvirtual_vtable_index;
  1387     assert(vmindex < 0, "(>=0) == do_dispatch");
  1388     if (!m->is_static()) {
  1389       me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
  1390     } else {
  1391       me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
  1392       // Part of the semantics of a static call is an initialization barrier.
  1393       // For a DMH, it is done now, when the handle is created.
  1394       Klass* k = Klass::cast(m->method_holder());
  1395       if (k->should_be_initialized()) {
  1396         k->initialize(CHECK);
  1399   } else {
  1400     // We are simulating an invokevirtual instruction.
  1401     // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
  1402     // The key logic is LinkResolver::runtime_resolve_virtual_method.
  1403     vmindex  = m->vtable_index();
  1404     vmtarget = m->method_holder();
  1405     me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
  1408   if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  1410   sun_dyn_DirectMethodHandle::set_vmtarget(mh(), vmtarget);
  1411   sun_dyn_DirectMethodHandle::set_vmindex(mh(),  vmindex);
  1412   DEBUG_ONLY(int flags; klassOop rlimit);
  1413   assert(MethodHandles::decode_method(mh(), rlimit, flags) == m(),
  1414          "properly stored for later decoding");
  1415   DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
  1416   assert(!(actual_do_dispatch && !do_dispatch),
  1417          "do not perform dispatch if !do_dispatch specified");
  1418   assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
  1419   assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
  1421   // Done!
  1422   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1425 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
  1426                                                            methodHandle m,
  1427                                                            TRAPS) {
  1428   // Verify type.
  1429   oop receiver = sun_dyn_BoundMethodHandle::argument(mh());
  1430   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1431   KlassHandle bound_recv_type;
  1432   if (receiver != NULL)  bound_recv_type = KlassHandle(THREAD, receiver->klass());
  1433   verify_method_type(m, mtype, true, bound_recv_type, CHECK);
  1435   int receiver_pos = m->size_of_parameters() - 1;
  1437   // Verify MH.vmargslot, which should point at the bound receiver.
  1438   verify_vmargslot(mh, -1, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1439   //verify_vmslots(mh, CHECK);
  1441   // Verify vmslots.
  1442   if (java_dyn_MethodHandle::vmslots(mh()) != receiver_pos) {
  1443     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
  1447 // Initialize a BMH with a receiver bound directly to a methodOop.
  1448 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
  1449                                                          methodHandle original_m,
  1450                                                          KlassHandle receiver_limit,
  1451                                                          int decode_flags,
  1452                                                          TRAPS) {
  1453   // Check arguments.
  1454   if (mh.is_null() || original_m.is_null()) {
  1455     THROW(vmSymbols::java_lang_InternalError());
  1458   KlassHandle receiver_klass;
  1460     oop receiver_oop = sun_dyn_BoundMethodHandle::argument(mh());
  1461     if (receiver_oop != NULL)
  1462       receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
  1464   methodHandle m = dispatch_decoded_method(original_m,
  1465                                            receiver_limit, decode_flags,
  1466                                            receiver_klass,
  1467                                            CHECK);
  1468   if (m.is_null())      { THROW(vmSymbols::java_lang_InternalError()); }
  1469   if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
  1471   java_dyn_MethodHandle::init_vmslots(mh());
  1473   if (VerifyMethodHandles) {
  1474     verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
  1477   sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1479   DEBUG_ONLY(int junk; klassOop junk2);
  1480   assert(MethodHandles::decode_method(mh(), junk2, junk) == m(), "properly stored for later decoding");
  1481   assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
  1483   // Done!
  1484   java_dyn_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
  1487 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
  1488                                              bool direct_to_method, TRAPS) {
  1489   Handle ptype_handle(THREAD,
  1490                            java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum));
  1491   KlassHandle ptype_klass;
  1492   BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
  1493   int slots_pushed = type2size[ptype];
  1495   oop argument = sun_dyn_BoundMethodHandle::argument(mh());
  1497   const char* err = NULL;
  1499   switch (ptype) {
  1500   case T_OBJECT:
  1501     if (argument != NULL)
  1502       // we must implicitly convert from the arg type to the outgoing ptype
  1503       err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
  1504     break;
  1506   case T_ARRAY: case T_VOID:
  1507     assert(false, "array, void do not appear here");
  1508   default:
  1509     if (ptype != T_INT && !is_subword_type(ptype)) {
  1510       err = "unexpected parameter type";
  1511       break;
  1513     // check subrange of Integer.value, if necessary
  1514     if (argument == NULL || argument->klass() != SystemDictionary::Integer_klass()) {
  1515       err = "bound integer argument must be of type java.lang.Integer";
  1516       break;
  1518     if (ptype != T_INT) {
  1519       int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
  1520       jint value = argument->int_field(value_offset);
  1521       int vminfo = adapter_subword_vminfo(ptype);
  1522       jint subword = truncate_subword_from_vminfo(value, vminfo);
  1523       if (value != subword) {
  1524         err = "bound subword value does not fit into the subword type";
  1525         break;
  1528     break;
  1529   case T_FLOAT:
  1530   case T_DOUBLE:
  1531   case T_LONG:
  1533       // we must implicitly convert from the unboxed arg type to the outgoing ptype
  1534       BasicType argbox = java_lang_boxing_object::basic_type(argument);
  1535       if (argbox != ptype) {
  1536         err = check_argument_type_change(T_OBJECT, (argument == NULL
  1537                                                     ? SystemDictionary::Object_klass()
  1538                                                     : argument->klass()),
  1539                                          ptype, ptype_klass(), argnum);
  1540         assert(err != NULL, "this must be an error");
  1542       break;
  1546   if (err == NULL) {
  1547     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1548     if (direct_to_method) {
  1549       assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
  1550       assert(slots_pushed <= MethodHandlePushLimit, "");
  1551     } else {
  1552       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1553       assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
  1554       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1555       // FIXME
  1556       // if (slots_pushed + target_pushes > MethodHandlePushLimit)
  1557       //   err = "too many bound parameters";
  1561   if (err == NULL) {
  1562     // Verify the rest of the method type.
  1563     err = check_method_type_insertion(java_dyn_MethodHandle::type(mh()),
  1564                                       argnum, ptype_handle(),
  1565                                       java_dyn_MethodHandle::type(target()));
  1568   if (err != NULL) {
  1569     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1573 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1574   // Check arguments.
  1575   if (mh.is_null() || target.is_null() || !java_dyn_MethodHandle::is_instance(target())) {
  1576     THROW(vmSymbols::java_lang_InternalError());
  1579   java_dyn_MethodHandle::init_vmslots(mh());
  1581   if (VerifyMethodHandles) {
  1582     int insert_after = argnum - 1;
  1583     verify_vmargslot(mh, insert_after, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1584     verify_vmslots(mh, CHECK);
  1587   // Get bound type and required slots.
  1588   oop ptype_oop = java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum);
  1589   BasicType ptype = java_lang_Class::as_BasicType(ptype_oop);
  1590   int slots_pushed = type2size[ptype];
  1592   // If (a) the target is a direct non-dispatched method handle,
  1593   // or (b) the target is a dispatched direct method handle and we
  1594   // are binding the receiver, cut out the middle-man.
  1595   // Do this by decoding the DMH and using its methodOop directly as vmtarget.
  1596   bool direct_to_method = false;
  1597   if (OptimizeMethodHandles &&
  1598       target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
  1599       (argnum == 0 || sun_dyn_DirectMethodHandle::vmindex(target()) < 0)) {
  1600     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  1601     methodHandle m(THREAD, decode_method(target(), receiver_limit_oop, decode_flags));
  1602     if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
  1603     DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - slots_pushed); // pos. of 1st arg.
  1604     assert(sun_dyn_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
  1605     if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
  1606       KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  1607       init_BoundMethodHandle_with_receiver(mh, m,
  1608                                            receiver_limit, decode_flags,
  1609                                            CHECK);
  1610       return;
  1613     // Even if it is not a bound receiver, we still might be able
  1614     // to bind another argument and still invoke the methodOop directly.
  1615     if (!(decode_flags & _dmf_does_dispatch)) {
  1616       direct_to_method = true;
  1617       sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1620   if (!direct_to_method)
  1621     sun_dyn_BoundMethodHandle::set_vmtarget(mh(), target());
  1623   if (VerifyMethodHandles) {
  1624     verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
  1627   // Next question:  Is this a ref, int, or long bound value?
  1628   MethodHandleEntry* me = NULL;
  1629   if (ptype == T_OBJECT) {
  1630     if (direct_to_method)  me = MethodHandles::entry(_bound_ref_direct_mh);
  1631     else                   me = MethodHandles::entry(_bound_ref_mh);
  1632   } else if (slots_pushed == 2) {
  1633     if (direct_to_method)  me = MethodHandles::entry(_bound_long_direct_mh);
  1634     else                   me = MethodHandles::entry(_bound_long_mh);
  1635   } else if (slots_pushed == 1) {
  1636     if (direct_to_method)  me = MethodHandles::entry(_bound_int_direct_mh);
  1637     else                   me = MethodHandles::entry(_bound_int_mh);
  1638   } else {
  1639     assert(false, "");
  1642   // Done!
  1643   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1646 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
  1647   char msg[200];
  1648   jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
  1649   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
  1652 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
  1653   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1654   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1656   verify_vmargslot(mh, argnum, argslot, CHECK);
  1657   verify_vmslots(mh, CHECK);
  1659   jint conv_op    = adapter_conversion_op(conversion);
  1660   if (!conv_op_valid(conv_op)) {
  1661     throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
  1662     return;
  1664   EntryKind ek = adapter_entry_kind(conv_op);
  1666   int stack_move = adapter_conversion_stack_move(conversion);
  1667   BasicType src  = adapter_conversion_src_type(conversion);
  1668   BasicType dest = adapter_conversion_dest_type(conversion);
  1669   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1671   Handle argument(THREAD,  sun_dyn_AdapterMethodHandle::argument(mh()));
  1672   Handle target(THREAD,    sun_dyn_AdapterMethodHandle::vmtarget(mh()));
  1673   Handle src_mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1674   Handle dst_mtype(THREAD, java_dyn_MethodHandle::type(target()));
  1676   const char* err = NULL;
  1678   if (err == NULL) {
  1679     // Check that the correct argument is supplied, but only if it is required.
  1680     switch (ek) {
  1681     case _adapter_check_cast:     // target type of cast
  1682     case _adapter_ref_to_prim:    // wrapper type from which to unbox
  1683     case _adapter_prim_to_ref:    // wrapper type to box into
  1684     case _adapter_collect_args:   // array type to collect into
  1685     case _adapter_spread_args:    // array type to spread from
  1686       if (!java_lang_Class::is_instance(argument())
  1687           || java_lang_Class::is_primitive(argument()))
  1688         { err = "adapter requires argument of type java.lang.Class"; break; }
  1689       if (ek == _adapter_collect_args ||
  1690           ek == _adapter_spread_args) {
  1691         // Make sure it is a suitable collection type.  (Array, for now.)
  1692         Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
  1693         if (!ak->oop_is_objArray()) {
  1694           { err = "adapter requires argument of type java.lang.Class<Object[]>"; break; }
  1697       break;
  1698     case _adapter_flyby:
  1699     case _adapter_ricochet:
  1700       if (!java_dyn_MethodHandle::is_instance(argument()))
  1701         { err = "MethodHandle adapter argument required"; break; }
  1702       break;
  1703     default:
  1704       if (argument.not_null())
  1705         { err = "adapter has spurious argument"; break; }
  1706       break;
  1710   if (err == NULL) {
  1711     // Check that the src/dest types are supplied if needed.
  1712     switch (ek) {
  1713     case _adapter_check_cast:
  1714       if (src != T_OBJECT || dest != T_OBJECT) {
  1715         err = "adapter requires object src/dest conversion subfields";
  1717       break;
  1718     case _adapter_prim_to_prim:
  1719       if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
  1720         err = "adapter requires primitive src/dest conversion subfields"; break;
  1722       if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
  1723           !(src == T_FLOAT || src == T_DOUBLE) &&  (dest == T_FLOAT || dest == T_DOUBLE)) {
  1724         err = "adapter cannot convert beween floating and fixed-point"; break;
  1726       break;
  1727     case _adapter_ref_to_prim:
  1728       if (src != T_OBJECT || !is_java_primitive(dest)
  1729           || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
  1730         err = "adapter requires primitive dest conversion subfield"; break;
  1732       break;
  1733     case _adapter_prim_to_ref:
  1734       if (!is_java_primitive(src) || dest != T_OBJECT
  1735           || argument() != Klass::cast(SystemDictionary::box_klass(src))->java_mirror()) {
  1736         err = "adapter requires primitive src conversion subfield"; break;
  1738       break;
  1739     case _adapter_swap_args:
  1740     case _adapter_rot_args:
  1742         if (!src || src != dest) {
  1743           err = "adapter requires src/dest conversion subfields for swap"; break;
  1745         int swap_size = type2size[src];
  1746         oop src_mtype  = sun_dyn_AdapterMethodHandle::type(mh());
  1747         oop dest_mtype = sun_dyn_AdapterMethodHandle::type(target());
  1748         int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(target());
  1749         int src_slot   = argslot;
  1750         int dest_slot  = vminfo;
  1751         bool rotate_up = (src_slot > dest_slot); // upward rotation
  1752         int src_arg    = argnum;
  1753         int dest_arg   = argument_slot_to_argnum(dest_mtype, dest_slot);
  1754         verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
  1755         if (!(dest_slot >= src_slot + swap_size) &&
  1756             !(src_slot >= dest_slot + swap_size)) {
  1757           err = "source, destination slots must be distinct";
  1758         } else if (ek == _adapter_swap_args && !(src_slot > dest_slot)) {
  1759           err = "source of swap must be deeper in stack";
  1760         } else if (ek == _adapter_swap_args) {
  1761           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, dest_arg),
  1762                                            java_dyn_MethodType::ptype(dest_mtype, src_arg),
  1763                                            dest_arg);
  1764         } else if (ek == _adapter_rot_args) {
  1765           if (rotate_up) {
  1766             assert((src_slot > dest_slot) && (src_arg < dest_arg), "");
  1767             // rotate up: [dest_slot..src_slot-ss] --> [dest_slot+ss..src_slot]
  1768             // that is:   [src_arg+1..dest_arg] --> [src_arg..dest_arg-1]
  1769             for (int i = src_arg+1; i <= dest_arg && err == NULL; i++) {
  1770               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1771                                                java_dyn_MethodType::ptype(dest_mtype, i-1),
  1772                                                i);
  1774           } else { // rotate down
  1775             assert((src_slot < dest_slot) && (src_arg > dest_arg), "");
  1776             // rotate down: [src_slot+ss..dest_slot] --> [src_slot..dest_slot-ss]
  1777             // that is:     [dest_arg..src_arg-1] --> [dst_arg+1..src_arg]
  1778             for (int i = dest_arg; i <= src_arg-1 && err == NULL; i++) {
  1779               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1780                                                java_dyn_MethodType::ptype(dest_mtype, i+1),
  1781                                                i);
  1785         if (err == NULL)
  1786           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, src_arg),
  1787                                            java_dyn_MethodType::ptype(dest_mtype, dest_arg),
  1788                                            src_arg);
  1790       break;
  1791     case _adapter_collect_args:
  1792     case _adapter_spread_args:
  1794         BasicType coll_type = (ek == _adapter_collect_args) ? dest : src;
  1795         BasicType elem_type = (ek == _adapter_collect_args) ? src : dest;
  1796         if (coll_type != T_OBJECT || elem_type != T_OBJECT) {
  1797           err = "adapter requires src/dest subfields"; break;
  1798           // later:
  1799           // - consider making coll be a primitive array
  1800           // - consider making coll be a heterogeneous collection
  1803       break;
  1804     default:
  1805       if (src != 0 || dest != 0) {
  1806         err = "adapter has spurious src/dest conversion subfields"; break;
  1808       break;
  1812   if (err == NULL) {
  1813     // Check the stack_move subfield.
  1814     // It must always report the net change in stack size, positive or negative.
  1815     int slots_pushed = stack_move / stack_move_unit();
  1816     switch (ek) {
  1817     case _adapter_prim_to_prim:
  1818     case _adapter_ref_to_prim:
  1819     case _adapter_prim_to_ref:
  1820       if (slots_pushed != type2size[dest] - type2size[src]) {
  1821         err = "wrong stack motion for primitive conversion";
  1823       break;
  1824     case _adapter_dup_args:
  1825       if (slots_pushed <= 0) {
  1826         err = "adapter requires conversion subfield slots_pushed > 0";
  1828       break;
  1829     case _adapter_drop_args:
  1830       if (slots_pushed >= 0) {
  1831         err = "adapter requires conversion subfield slots_pushed < 0";
  1833       break;
  1834     case _adapter_collect_args:
  1835       if (slots_pushed > 1) {
  1836         err = "adapter requires conversion subfield slots_pushed <= 1";
  1838       break;
  1839     case _adapter_spread_args:
  1840       if (slots_pushed < -1) {
  1841         err = "adapter requires conversion subfield slots_pushed >= -1";
  1843       break;
  1844     default:
  1845       if (stack_move != 0) {
  1846         err = "adapter has spurious stack_move conversion subfield";
  1848       break;
  1850     if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
  1851       err = "stack_move conversion subfield must be multiple of stack_move_unit";
  1855   if (err == NULL) {
  1856     // Make sure this adapter does not push too deeply.
  1857     int slots_pushed = stack_move / stack_move_unit();
  1858     int this_vmslots = java_dyn_MethodHandle::vmslots(mh());
  1859     int target_vmslots = java_dyn_MethodHandle::vmslots(target());
  1860     if (slots_pushed != (target_vmslots - this_vmslots)) {
  1861       err = "stack_move inconsistent with previous and current MethodType vmslots";
  1862     } else if (slots_pushed > 0)  {
  1863       // verify stack_move against MethodHandlePushLimit
  1864       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1865       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1866       if (slots_pushed + target_pushes > MethodHandlePushLimit) {
  1867         err = "adapter pushes too many parameters";
  1871     // While we're at it, check that the stack motion decoder works:
  1872     DEBUG_ONLY(int target_pushes = decode_MethodHandle_stack_pushes(target()));
  1873     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1874     assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
  1877   if (err == NULL && vminfo != 0) {
  1878     switch (ek) {
  1879       case _adapter_swap_args:
  1880       case _adapter_rot_args:
  1881         break;                // OK
  1882     default:
  1883       err = "vminfo subfield is reserved to the JVM";
  1887   // Do additional ad hoc checks.
  1888   if (err == NULL) {
  1889     switch (ek) {
  1890     case _adapter_retype_only:
  1891       err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
  1892       break;
  1894     case _adapter_retype_raw:
  1895       err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
  1896       break;
  1898     case _adapter_check_cast:
  1900         // The actual value being checked must be a reference:
  1901         err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype(), argnum),
  1902                                          object_java_mirror(), argnum);
  1903         if (err != NULL)  break;
  1905         // The output of the cast must fit with the destination argument:
  1906         Handle cast_class = argument;
  1907         err = check_method_type_conversion(src_mtype(),
  1908                                            argnum, cast_class(),
  1909                                            dst_mtype());
  1911       break;
  1913       // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
  1917   if (err != NULL) {
  1918     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  1919     return;
  1924 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1925   oop  argument   = sun_dyn_AdapterMethodHandle::argument(mh());
  1926   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1927   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1928   jint conv_op    = adapter_conversion_op(conversion);
  1930   // adjust the adapter code to the internal EntryKind enumeration:
  1931   EntryKind ek_orig = adapter_entry_kind(conv_op);
  1932   EntryKind ek_opt  = ek_orig;  // may be optimized
  1934   // Finalize the vmtarget field (Java initialized it to null).
  1935   if (!java_dyn_MethodHandle::is_instance(target())) {
  1936     throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
  1937     return;
  1939   sun_dyn_AdapterMethodHandle::set_vmtarget(mh(), target());
  1941   if (VerifyMethodHandles) {
  1942     verify_AdapterMethodHandle(mh, argnum, CHECK);
  1945   int stack_move = adapter_conversion_stack_move(conversion);
  1946   BasicType src  = adapter_conversion_src_type(conversion);
  1947   BasicType dest = adapter_conversion_dest_type(conversion);
  1948   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1950   const char* err = NULL;
  1952   // Now it's time to finish the case analysis and pick a MethodHandleEntry.
  1953   switch (ek_orig) {
  1954   case _adapter_retype_only:
  1955   case _adapter_retype_raw:
  1956   case _adapter_check_cast:
  1957   case _adapter_dup_args:
  1958   case _adapter_drop_args:
  1959     // these work fine via general case code
  1960     break;
  1962   case _adapter_prim_to_prim:
  1964       // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
  1965       // And, the {float,double} -> {int,long} cases must be handled by Java.
  1966       switch (type2size[src] *4+ type2size[dest]) {
  1967       case 1 *4+ 1:
  1968         assert(src == T_INT || is_subword_type(src), "source is not float");
  1969         // Subword-related cases are int -> {boolean,byte,char,short}.
  1970         ek_opt = _adapter_opt_i2i;
  1971         vminfo = adapter_subword_vminfo(dest);
  1972         break;
  1973       case 2 *4+ 1:
  1974         if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
  1975           ek_opt = _adapter_opt_l2i;
  1976           vminfo = adapter_subword_vminfo(dest);
  1977         } else if (src == T_DOUBLE && dest == T_FLOAT) {
  1978           ek_opt = _adapter_opt_d2f;
  1979         } else {
  1980           assert(false, "");
  1982         break;
  1983       case 1 *4+ 2:
  1984         if (src == T_INT && dest == T_LONG) {
  1985           ek_opt = _adapter_opt_i2l;
  1986         } else if (src == T_FLOAT && dest == T_DOUBLE) {
  1987           ek_opt = _adapter_opt_f2d;
  1988         } else {
  1989           assert(false, "");
  1991         break;
  1992       default:
  1993         assert(false, "");
  1994         break;
  1997     break;
  1999   case _adapter_ref_to_prim:
  2001       switch (type2size[dest]) {
  2002       case 1:
  2003         ek_opt = _adapter_opt_unboxi;
  2004         vminfo = adapter_subword_vminfo(dest);
  2005         break;
  2006       case 2:
  2007         ek_opt = _adapter_opt_unboxl;
  2008         break;
  2009       default:
  2010         assert(false, "");
  2011         break;
  2014     break;
  2016   case _adapter_prim_to_ref:
  2017     goto throw_not_impl;        // allocates, hence could block
  2019   case _adapter_swap_args:
  2020   case _adapter_rot_args:
  2022       int swap_slots = type2size[src];
  2023       int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(mh());
  2024       int src_slot   = argslot;
  2025       int dest_slot  = vminfo;
  2026       int rotate     = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
  2027       switch (swap_slots) {
  2028       case 1:
  2029         ek_opt = (!rotate    ? _adapter_opt_swap_1 :
  2030                   rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
  2031         break;
  2032       case 2:
  2033         ek_opt = (!rotate    ? _adapter_opt_swap_2 :
  2034                   rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
  2035         break;
  2036       default:
  2037         assert(false, "");
  2038         break;
  2041     break;
  2043   case _adapter_collect_args:
  2044     goto throw_not_impl;        // allocates, hence could block
  2046   case _adapter_spread_args:
  2048       // vminfo will be the required length of the array
  2049       int slots_pushed = stack_move / stack_move_unit();
  2050       int array_size   = slots_pushed + 1;
  2051       assert(array_size >= 0, "");
  2052       vminfo = array_size;
  2053       switch (array_size) {
  2054       case 0:   ek_opt = _adapter_opt_spread_0;       break;
  2055       case 1:   ek_opt = _adapter_opt_spread_1;       break;
  2056       default:  ek_opt = _adapter_opt_spread_more;    break;
  2058       if ((vminfo & CONV_VMINFO_MASK) != vminfo)
  2059         goto throw_not_impl;    // overflow
  2061     break;
  2063   case _adapter_flyby:
  2064   case _adapter_ricochet:
  2065     goto throw_not_impl;        // runs Java code, hence could block
  2067   default:
  2068     // should have failed much earlier; must be a missing case here
  2069     assert(false, "incomplete switch");
  2070     // and fall through:
  2072   throw_not_impl:
  2073     // FIXME: these adapters are NYI
  2074     err = "adapter not yet implemented in the JVM";
  2075     break;
  2078   if (err != NULL) {
  2079     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  2080     return;
  2083   // Rebuild the conversion value; maybe parts of it were changed.
  2084   jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
  2086   // Finalize the conversion field.  (Note that it is final to Java code.)
  2087   sun_dyn_AdapterMethodHandle::set_conversion(mh(), new_conversion);
  2089   // Done!
  2090   java_dyn_MethodHandle::set_vmentry(mh(), entry(ek_opt));
  2092   // There should be enough memory barriers on exit from native methods
  2093   // to ensure that the MH is fully initialized to all threads before
  2094   // Java code can publish it in global data structures.
  2097 //
  2098 // Here are the native methods on sun.dyn.MethodHandleImpl.
  2099 // They are the private interface between this JVM and the HotSpot-specific
  2100 // Java code that implements JSR 292 method handles.
  2101 //
  2102 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
  2103 // that intrinsic (non-JNI) native methods are defined in HotSpot.
  2104 //
  2106 // direct method handles for invokestatic or invokespecial
  2107 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
  2108 JVM_ENTRY(void, MHI_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2109                              jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
  2110   ResourceMark rm;              // for error messages
  2112   // This is the guy we are initializing:
  2113   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2114   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2116   // Early returns out of this method leave the DMH in an unfinished state.
  2117   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2119   // which method are we really talking about?
  2120   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2121   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2122   if (sun_dyn_MemberName::is_instance(target_oop) &&
  2123       sun_dyn_MemberName::vmindex(target_oop) == VM_INDEX_UNINITIALIZED) {
  2124     Handle mname(THREAD, target_oop);
  2125     MethodHandles::resolve_MemberName(mname, CHECK);
  2126     target_oop = mname(); // in case of GC
  2129   int decode_flags = 0; klassOop receiver_limit = NULL;
  2130   methodHandle m(THREAD,
  2131                  MethodHandles::decode_method(target_oop,
  2132                                               receiver_limit, decode_flags));
  2133   if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
  2135   // The trusted Java code that calls this method should already have performed
  2136   // access checks on behalf of the given caller.  But, we can verify this.
  2137   if (VerifyMethodHandles && caller_jh != NULL) {
  2138     KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
  2139     // If this were a bytecode, the first access check would be against
  2140     // the "reference class" mentioned in the CONSTANT_Methodref.
  2141     // We don't know at this point which class that was, and if we
  2142     // check against m.method_holder we might get the wrong answer.
  2143     // So we just make sure to handle this check when the resolution
  2144     // happens, when we call resolve_MemberName.
  2145     //
  2146     // (A public class can inherit public members from private supers,
  2147     // and it would be wrong to check access against the private super
  2148     // if the original symbolic reference was against the public class.)
  2149     //
  2150     // If there were a bytecode, the next step would be to lookup the method
  2151     // in the reference class, then then check the method's access bits.
  2152     // Emulate LinkResolver::check_method_accessability.
  2153     klassOop resolved_klass = m->method_holder();
  2154     if (!Reflection::verify_field_access(caller->as_klassOop(),
  2155                                          resolved_klass, resolved_klass,
  2156                                          m->access_flags(),
  2157                                          true)) {
  2158       // %%% following cutout belongs in Reflection::verify_field_access?
  2159       bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
  2160                                                         resolved_klass, THREAD);
  2161       if (!same_pm) {
  2162         THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
  2167   MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
  2169 JVM_END
  2171 // bound method handles
  2172 JVM_ENTRY(void, MHI_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2173                              jobject target_jh, int argnum)) {
  2174   ResourceMark rm;              // for error messages
  2176   // This is the guy we are initializing:
  2177   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2178   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2180   // Early returns out of this method leave the BMH in an unfinished state.
  2181   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2183   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2184   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2186   if (!java_dyn_MethodHandle::is_instance(target())) {
  2187     // Target object is a reflective method.  (%%% Do we need this alternate path?)
  2188     Untested("init_BMH of non-MH");
  2189     if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
  2190     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  2191     methodHandle m(THREAD,
  2192                    MethodHandles::decode_method(target(),
  2193                                                 receiver_limit_oop,
  2194                                                 decode_flags));
  2195     KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  2196     MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
  2197                                                        receiver_limit,
  2198                                                        decode_flags,
  2199                                                        CHECK);
  2200     return;
  2203   // Build a BMH on top of a DMH or another BMH:
  2204   MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
  2206 JVM_END
  2208 // adapter method handles
  2209 JVM_ENTRY(void, MHI_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2210                              jobject target_jh, int argnum)) {
  2211   // This is the guy we are initializing:
  2212   if (mh_jh == NULL || target_jh == NULL) {
  2213     THROW(vmSymbols::java_lang_InternalError());
  2215   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2216   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2218   // Early returns out of this method leave the AMH in an unfinished state.
  2219   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2221   MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
  2223 JVM_END
  2225 // method type forms
  2226 JVM_ENTRY(void, MHI_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
  2227   if (erased_jh == NULL)  return;
  2228   if (TraceMethodHandles) {
  2229     tty->print("creating MethodType form ");
  2230     if (WizardMode || Verbose) {   // Warning: this calls Java code on the MH!
  2231       // call Object.toString()
  2232       symbolOop name = vmSymbols::toString_name(), sig = vmSymbols::void_string_signature();
  2233       JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
  2234       JavaValue result(T_OBJECT);
  2235       JavaCalls::call_virtual(&result, SystemDictionary::Object_klass(), name, sig,
  2236                               &args, CHECK);
  2237       Handle str(THREAD, (oop)result.get_jobject());
  2238       java_lang_String::print(str, tty);
  2240     tty->cr();
  2243 JVM_END
  2245 // debugging and reflection
  2246 JVM_ENTRY(jobject, MHI_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
  2247   Handle mh(THREAD, JNIHandles::resolve(mh_jh));
  2248   if (!java_dyn_MethodHandle::is_instance(mh())) {
  2249     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
  2251   oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
  2252   return JNIHandles::make_local(THREAD, target);
  2254 JVM_END
  2256 JVM_ENTRY(jint, MHI_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  2257   switch (which) {
  2258   case MethodHandles::GC_JVM_PUSH_LIMIT:
  2259     guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
  2260               "MethodHandlePushLimit parameter must be in valid range");
  2261     return MethodHandlePushLimit;
  2262   case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
  2263     // return number of words per slot, signed according to stack direction
  2264     return MethodHandles::stack_move_unit();
  2265   case MethodHandles::GC_CONV_OP_IMPLEMENTED_MASK:
  2266     return MethodHandles::adapter_conversion_ops_supported_mask();
  2268   return 0;
  2270 JVM_END
  2272 #ifndef PRODUCT
  2273 #define EACH_NAMED_CON(template) \
  2274     template(MethodHandles,GC_JVM_PUSH_LIMIT) \
  2275     template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) \
  2276     template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
  2277     template(MethodHandles,ETF_DIRECT_HANDLE) \
  2278     template(MethodHandles,ETF_METHOD_NAME) \
  2279     template(MethodHandles,ETF_REFLECT_METHOD) \
  2280     template(sun_dyn_MemberName,MN_IS_METHOD) \
  2281     template(sun_dyn_MemberName,MN_IS_CONSTRUCTOR) \
  2282     template(sun_dyn_MemberName,MN_IS_FIELD) \
  2283     template(sun_dyn_MemberName,MN_IS_TYPE) \
  2284     template(sun_dyn_MemberName,MN_SEARCH_SUPERCLASSES) \
  2285     template(sun_dyn_MemberName,MN_SEARCH_INTERFACES) \
  2286     template(sun_dyn_MemberName,VM_INDEX_UNINITIALIZED) \
  2287     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_ONLY) \
  2288     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_RAW) \
  2289     template(sun_dyn_AdapterMethodHandle,OP_CHECK_CAST) \
  2290     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
  2291     template(sun_dyn_AdapterMethodHandle,OP_REF_TO_PRIM) \
  2292     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_REF) \
  2293     template(sun_dyn_AdapterMethodHandle,OP_SWAP_ARGS) \
  2294     template(sun_dyn_AdapterMethodHandle,OP_ROT_ARGS) \
  2295     template(sun_dyn_AdapterMethodHandle,OP_DUP_ARGS) \
  2296     template(sun_dyn_AdapterMethodHandle,OP_DROP_ARGS) \
  2297     template(sun_dyn_AdapterMethodHandle,OP_COLLECT_ARGS) \
  2298     template(sun_dyn_AdapterMethodHandle,OP_SPREAD_ARGS) \
  2299     template(sun_dyn_AdapterMethodHandle,OP_FLYBY) \
  2300     template(sun_dyn_AdapterMethodHandle,OP_RICOCHET) \
  2301     template(sun_dyn_AdapterMethodHandle,CONV_OP_LIMIT) \
  2302     template(sun_dyn_AdapterMethodHandle,CONV_OP_MASK) \
  2303     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_MASK) \
  2304     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
  2305     template(sun_dyn_AdapterMethodHandle,CONV_OP_SHIFT) \
  2306     template(sun_dyn_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
  2307     template(sun_dyn_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
  2308     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
  2309     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
  2310     /*end*/
  2312 #define ONE_PLUS(scope,value) 1+
  2313 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
  2314 #define VALUE_COMMA(scope,value) scope::value,
  2315 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
  2316 #define STRING_NULL(scope,value) #value "\0"
  2317 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
  2319 #undef ONE_PLUS
  2320 #undef VALUE_COMMA
  2321 #undef STRING_NULL
  2322 #undef EACH_NAMED_CON
  2323 #endif
  2325 JVM_ENTRY(jint, MHI_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
  2326 #ifndef PRODUCT
  2327   if (which >= 0 && which < con_value_count) {
  2328     int con = con_values[which];
  2329     objArrayOop box = (objArrayOop) JNIHandles::resolve(box_jh);
  2330     if (box != NULL && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
  2331       const char* str = &con_names[0];
  2332       for (int i = 0; i < which; i++)
  2333         str += strlen(str) + 1;   // skip name and null
  2334       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);
  2335       box->obj_at_put(0, name);
  2337     return con;
  2339 #endif
  2340   return 0;
  2342 JVM_END
  2344 // void init(MemberName self, AccessibleObject ref)
  2345 JVM_ENTRY(void, MHI_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
  2346   if (mname_jh == NULL || target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2347   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2348   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2349   MethodHandles::init_MemberName(mname(), target_oop);
  2351 JVM_END
  2353 // void expand(MemberName self)
  2354 JVM_ENTRY(void, MHI_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  2355   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2356   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2357   MethodHandles::expand_MemberName(mname, 0, CHECK);
  2359 JVM_END
  2361 // void resolve(MemberName self, Class<?> caller)
  2362 JVM_ENTRY(void, MHI_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  2363   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2364   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2366   // The trusted Java code that calls this method should already have performed
  2367   // access checks on behalf of the given caller.  But, we can verify this.
  2368   if (VerifyMethodHandles && caller_jh != NULL) {
  2369     klassOop reference_klass = java_lang_Class::as_klassOop(sun_dyn_MemberName::clazz(mname()));
  2370     if (reference_klass != NULL) {
  2371       // Emulate LinkResolver::check_klass_accessability.
  2372       klassOop caller = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh));
  2373       if (!Reflection::verify_class_access(caller,
  2374                                            reference_klass,
  2375                                            true)) {
  2376         THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(reference_klass)->external_name());
  2381   MethodHandles::resolve_MemberName(mname, CHECK);
  2383 JVM_END
  2385 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2386 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2387 JVM_ENTRY(jint, MHI_getMembers(JNIEnv *env, jobject igcls,
  2388                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
  2389                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  2390   if (clazz_jh == NULL || results_jh == NULL)  return -1;
  2391   klassOop k_oop = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh));
  2393   objArrayOop results = (objArrayOop) JNIHandles::resolve(results_jh);
  2394   if (results == NULL || !results->is_objArray())       return -1;
  2396   symbolOop name = NULL, sig = NULL;
  2397   if (name_jh != NULL) {
  2398     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
  2399     if (name == NULL)  return 0; // a match is not possible
  2401   if (sig_jh != NULL) {
  2402     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
  2403     if (sig == NULL)  return 0; // a match is not possible
  2406   klassOop caller = NULL;
  2407   if (caller_jh != NULL) {
  2408     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
  2409     if (!java_lang_Class::is_instance(caller_oop))  return -1;
  2410     caller = java_lang_Class::as_klassOop(caller_oop);
  2413   if (name != NULL && sig != NULL && results != NULL) {
  2414     // try a direct resolve
  2415     // %%% TO DO
  2418   int res = MethodHandles::find_MemberNames(k_oop, name, sig, mflags,
  2419                                             caller, skip, results);
  2420   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  2421   return res;
  2423 JVM_END
  2425 JVM_ENTRY(void, MHI_registerBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh, jobject bsm_jh)) {
  2426   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2427   ik->link_class(CHECK);
  2428   if (!java_dyn_MethodHandle::is_instance(JNIHandles::resolve(bsm_jh))) {
  2429     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "method handle");
  2431   const char* err = NULL;
  2432   if (ik->is_initialized() || ik->is_in_error_state()) {
  2433     err = "too late: class is already initialized";
  2434   } else {
  2435     ObjectLocker ol(ik, THREAD);  // note:  this should be a recursive lock
  2436     if (ik->is_not_initialized() ||
  2437         (ik->is_being_initialized() && ik->is_reentrant_initialization(THREAD))) {
  2438       if (ik->bootstrap_method() != NULL) {
  2439         err = "class is already equipped with a bootstrap method";
  2440       } else {
  2441         ik->set_bootstrap_method(JNIHandles::resolve_non_null(bsm_jh));
  2442         err = NULL;
  2444     } else {
  2445       err = "class is already initialized";
  2446       if (ik->is_being_initialized())
  2447         err = "class is already being initialized in a different thread";
  2450   if (err != NULL) {
  2451     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), err);
  2454 JVM_END
  2456 JVM_ENTRY(jobject, MHI_getBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh)) {
  2457   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2458   return JNIHandles::make_local(THREAD, ik->bootstrap_method());
  2460 JVM_END
  2462 JVM_ENTRY(void, MHI_setCallSiteTarget(JNIEnv *env, jobject igcls, jobject site_jh, jobject target_jh)) {
  2463   // No special action required, yet.
  2464   oop site_oop = JNIHandles::resolve(site_jh);
  2465   if (!java_dyn_CallSite::is_instance(site_oop))
  2466     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "not a CallSite");
  2467   java_dyn_CallSite::set_target(site_oop, JNIHandles::resolve(target_jh));
  2469 JVM_END
  2472 /// JVM_RegisterMethodHandleMethods
  2474 #define ADR "J"
  2476 #define LANG "Ljava/lang/"
  2477 #define JDYN "Ljava/dyn/"
  2478 #define IDYN "Lsun/dyn/"
  2480 #define OBJ   LANG"Object;"
  2481 #define CLS   LANG"Class;"
  2482 #define STRG  LANG"String;"
  2483 #define CST   JDYN"CallSite;"
  2484 #define MT    JDYN"MethodType;"
  2485 #define MH    JDYN"MethodHandle;"
  2486 #define MHI   IDYN"MethodHandleImpl;"
  2487 #define MEM   IDYN"MemberName;"
  2488 #define AMH   IDYN"AdapterMethodHandle;"
  2489 #define BMH   IDYN"BoundMethodHandle;"
  2490 #define DMH   IDYN"DirectMethodHandle;"
  2492 #define CC (char*)  /*cast a literal from (const char*)*/
  2493 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
  2495 // These are the native methods on sun.dyn.MethodHandleNatives.
  2496 static JNINativeMethod methods[] = {
  2497   // void init(MemberName self, AccessibleObject ref)
  2498   {CC"init",                    CC"("AMH""MH"I)V",              FN_PTR(MHI_init_AMH)},
  2499   {CC"init",                    CC"("BMH""OBJ"I)V",             FN_PTR(MHI_init_BMH)},
  2500   {CC"init",                    CC"("DMH""OBJ"Z"CLS")V",        FN_PTR(MHI_init_DMH)},
  2501   {CC"init",                    CC"("MT")V",                    FN_PTR(MHI_init_MT)},
  2502   {CC"init",                    CC"("MEM""OBJ")V",              FN_PTR(MHI_init_Mem)},
  2503   {CC"expand",                  CC"("MEM")V",                   FN_PTR(MHI_expand_Mem)},
  2504   {CC"resolve",                 CC"("MEM""CLS")V",              FN_PTR(MHI_resolve_Mem)},
  2505   {CC"getTarget",               CC"("MH"I)"OBJ,                 FN_PTR(MHI_getTarget)},
  2506   {CC"getConstant",             CC"(I)I",                       FN_PTR(MHI_getConstant)},
  2507   //  static native int getNamedCon(int which, Object[] name)
  2508   {CC"getNamedCon",             CC"(I["OBJ")I",                 FN_PTR(MHI_getNamedCon)},
  2509   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2510   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2511   {CC"getMembers",              CC"("CLS""STRG""STRG"I"CLS"I["MEM")I",  FN_PTR(MHI_getMembers)}
  2512 };
  2514 // More entry points specifically for EnableInvokeDynamic.
  2515 static JNINativeMethod methods2[] = {
  2516   {CC"registerBootstrap",       CC"("CLS MH")V",                FN_PTR(MHI_registerBootstrap)},
  2517   {CC"getBootstrap",            CC"("CLS")"MH,                  FN_PTR(MHI_getBootstrap)},
  2518   {CC"setCallSiteTarget",       CC"("CST MH")V",                FN_PTR(MHI_setCallSiteTarget)}
  2519 };
  2522 // This one function is exported, used by NativeLookup.
  2524 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
  2525   assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
  2527   // note: this explicit warning-producing stuff will be replaced by auto-detection of the JSR 292 classes
  2529   if (!EnableMethodHandles) {
  2530     warning("JSR 292 method handles are disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles to enable.");
  2531     return;  // bind nothing
  2534   bool enable_MH = true;
  2537     ThreadToNativeFromVM ttnfv(thread);
  2539     int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
  2540     if (env->ExceptionOccurred()) {
  2541       MethodHandles::set_enabled(false);
  2542       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2543       enable_MH = false;
  2544       env->ExceptionClear();
  2548   if (enable_MH) {
  2549     KlassHandle MHI_klass = SystemDictionaryHandles::MethodHandleImpl_klass();
  2550     if (MHI_klass.not_null()) {
  2551       symbolHandle raiseException_name = oopFactory::new_symbol_handle("raiseException", CHECK);
  2552       symbolHandle raiseException_sig  = oopFactory::new_symbol_handle("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK);
  2553       methodOop raiseException_method  = instanceKlass::cast(MHI_klass->as_klassOop())
  2554                     ->find_method(raiseException_name(), raiseException_sig());
  2555       if (raiseException_method != NULL && raiseException_method->is_static()) {
  2556         MethodHandles::set_raise_exception_method(raiseException_method);
  2557       } else {
  2558         warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2559         enable_MH = false;
  2564   if (enable_MH) {
  2565     MethodHandles::set_enabled(true);
  2568   if (!EnableInvokeDynamic) {
  2569     warning("JSR 292 invokedynamic is disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic to enable.");
  2570     return;  // bind nothing
  2574     ThreadToNativeFromVM ttnfv(thread);
  2576     int status = env->RegisterNatives(MHN_class, methods2, sizeof(methods2)/sizeof(JNINativeMethod));
  2577     if (env->ExceptionOccurred()) {
  2578       MethodHandles::set_enabled(false);
  2579       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2580       env->ExceptionClear();
  2581     } else {
  2582       MethodHandles::set_enabled(true);
  2586 JVM_END

mercurial