src/share/vm/prims/methodHandles.cpp

Wed, 25 Aug 2010 05:27:54 -0700

author
twisti
date
Wed, 25 Aug 2010 05:27:54 -0700
changeset 2103
3e8fbc61cee8
parent 2015
083fde3b838e
child 2204
5beba6174298
permissions
-rw-r--r--

6978355: renaming for 6961697
Summary: This is the renaming part of 6961697 to keep the actual changes small for review.
Reviewed-by: kvn, never

     1 /*
     2  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 /*
    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);
   117   MethodHandlesAdapterGenerator g(&code);
   118   g.generate();
   119 }
   122 //------------------------------------------------------------------------------
   123 // MethodHandlesAdapterGenerator::generate
   124 //
   125 void MethodHandlesAdapterGenerator::generate() {
   126   // Generate generic method handle adapters.
   127   for (MethodHandles::EntryKind ek = MethodHandles::_EK_FIRST;
   128        ek < MethodHandles::_EK_LIMIT;
   129        ek = MethodHandles::EntryKind(1 + (int)ek)) {
   130     StubCodeMark mark(this, "MethodHandle", MethodHandles::entry_name(ek));
   131     MethodHandles::generate_method_handle_stub(_masm, ek);
   132   }
   133 }
   136 void MethodHandles::set_enabled(bool z) {
   137   if (_enabled != z) {
   138     guarantee(z && EnableMethodHandles, "can only enable once, and only if -XX:+EnableMethodHandles");
   139     _enabled = z;
   140   }
   141 }
   143 // Note: A method which does not have a TRAPS argument cannot block in the GC
   144 // or throw exceptions.  Such methods are used in this file to do something quick
   145 // and local, like parse a data structure.  For speed, such methods work on plain
   146 // oops, not handles.  Trapping methods uniformly operate on handles.
   148 methodOop MethodHandles::decode_vmtarget(oop vmtarget, int vmindex, oop mtype,
   149                                          klassOop& receiver_limit_result, int& decode_flags_result) {
   150   if (vmtarget == NULL)  return NULL;
   151   assert(methodOopDesc::nonvirtual_vtable_index < 0, "encoding");
   152   if (vmindex < 0) {
   153     // this DMH performs no dispatch; it is directly bound to a methodOop
   154     // A MemberName may either be directly bound to a methodOop,
   155     // or it may use the klass/index form; both forms mean the same thing.
   156     methodOop m = decode_methodOop(methodOop(vmtarget), decode_flags_result);
   157     if ((decode_flags_result & _dmf_has_receiver) != 0
   158         && java_dyn_MethodType::is_instance(mtype)) {
   159       // Extract receiver type restriction from mtype.ptypes[0].
   160       objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype);
   161       oop ptype0 = (ptypes == NULL || ptypes->length() < 1) ? oop(NULL) : ptypes->obj_at(0);
   162       if (java_lang_Class::is_instance(ptype0))
   163         receiver_limit_result = java_lang_Class::as_klassOop(ptype0);
   164     }
   165     if (vmindex == methodOopDesc::nonvirtual_vtable_index) {
   166       // this DMH can be an "invokespecial" version
   167       decode_flags_result &= ~_dmf_does_dispatch;
   168     } else {
   169       assert(vmindex == methodOopDesc::invalid_vtable_index, "random vmindex?");
   170     }
   171     return m;
   172   } else {
   173     assert(vmtarget->is_klass(), "must be class or interface");
   174     decode_flags_result |= MethodHandles::_dmf_does_dispatch;
   175     decode_flags_result |= MethodHandles::_dmf_has_receiver;
   176     receiver_limit_result = (klassOop)vmtarget;
   177     Klass* tk = Klass::cast((klassOop)vmtarget);
   178     if (tk->is_interface()) {
   179       // an itable linkage is <interface, itable index>
   180       decode_flags_result |= MethodHandles::_dmf_from_interface;
   181       return klassItable::method_for_itable_index((klassOop)vmtarget, vmindex);
   182     } else {
   183       if (!tk->oop_is_instance())
   184         tk = instanceKlass::cast(SystemDictionary::Object_klass());
   185       return ((instanceKlass*)tk)->method_at_vtable(vmindex);
   186     }
   187   }
   188 }
   190 // MemberName and DirectMethodHandle have the same linkage to the JVM internals.
   191 // (MemberName is the non-operational name used for queries and setup.)
   193 methodOop MethodHandles::decode_DirectMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   194   oop vmtarget = sun_dyn_DirectMethodHandle::vmtarget(mh);
   195   int vmindex  = sun_dyn_DirectMethodHandle::vmindex(mh);
   196   oop mtype    = sun_dyn_DirectMethodHandle::type(mh);
   197   return decode_vmtarget(vmtarget, vmindex, mtype, receiver_limit_result, decode_flags_result);
   198 }
   200 methodOop MethodHandles::decode_BoundMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   201   assert(sun_dyn_BoundMethodHandle::is_instance(mh), "");
   202   assert(mh->klass() != SystemDictionary::AdapterMethodHandle_klass(), "");
   203   for (oop bmh = mh;;) {
   204     // Bound MHs can be stacked to bind several arguments.
   205     oop target = java_dyn_MethodHandle::vmtarget(bmh);
   206     if (target == NULL)  return NULL;
   207     decode_flags_result |= MethodHandles::_dmf_binds_argument;
   208     klassOop tk = target->klass();
   209     if (tk == SystemDictionary::BoundMethodHandle_klass()) {
   210       bmh = target;
   211       continue;
   212     } else {
   213       if (java_dyn_MethodHandle::is_subclass(tk)) {
   214         //assert(tk == SystemDictionary::DirectMethodHandle_klass(), "end of BMH chain must be DMH");
   215         return decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   216       } else {
   217         // Optimized case:  binding a receiver to a non-dispatched DMH
   218         // short-circuits directly to the methodOop.
   219         // (It might be another argument besides a receiver also.)
   220         assert(target->is_method(), "must be a simple method");
   221         decode_flags_result |= MethodHandles::_dmf_binds_method;
   222         methodOop m = (methodOop) target;
   223         if (!m->is_static())
   224           decode_flags_result |= MethodHandles::_dmf_has_receiver;
   225         return m;
   226       }
   227     }
   228   }
   229 }
   231 methodOop MethodHandles::decode_AdapterMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   232   assert(mh->klass() == SystemDictionary::AdapterMethodHandle_klass(), "");
   233   for (oop amh = mh;;) {
   234     // Adapter MHs can be stacked to convert several arguments.
   235     int conv_op = adapter_conversion_op(sun_dyn_AdapterMethodHandle::conversion(amh));
   236     decode_flags_result |= (_dmf_adapter_lsb << conv_op) & _DMF_ADAPTER_MASK;
   237     oop target = java_dyn_MethodHandle::vmtarget(amh);
   238     if (target == NULL)  return NULL;
   239     klassOop tk = target->klass();
   240     if (tk == SystemDictionary::AdapterMethodHandle_klass()) {
   241       amh = target;
   242       continue;
   243     } else {
   244       // must be a BMH (which will bind some more arguments) or a DMH (for the final call)
   245       return MethodHandles::decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   246     }
   247   }
   248 }
   250 methodOop MethodHandles::decode_MethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   251   if (mh == NULL)  return NULL;
   252   klassOop mhk = mh->klass();
   253   assert(java_dyn_MethodHandle::is_subclass(mhk), "must be a MethodHandle");
   254   if (mhk == SystemDictionary::DirectMethodHandle_klass()) {
   255     return decode_DirectMethodHandle(mh, receiver_limit_result, decode_flags_result);
   256   } else if (mhk == SystemDictionary::BoundMethodHandle_klass()) {
   257     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   258   } else if (mhk == SystemDictionary::AdapterMethodHandle_klass()) {
   259     return decode_AdapterMethodHandle(mh, receiver_limit_result, decode_flags_result);
   260   } else if (sun_dyn_BoundMethodHandle::is_subclass(mhk)) {
   261     // could be a JavaMethodHandle (but not an adapter MH)
   262     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   263   } else {
   264     assert(false, "cannot parse this MH");
   265     return NULL;              // random MH?
   266   }
   267 }
   269 methodOop MethodHandles::decode_methodOop(methodOop m, int& decode_flags_result) {
   270   assert(m->is_method(), "");
   271   if (m->is_static()) {
   272     // check that signature begins '(L' or '([' (not '(I', '()', etc.)
   273     symbolOop sig = m->signature();
   274     BasicType recv_bt = char2type(sig->byte_at(1));
   275     // Note: recv_bt might be T_ILLEGAL if byte_at(2) is ')'
   276     assert(sig->byte_at(0) == '(', "must be method sig");
   277 //     if (recv_bt == T_OBJECT || recv_bt == T_ARRAY)
   278 //       decode_flags_result |= _dmf_has_receiver;
   279   } else {
   280     // non-static method
   281     decode_flags_result |= _dmf_has_receiver;
   282     if (!m->can_be_statically_bound() && !m->is_initializer()) {
   283       decode_flags_result |= _dmf_does_dispatch;
   284       if (Klass::cast(m->method_holder())->is_interface())
   285         decode_flags_result |= _dmf_from_interface;
   286     }
   287   }
   288   return m;
   289 }
   292 // A trusted party is handing us a cookie to determine a method.
   293 // Let's boil it down to the method oop they really want.
   294 methodOop MethodHandles::decode_method(oop x, klassOop& receiver_limit_result, int& decode_flags_result) {
   295   decode_flags_result = 0;
   296   receiver_limit_result = NULL;
   297   klassOop xk = x->klass();
   298   if (xk == Universe::methodKlassObj()) {
   299     return decode_methodOop((methodOop) x, decode_flags_result);
   300   } else if (xk == SystemDictionary::MemberName_klass()) {
   301     // Note: This only works if the MemberName has already been resolved.
   302     return decode_MemberName(x, receiver_limit_result, decode_flags_result);
   303   } else if (java_dyn_MethodHandle::is_subclass(xk)) {
   304     return decode_MethodHandle(x, receiver_limit_result, decode_flags_result);
   305   } else if (xk == SystemDictionary::reflect_Method_klass()) {
   306     oop clazz  = java_lang_reflect_Method::clazz(x);
   307     int slot   = java_lang_reflect_Method::slot(x);
   308     klassOop k = java_lang_Class::as_klassOop(clazz);
   309     if (k != NULL && Klass::cast(k)->oop_is_instance())
   310       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   311                               decode_flags_result);
   312   } else if (xk == SystemDictionary::reflect_Constructor_klass()) {
   313     oop clazz  = java_lang_reflect_Constructor::clazz(x);
   314     int slot   = java_lang_reflect_Constructor::slot(x);
   315     klassOop k = java_lang_Class::as_klassOop(clazz);
   316     if (k != NULL && Klass::cast(k)->oop_is_instance())
   317       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   318                               decode_flags_result);
   319   } else {
   320     // unrecognized object
   321     assert(!x->is_method(), "already checked");
   322     assert(!sun_dyn_MemberName::is_instance(x), "already checked");
   323   }
   324   return NULL;
   325 }
   328 int MethodHandles::decode_MethodHandle_stack_pushes(oop mh) {
   329   if (mh->klass() == SystemDictionary::DirectMethodHandle_klass())
   330     return 0;                   // no push/pop
   331   int this_vmslots = java_dyn_MethodHandle::vmslots(mh);
   332   int last_vmslots = 0;
   333   oop last_mh = mh;
   334   for (;;) {
   335     oop target = java_dyn_MethodHandle::vmtarget(last_mh);
   336     if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   337       last_vmslots = java_dyn_MethodHandle::vmslots(target);
   338       break;
   339     } else if (!java_dyn_MethodHandle::is_instance(target)) {
   340       // might be klass or method
   341       assert(target->is_method(), "must get here with a direct ref to method");
   342       last_vmslots = methodOop(target)->size_of_parameters();
   343       break;
   344     }
   345     last_mh = target;
   346   }
   347   // If I am called with fewer VM slots than my ultimate callee,
   348   // it must be that I push the additionally needed slots.
   349   // Likewise if am called with more VM slots, I will pop them.
   350   return (last_vmslots - this_vmslots);
   351 }
   354 // MemberName support
   356 // import sun_dyn_MemberName.*
   357 enum {
   358   IS_METHOD      = sun_dyn_MemberName::MN_IS_METHOD,
   359   IS_CONSTRUCTOR = sun_dyn_MemberName::MN_IS_CONSTRUCTOR,
   360   IS_FIELD       = sun_dyn_MemberName::MN_IS_FIELD,
   361   IS_TYPE        = sun_dyn_MemberName::MN_IS_TYPE,
   362   SEARCH_SUPERCLASSES = sun_dyn_MemberName::MN_SEARCH_SUPERCLASSES,
   363   SEARCH_INTERFACES   = sun_dyn_MemberName::MN_SEARCH_INTERFACES,
   364   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE,
   365   VM_INDEX_UNINITIALIZED = sun_dyn_MemberName::VM_INDEX_UNINITIALIZED
   366 };
   368 Handle MethodHandles::new_MemberName(TRAPS) {
   369   Handle empty;
   370   instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
   371   if (!k->is_initialized())  k->initialize(CHECK_(empty));
   372   return Handle(THREAD, k->allocate_instance(THREAD));
   373 }
   375 void MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
   376   if (target_oop->klass() == SystemDictionary::reflect_Field_klass()) {
   377     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
   378     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
   379     int mods  = java_lang_reflect_Field::modifiers(target_oop);
   380     klassOop k = java_lang_Class::as_klassOop(clazz);
   381     int offset = instanceKlass::cast(k)->offset_from_fields(slot);
   382     init_MemberName(mname_oop, k, accessFlags_from(mods), offset);
   383   } else {
   384     int decode_flags = 0; klassOop receiver_limit = NULL;
   385     methodOop m = MethodHandles::decode_method(target_oop,
   386                                                receiver_limit, decode_flags);
   387     bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   388     init_MemberName(mname_oop, m, do_dispatch);
   389   }
   390 }
   392 void MethodHandles::init_MemberName(oop mname_oop, methodOop m, bool do_dispatch) {
   393   int flags = ((m->is_initializer() ? IS_CONSTRUCTOR : IS_METHOD)
   394                | (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS ));
   395   oop vmtarget = m;
   396   int vmindex  = methodOopDesc::invalid_vtable_index;  // implies no info yet
   397   if (!do_dispatch || (flags & IS_CONSTRUCTOR) || m->can_be_statically_bound())
   398     vmindex = methodOopDesc::nonvirtual_vtable_index; // implies never any dispatch
   399   assert(vmindex != VM_INDEX_UNINITIALIZED, "Java sentinel value");
   400   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   401   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   402   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   403   sun_dyn_MemberName::set_clazz(mname_oop,    Klass::cast(m->method_holder())->java_mirror());
   404 }
   406 void MethodHandles::init_MemberName(oop mname_oop, klassOop field_holder, AccessFlags mods, int offset) {
   407   int flags = (IS_FIELD | (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS ));
   408   oop vmtarget = field_holder;
   409   int vmindex  = offset;  // determines the field uniquely when combined with static bit
   410   assert(vmindex != VM_INDEX_UNINITIALIZED, "bad alias on vmindex");
   411   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   412   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   413   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   414   sun_dyn_MemberName::set_clazz(mname_oop,    Klass::cast(field_holder)->java_mirror());
   415 }
   418 methodOop MethodHandles::decode_MemberName(oop mname, klassOop& receiver_limit_result, int& decode_flags_result) {
   419   int flags  = sun_dyn_MemberName::flags(mname);
   420   if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) == 0)  return NULL;  // not invocable
   421   oop vmtarget = sun_dyn_MemberName::vmtarget(mname);
   422   int vmindex  = sun_dyn_MemberName::vmindex(mname);
   423   if (vmindex == VM_INDEX_UNINITIALIZED)  return NULL; // not resolved
   424   methodOop m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit_result, decode_flags_result);
   425   oop clazz = sun_dyn_MemberName::clazz(mname);
   426   if (clazz != NULL && java_lang_Class::is_instance(clazz)) {
   427     klassOop klass = java_lang_Class::as_klassOop(clazz);
   428     if (klass != NULL)  receiver_limit_result = klass;
   429   }
   430   return m;
   431 }
   433 // An unresolved member name is a mere symbolic reference.
   434 // Resolving it plants a vmtarget/vmindex in it,
   435 // which refers dirctly to JVM internals.
   436 void MethodHandles::resolve_MemberName(Handle mname, TRAPS) {
   437   assert(sun_dyn_MemberName::is_instance(mname()), "");
   438 #ifdef ASSERT
   439   // If this assert throws, renegotiate the sentinel value used by the Java code,
   440   // so that it is distinct from any valid vtable index value, and any special
   441   // values defined in methodOopDesc::VtableIndexFlag.
   442   // The point of the slop is to give the Java code and the JVM some room
   443   // to independently specify sentinel values.
   444   const int sentinel_slop  = 10;
   445   const int sentinel_limit = methodOopDesc::highest_unused_vtable_index_value - sentinel_slop;
   446   assert(VM_INDEX_UNINITIALIZED < sentinel_limit, "Java sentinel != JVM sentinels");
   447 #endif
   448   if (sun_dyn_MemberName::vmindex(mname()) != VM_INDEX_UNINITIALIZED)
   449     return;  // already resolved
   450   oop defc_oop = sun_dyn_MemberName::clazz(mname());
   451   oop name_str = sun_dyn_MemberName::name(mname());
   452   oop type_str = sun_dyn_MemberName::type(mname());
   453   int flags    = sun_dyn_MemberName::flags(mname());
   455   if (defc_oop == NULL || name_str == NULL || type_str == NULL) {
   456     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve");
   457   }
   458   klassOop defc_klassOop = java_lang_Class::as_klassOop(defc_oop);
   459   defc_oop = NULL;  // safety
   460   if (defc_klassOop == NULL)  return;  // a primitive; no resolution possible
   461   if (!Klass::cast(defc_klassOop)->oop_is_instance()) {
   462     if (!Klass::cast(defc_klassOop)->oop_is_array())  return;
   463     defc_klassOop = SystemDictionary::Object_klass();
   464   }
   465   instanceKlassHandle defc(THREAD, defc_klassOop);
   466   defc_klassOop = NULL;  // safety
   467   if (defc.is_null()) {
   468     THROW_MSG(vmSymbols::java_lang_InternalError(), "primitive class");
   469   }
   470   defc->link_class(CHECK);
   472   // convert the external string name to an internal symbol
   473   symbolHandle name(THREAD, java_lang_String::as_symbol_or_null(name_str));
   474   if (name.is_null())  return;  // no such name
   475   name_str = NULL;  // safety
   477   Handle polymorphic_method_type;
   478   bool polymorphic_signature = false;
   479   if ((flags & ALL_KINDS) == IS_METHOD &&
   480       (defc() == SystemDictionary::InvokeDynamic_klass() ||
   481        (defc() == SystemDictionary::MethodHandle_klass() &&
   482         methodOopDesc::is_method_handle_invoke_name(name()))))
   483     polymorphic_signature = true;
   485   // convert the external string or reflective type to an internal signature
   486   symbolHandle type; {
   487     symbolOop type_sym = NULL;
   488     if (java_dyn_MethodType::is_instance(type_str)) {
   489       type_sym = java_dyn_MethodType::as_signature(type_str, polymorphic_signature, CHECK);
   490       if (polymorphic_signature)
   491         polymorphic_method_type = Handle(THREAD, type_str);  //preserve exactly
   492     } else if (java_lang_Class::is_instance(type_str)) {
   493       type_sym = java_lang_Class::as_signature(type_str, false, CHECK);
   494     } else if (java_lang_String::is_instance(type_str)) {
   495       if (polymorphic_signature) {
   496         type     = java_lang_String::as_symbol(type_str, CHECK);
   497       } else {
   498         type_sym = java_lang_String::as_symbol_or_null(type_str);
   499       }
   500     } else {
   501       THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized type");
   502     }
   503     if (type_sym != NULL)
   504       type = symbolHandle(THREAD, type_sym);
   505   }
   506   if (type.is_null())  return;  // no such signature exists in the VM
   507   type_str = NULL; // safety
   509   // Time to do the lookup.
   510   switch (flags & ALL_KINDS) {
   511   case IS_METHOD:
   512     {
   513       CallInfo result;
   514       {
   515         EXCEPTION_MARK;
   516         if ((flags & JVM_ACC_STATIC) != 0) {
   517           LinkResolver::resolve_static_call(result,
   518                         defc, name, type, KlassHandle(), false, false, THREAD);
   519         } else if (defc->is_interface()) {
   520           LinkResolver::resolve_interface_call(result, Handle(), defc,
   521                         defc, name, type, KlassHandle(), false, false, THREAD);
   522         } else {
   523           LinkResolver::resolve_virtual_call(result, Handle(), defc,
   524                         defc, name, type, KlassHandle(), false, false, THREAD);
   525         }
   526         if (HAS_PENDING_EXCEPTION) {
   527           CLEAR_PENDING_EXCEPTION;
   528           break;  // go to second chance
   529         }
   530       }
   531       methodHandle m = result.resolved_method();
   532       oop vmtarget = NULL;
   533       int vmindex = methodOopDesc::nonvirtual_vtable_index;
   534       if (defc->is_interface()) {
   535         vmindex = klassItable::compute_itable_index(m());
   536         assert(vmindex >= 0, "");
   537       } else if (result.has_vtable_index()) {
   538         vmindex = result.vtable_index();
   539         assert(vmindex >= 0, "");
   540       }
   541       assert(vmindex != VM_INDEX_UNINITIALIZED, "");
   542       if (vmindex < 0) {
   543         assert(result.is_statically_bound(), "");
   544         vmtarget = m();
   545       } else {
   546         vmtarget = result.resolved_klass()->as_klassOop();
   547       }
   548       int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   549       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   550       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   551       sun_dyn_MemberName::set_modifiers(mname(), mods);
   552       DEBUG_ONLY(int junk; klassOop junk2);
   553       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   554              "properly stored for later decoding");
   555       return;
   556     }
   557   case IS_CONSTRUCTOR:
   558     {
   559       CallInfo result;
   560       {
   561         EXCEPTION_MARK;
   562         if (name() == vmSymbols::object_initializer_name()) {
   563           LinkResolver::resolve_special_call(result,
   564                         defc, name, type, KlassHandle(), false, THREAD);
   565         } else {
   566           break;                // will throw after end of switch
   567         }
   568         if (HAS_PENDING_EXCEPTION) {
   569           CLEAR_PENDING_EXCEPTION;
   570           return;
   571         }
   572       }
   573       assert(result.is_statically_bound(), "");
   574       methodHandle m = result.resolved_method();
   575       oop vmtarget = m();
   576       int vmindex  = methodOopDesc::nonvirtual_vtable_index;
   577       int mods     = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   578       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   579       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   580       sun_dyn_MemberName::set_modifiers(mname(), mods);
   581       DEBUG_ONLY(int junk; klassOop junk2);
   582       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   583              "properly stored for later decoding");
   584       return;
   585     }
   586   case IS_FIELD:
   587     {
   588       // This is taken from LinkResolver::resolve_field, sans access checks.
   589       fieldDescriptor fd; // find_field initializes fd if found
   590       KlassHandle sel_klass(THREAD, instanceKlass::cast(defc())->find_field(name(), type(), &fd));
   591       // check if field exists; i.e., if a klass containing the field def has been selected
   592       if (sel_klass.is_null())  return;
   593       oop vmtarget = sel_klass->as_klassOop();
   594       int vmindex  = fd.offset();
   595       int mods     = (fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS);
   596       if (vmindex == VM_INDEX_UNINITIALIZED)  break;  // should not happen
   597       sun_dyn_MemberName::set_vmtarget(mname(),  vmtarget);
   598       sun_dyn_MemberName::set_vmindex(mname(),   vmindex);
   599       sun_dyn_MemberName::set_modifiers(mname(), mods);
   600       return;
   601     }
   602   default:
   603     THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   604   }
   606   // Second chance.
   607   if (polymorphic_method_type.not_null()) {
   608     // Look on a non-null class loader.
   609     Handle cur_class_loader;
   610     const int nptypes = java_dyn_MethodType::ptype_count(polymorphic_method_type());
   611     for (int i = 0; i <= nptypes; i++) {
   612       oop type_mirror;
   613       if (i < nptypes)  type_mirror = java_dyn_MethodType::ptype(polymorphic_method_type(), i);
   614       else              type_mirror = java_dyn_MethodType::rtype(polymorphic_method_type());
   615       klassOop example_type = java_lang_Class::as_klassOop(type_mirror);
   616       if (example_type == NULL)  continue;
   617       oop class_loader = Klass::cast(example_type)->class_loader();
   618       if (class_loader == NULL || class_loader == cur_class_loader())  continue;
   619       cur_class_loader = Handle(THREAD, class_loader);
   620       methodOop m = SystemDictionary::find_method_handle_invoke(name,
   621                                                                 type,
   622                                                                 KlassHandle(THREAD, example_type),
   623                                                                 THREAD);
   624       if (HAS_PENDING_EXCEPTION) {
   625         CLEAR_PENDING_EXCEPTION;
   626         m = NULL;
   627         // try again with a different class loader...
   628       }
   629       if (m != NULL) {
   630         int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   631         sun_dyn_MemberName::set_vmtarget(mname(),  m);
   632         sun_dyn_MemberName::set_vmindex(mname(),   m->vtable_index());
   633         sun_dyn_MemberName::set_modifiers(mname(), mods);
   634         return;
   635       }
   636     }
   637   }
   638 }
   640 // Conversely, a member name which is only initialized from JVM internals
   641 // may have null defc, name, and type fields.
   642 // Resolving it plants a vmtarget/vmindex in it,
   643 // which refers directly to JVM internals.
   644 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
   645   assert(sun_dyn_MemberName::is_instance(mname()), "");
   646   oop vmtarget = sun_dyn_MemberName::vmtarget(mname());
   647   int vmindex  = sun_dyn_MemberName::vmindex(mname());
   648   if (vmtarget == NULL || vmindex == VM_INDEX_UNINITIALIZED) {
   649     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
   650   }
   652   bool have_defc = (sun_dyn_MemberName::clazz(mname()) != NULL);
   653   bool have_name = (sun_dyn_MemberName::name(mname()) != NULL);
   654   bool have_type = (sun_dyn_MemberName::type(mname()) != NULL);
   655   int flags      = sun_dyn_MemberName::flags(mname());
   657   if (suppress != 0) {
   658     if (suppress & _suppress_defc)  have_defc = true;
   659     if (suppress & _suppress_name)  have_name = true;
   660     if (suppress & _suppress_type)  have_type = true;
   661   }
   663   if (have_defc && have_name && have_type)  return;  // nothing needed
   665   switch (flags & ALL_KINDS) {
   666   case IS_METHOD:
   667   case IS_CONSTRUCTOR:
   668     {
   669       klassOop receiver_limit = NULL;
   670       int      decode_flags   = 0;
   671       methodHandle m(THREAD, decode_vmtarget(vmtarget, vmindex, NULL,
   672                                              receiver_limit, decode_flags));
   673       if (m.is_null())  break;
   674       if (!have_defc) {
   675         klassOop defc = m->method_holder();
   676         if (receiver_limit != NULL && receiver_limit != defc
   677             && Klass::cast(receiver_limit)->is_subtype_of(defc))
   678           defc = receiver_limit;
   679         sun_dyn_MemberName::set_clazz(mname(), Klass::cast(defc)->java_mirror());
   680       }
   681       if (!have_name) {
   682         //not java_lang_String::create_from_symbol; let's intern member names
   683         Handle name = StringTable::intern(m->name(), CHECK);
   684         sun_dyn_MemberName::set_name(mname(), name());
   685       }
   686       if (!have_type) {
   687         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
   688         sun_dyn_MemberName::set_type(mname(), type());
   689       }
   690       return;
   691     }
   692   case IS_FIELD:
   693     {
   694       // This is taken from LinkResolver::resolve_field, sans access checks.
   695       if (!vmtarget->is_klass())  break;
   696       if (!Klass::cast((klassOop) vmtarget)->oop_is_instance())  break;
   697       instanceKlassHandle defc(THREAD, (klassOop) vmtarget);
   698       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
   699       fieldDescriptor fd; // find_field initializes fd if found
   700       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
   701         break;                  // cannot expand
   702       if (!have_defc) {
   703         sun_dyn_MemberName::set_clazz(mname(), defc->java_mirror());
   704       }
   705       if (!have_name) {
   706         //not java_lang_String::create_from_symbol; let's intern member names
   707         Handle name = StringTable::intern(fd.name(), CHECK);
   708         sun_dyn_MemberName::set_name(mname(), name());
   709       }
   710       if (!have_type) {
   711         Handle type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
   712         sun_dyn_MemberName::set_type(mname(), type());
   713       }
   714       return;
   715     }
   716   }
   717   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   718 }
   720 int MethodHandles::find_MemberNames(klassOop k,
   721                                     symbolOop name, symbolOop sig,
   722                                     int mflags, klassOop caller,
   723                                     int skip, objArrayOop results) {
   724   DEBUG_ONLY(No_Safepoint_Verifier nsv);
   725   // this code contains no safepoints!
   727   // %%% take caller into account!
   729   if (k == NULL || !Klass::cast(k)->oop_is_instance())  return -1;
   731   int rfill = 0, rlimit = results->length(), rskip = skip;
   732   // overflow measurement:
   733   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
   735   int match_flags = mflags;
   736   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
   737   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
   738   bool local_only = !(search_superc | search_intfc);
   739   bool classes_only = false;
   741   if (name != NULL) {
   742     if (name->utf8_length() == 0)  return 0; // a match is not possible
   743   }
   744   if (sig != NULL) {
   745     if (sig->utf8_length() == 0)  return 0; // a match is not possible
   746     if (sig->byte_at(0) == '(')
   747       match_flags &= ~(IS_FIELD | IS_TYPE);
   748     else
   749       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
   750   }
   752   if ((match_flags & IS_TYPE) != 0) {
   753     // NYI, and Core Reflection works quite well for this query
   754   }
   756   if ((match_flags & IS_FIELD) != 0) {
   757     for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   758       if (name != NULL && st.name() != name)
   759           continue;
   760       if (sig != NULL && st.signature() != sig)
   761         continue;
   762       // passed the filters
   763       if (rskip > 0) {
   764         --rskip;
   765       } else if (rfill < rlimit) {
   766         oop result = results->obj_at(rfill++);
   767         if (!sun_dyn_MemberName::is_instance(result))
   768           return -99;  // caller bug!
   769         MethodHandles::init_MemberName(result, st.klass()->as_klassOop(), st.access_flags(), st.offset());
   770       } else if (++overflow >= overflow_limit) {
   771         match_flags = 0; break; // got tired of looking at overflow
   772       }
   773     }
   774   }
   776   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
   777     // watch out for these guys:
   778     symbolOop init_name   = vmSymbols::object_initializer_name();
   779     symbolOop clinit_name = vmSymbols::class_initializer_name();
   780     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
   781     bool negate_name_test = false;
   782     // fix name so that it captures the intention of IS_CONSTRUCTOR
   783     if (!(match_flags & IS_METHOD)) {
   784       // constructors only
   785       if (name == NULL) {
   786         name = init_name;
   787       } else if (name != init_name) {
   788         return 0;               // no constructors of this method name
   789       }
   790     } else if (!(match_flags & IS_CONSTRUCTOR)) {
   791       // methods only
   792       if (name == NULL) {
   793         name = init_name;
   794         negate_name_test = true; // if we see the name, we *omit* the entry
   795       } else if (name == init_name) {
   796         return 0;               // no methods of this constructor name
   797       }
   798     } else {
   799       // caller will accept either sort; no need to adjust name
   800     }
   801     for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   802       methodOop m = st.method();
   803       symbolOop m_name = m->name();
   804       if (m_name == clinit_name)
   805         continue;
   806       if (name != NULL && ((m_name != name) ^ negate_name_test))
   807           continue;
   808       if (sig != NULL && m->signature() != sig)
   809         continue;
   810       // passed the filters
   811       if (rskip > 0) {
   812         --rskip;
   813       } else if (rfill < rlimit) {
   814         oop result = results->obj_at(rfill++);
   815         if (!sun_dyn_MemberName::is_instance(result))
   816           return -99;  // caller bug!
   817         MethodHandles::init_MemberName(result, m, true);
   818       } else if (++overflow >= overflow_limit) {
   819         match_flags = 0; break; // got tired of looking at overflow
   820       }
   821     }
   822   }
   824   // return number of elements we at leasted wanted to initialize
   825   return rfill + overflow;
   826 }
   829 // Decode this java.lang.Class object into an instanceKlass, if possible.
   830 // Throw IAE if not
   831 instanceKlassHandle MethodHandles::resolve_instance_klass(oop java_mirror_oop, TRAPS) {
   832   instanceKlassHandle empty;
   833   klassOop caller = NULL;
   834   if (java_lang_Class::is_instance(java_mirror_oop)) {
   835     caller = java_lang_Class::as_klassOop(java_mirror_oop);
   836   }
   837   if (caller == NULL || !Klass::cast(caller)->oop_is_instance()) {
   838     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not a class", empty);
   839   }
   840   return instanceKlassHandle(THREAD, caller);
   841 }
   845 // Decode the vmtarget field of a method handle.
   846 // Sanitize out methodOops, klassOops, and any other non-Java data.
   847 // This is for debugging and reflection.
   848 oop MethodHandles::encode_target(Handle mh, int format, TRAPS) {
   849   assert(java_dyn_MethodHandle::is_instance(mh()), "must be a MH");
   850   if (format == ETF_HANDLE_OR_METHOD_NAME) {
   851     oop target = java_dyn_MethodHandle::vmtarget(mh());
   852     if (target == NULL) {
   853       return NULL;                // unformed MH
   854     }
   855     klassOop tklass = target->klass();
   856     if (Klass::cast(tklass)->is_subclass_of(SystemDictionary::Object_klass())) {
   857       return target;              // target is another MH (or something else?)
   858     }
   859   }
   860   if (format == ETF_DIRECT_HANDLE) {
   861     oop target = mh();
   862     for (;;) {
   863       if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   864         return target;
   865       }
   866       if (!java_dyn_MethodHandle::is_instance(target)){
   867         return NULL;                // unformed MH
   868       }
   869       target = java_dyn_MethodHandle::vmtarget(target);
   870     }
   871   }
   872   // cases of metadata in MH.vmtarget:
   873   // - AMH can have methodOop for static invoke with bound receiver
   874   // - DMH can have methodOop for static invoke (on variable receiver)
   875   // - DMH can have klassOop for dispatched (non-static) invoke
   876   klassOop receiver_limit = NULL;
   877   int decode_flags = 0;
   878   methodOop m = decode_MethodHandle(mh(), receiver_limit, decode_flags);
   879   if (m == NULL)  return NULL;
   880   switch (format) {
   881   case ETF_REFLECT_METHOD:
   882     // same as jni_ToReflectedMethod:
   883     if (m->is_initializer()) {
   884       return Reflection::new_constructor(m, THREAD);
   885     } else {
   886       return Reflection::new_method(m, UseNewReflection, false, THREAD);
   887     }
   889   case ETF_HANDLE_OR_METHOD_NAME:   // method, not handle
   890   case ETF_METHOD_NAME:
   891     {
   892       if (SystemDictionary::MemberName_klass() == NULL)  break;
   893       instanceKlassHandle mname_klass(THREAD, SystemDictionary::MemberName_klass());
   894       mname_klass->initialize(CHECK_NULL);
   895       Handle mname = mname_klass->allocate_instance_handle(CHECK_NULL);
   896       sun_dyn_MemberName::set_vmindex(mname(), VM_INDEX_UNINITIALIZED);
   897       bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   898       init_MemberName(mname(), m, do_dispatch);
   899       expand_MemberName(mname, 0, CHECK_NULL);
   900       return mname();
   901     }
   902   }
   904   // Unknown format code.
   905   char msg[50];
   906   jio_snprintf(msg, sizeof(msg), "unknown getTarget format=%d", format);
   907   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), msg);
   908 }
   910 static const char* always_null_names[] = {
   911   "java/lang/Void",
   912   "java/lang/Null",
   913   //"java/lang/Nothing",
   914   "sun/dyn/empty/Empty",
   915   NULL
   916 };
   918 static bool is_always_null_type(klassOop klass) {
   919   if (!Klass::cast(klass)->oop_is_instance())  return false;
   920   instanceKlass* ik = instanceKlass::cast(klass);
   921   // Must be on the boot class path:
   922   if (ik->class_loader() != NULL)  return false;
   923   // Check the name.
   924   symbolOop name = ik->name();
   925   for (int i = 0; ; i++) {
   926     const char* test_name = always_null_names[i];
   927     if (test_name == NULL)  break;
   928     if (name->equals(test_name))
   929       return true;
   930   }
   931   return false;
   932 }
   934 bool MethodHandles::class_cast_needed(klassOop src, klassOop dst) {
   935   if (src == dst || dst == SystemDictionary::Object_klass())
   936     return false;                               // quickest checks
   937   Klass* srck = Klass::cast(src);
   938   Klass* dstk = Klass::cast(dst);
   939   if (dstk->is_interface()) {
   940     // interface receivers can safely be viewed as untyped,
   941     // because interface calls always include a dynamic check
   942     //dstk = Klass::cast(SystemDictionary::Object_klass());
   943     return false;
   944   }
   945   if (srck->is_interface()) {
   946     // interface arguments must be viewed as untyped
   947     //srck = Klass::cast(SystemDictionary::Object_klass());
   948     return true;
   949   }
   950   if (is_always_null_type(src)) {
   951     // some source types are known to be never instantiated;
   952     // they represent references which are always null
   953     // such null references never fail to convert safely
   954     return false;
   955   }
   956   return !srck->is_subclass_of(dstk->as_klassOop());
   957 }
   959 static oop object_java_mirror() {
   960   return Klass::cast(SystemDictionary::Object_klass())->java_mirror();
   961 }
   963 bool MethodHandles::same_basic_type_for_arguments(BasicType src,
   964                                                   BasicType dst,
   965                                                   bool raw,
   966                                                   bool for_return) {
   967   if (for_return) {
   968     // return values can always be forgotten:
   969     if (dst == T_VOID)  return true;
   970     if (src == T_VOID)  return raw && (dst == T_INT);
   971     // We allow caller to receive a garbage int, which is harmless.
   972     // This trick is pulled by trusted code (see VerifyType.canPassRaw).
   973   }
   974   assert(src != T_VOID && dst != T_VOID, "should not be here");
   975   if (src == dst)  return true;
   976   if (type2size[src] != type2size[dst])  return false;
   977   // allow reinterpretation casts for integral widening
   978   if (is_subword_type(src)) { // subwords can fit in int or other subwords
   979     if (dst == T_INT)         // any subword fits in an int
   980       return true;
   981     if (src == T_BOOLEAN)     // boolean fits in any subword
   982       return is_subword_type(dst);
   983     if (src == T_BYTE && dst == T_SHORT)
   984       return true;            // remaining case: byte fits in short
   985   }
   986   // allow float/fixed reinterpretation casts
   987   if (src == T_FLOAT)   return dst == T_INT;
   988   if (src == T_INT)     return dst == T_FLOAT;
   989   if (src == T_DOUBLE)  return dst == T_LONG;
   990   if (src == T_LONG)    return dst == T_DOUBLE;
   991   return false;
   992 }
   994 const char* MethodHandles::check_method_receiver(methodOop m,
   995                                                  klassOop passed_recv_type) {
   996   assert(!m->is_static(), "caller resp.");
   997   if (passed_recv_type == NULL)
   998     return "receiver type is primitive";
   999   if (class_cast_needed(passed_recv_type, m->method_holder())) {
  1000     Klass* formal = Klass::cast(m->method_holder());
  1001     return SharedRuntime::generate_class_cast_message("receiver type",
  1002                                                       formal->external_name());
  1004   return NULL;                  // checks passed
  1007 // Verify that m's signature can be called type-safely by a method handle
  1008 // of the given method type 'mtype'.
  1009 // It takes a TRAPS argument because it must perform symbol lookups.
  1010 void MethodHandles::verify_method_signature(methodHandle m,
  1011                                             Handle mtype,
  1012                                             int first_ptype_pos,
  1013                                             KlassHandle insert_ptype,
  1014                                             TRAPS) {
  1015   objArrayHandle ptypes(THREAD, java_dyn_MethodType::ptypes(mtype()));
  1016   int pnum = first_ptype_pos;
  1017   int pmax = ptypes->length();
  1018   int mnum = 0;                 // method argument
  1019   const char* err = NULL;
  1020   for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
  1021     oop ptype_oop = NULL;
  1022     if (ss.at_return_type()) {
  1023       if (pnum != pmax)
  1024         { err = "too many arguments"; break; }
  1025       ptype_oop = java_dyn_MethodType::rtype(mtype());
  1026     } else {
  1027       if (pnum >= pmax)
  1028         { err = "not enough arguments"; break; }
  1029       if (pnum >= 0)
  1030         ptype_oop = ptypes->obj_at(pnum);
  1031       else if (insert_ptype.is_null())
  1032         ptype_oop = NULL;
  1033       else
  1034         ptype_oop = insert_ptype->java_mirror();
  1035       pnum += 1;
  1036       mnum += 1;
  1038     klassOop  pklass = NULL;
  1039     BasicType ptype  = T_OBJECT;
  1040     if (ptype_oop != NULL)
  1041       ptype = java_lang_Class::as_BasicType(ptype_oop, &pklass);
  1042     else
  1043       // null does not match any non-reference; use Object to report the error
  1044       pklass = SystemDictionary::Object_klass();
  1045     klassOop  mklass = NULL;
  1046     BasicType mtype  = ss.type();
  1047     if (mtype == T_ARRAY)  mtype = T_OBJECT; // fold all refs to T_OBJECT
  1048     if (mtype == T_OBJECT) {
  1049       if (ptype_oop == NULL) {
  1050         // null matches any reference
  1051         continue;
  1053       KlassHandle pklass_handle(THREAD, pklass); pklass = NULL;
  1054       // If we fail to resolve types at this point, we will throw an error.
  1055       symbolOop    name_oop = ss.as_symbol(CHECK);
  1056       symbolHandle name(THREAD, name_oop);
  1057       instanceKlass* mk = instanceKlass::cast(m->method_holder());
  1058       Handle loader(THREAD, mk->class_loader());
  1059       Handle domain(THREAD, mk->protection_domain());
  1060       mklass = SystemDictionary::resolve_or_null(name, loader, domain, CHECK);
  1061       pklass = pklass_handle();
  1062       if (mklass == NULL && pklass != NULL &&
  1063           Klass::cast(pklass)->name() == name() &&
  1064           m->is_method_handle_invoke()) {
  1065         // Assume a match.  We can't really decode the signature of MH.invoke*.
  1066         continue;
  1069     if (!ss.at_return_type()) {
  1070       err = check_argument_type_change(ptype, pklass, mtype, mklass, mnum);
  1071     } else {
  1072       err = check_return_type_change(mtype, mklass, ptype, pklass); // note reversal!
  1074     if (err != NULL)  break;
  1077   if (err != NULL) {
  1078     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1082 // Main routine for verifying the MethodHandle.type of a proposed
  1083 // direct or bound-direct method handle.
  1084 void MethodHandles::verify_method_type(methodHandle m,
  1085                                        Handle mtype,
  1086                                        bool has_bound_recv,
  1087                                        KlassHandle bound_recv_type,
  1088                                        TRAPS) {
  1089   bool m_needs_receiver = !m->is_static();
  1091   const char* err = NULL;
  1093   int first_ptype_pos = m_needs_receiver ? 1 : 0;
  1094   if (has_bound_recv) {
  1095     first_ptype_pos -= 1;  // ptypes do not include the bound argument; start earlier in them
  1096     if (m_needs_receiver && bound_recv_type.is_null())
  1097       { err = "bound receiver is not an object"; goto die; }
  1100   if (m_needs_receiver && err == NULL) {
  1101     objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype());
  1102     if (ptypes->length() < first_ptype_pos)
  1103       { err = "receiver argument is missing"; goto die; }
  1104     if (has_bound_recv)
  1105       err = check_method_receiver(m(), bound_recv_type->as_klassOop());
  1106     else
  1107       err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
  1108     if (err != NULL)  goto die;
  1111   // Check the other arguments for mistypes.
  1112   verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
  1113   return;
  1115  die:
  1116   THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1119 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
  1120   // Verify vmslots.
  1121   int check_slots = argument_slot_count(java_dyn_MethodHandle::type(mh()));
  1122   if (java_dyn_MethodHandle::vmslots(mh()) != check_slots) {
  1123     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
  1127 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
  1128   // Verify that argslot points at the given argnum.
  1129   int check_slot = argument_slot(java_dyn_MethodHandle::type(mh()), argnum);
  1130   if (argslot != check_slot || argslot < 0) {
  1131     const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
  1132     size_t msglen = strlen(fmt) + 3*11 + 1;
  1133     char* msg = NEW_RESOURCE_ARRAY(char, msglen);
  1134     jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
  1135     THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
  1139 // Verify the correspondence between two method types.
  1140 // Apart from the advertised changes, caller method type X must
  1141 // be able to invoke the callee method Y type with no violations
  1142 // of type integrity.
  1143 // Return NULL if all is well, else a short error message.
  1144 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
  1145                                                     int insert_argnum, oop insert_type,
  1146                                                     int change_argnum, oop change_type,
  1147                                                     int delete_argnum,
  1148                                                     oop dst_mtype, int dst_beg, int dst_end,
  1149                                                     bool raw) {
  1150   objArrayOop src_ptypes = java_dyn_MethodType::ptypes(src_mtype);
  1151   objArrayOop dst_ptypes = java_dyn_MethodType::ptypes(dst_mtype);
  1153   int src_max = src_ptypes->length();
  1154   int dst_max = dst_ptypes->length();
  1156   if (src_end == -1)  src_end = src_max;
  1157   if (dst_end == -1)  dst_end = dst_max;
  1159   assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
  1160   assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
  1162   // pending actions; set to -1 when done:
  1163   int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
  1165   const char* err = NULL;
  1167   // Walk along each array of parameter types, including a virtual
  1168   // NULL end marker at the end of each.
  1169   for (int src_idx = src_beg, dst_idx = dst_beg;
  1170        (src_idx <= src_end && dst_idx <= dst_end);
  1171        src_idx++, dst_idx++) {
  1172     oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
  1173     oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
  1174     bool fix_null_src_type = false;
  1176     // Perform requested edits.
  1177     if (ins_idx == src_idx) {
  1178       // note that the inserted guy is never affected by a change or deletion
  1179       ins_idx = -1;
  1180       src_type = insert_type;
  1181       fix_null_src_type = true;
  1182       --src_idx;                // back up to process src type on next loop
  1183       src_idx = src_end;
  1184     } else {
  1185       // note that the changed guy can be immediately deleted
  1186       if (chg_idx == src_idx) {
  1187         chg_idx = -1;
  1188         assert(src_idx < src_end, "oob");
  1189         src_type = change_type;
  1190         fix_null_src_type = true;
  1192       if (del_idx == src_idx) {
  1193         del_idx = -1;
  1194         assert(src_idx < src_end, "oob");
  1195         --dst_idx;
  1196         continue;               // rerun loop after skipping this position
  1200     if (src_type == NULL && fix_null_src_type)
  1201       // explicit null in this case matches any dest reference
  1202       src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
  1204     // Compare the two argument types.
  1205     if (src_type != dst_type) {
  1206       if (src_type == NULL)  return "not enough arguments";
  1207       if (dst_type == NULL)  return "too many arguments";
  1208       err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
  1209       if (err != NULL)  return err;
  1213   // Now compare return types also.
  1214   oop src_rtype = java_dyn_MethodType::rtype(src_mtype);
  1215   oop dst_rtype = java_dyn_MethodType::rtype(dst_mtype);
  1216   if (src_rtype != dst_rtype) {
  1217     err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
  1218     if (err != NULL)  return err;
  1221   assert(err == NULL, "");
  1222   return NULL;  // all is well
  1226 const char* MethodHandles::check_argument_type_change(BasicType src_type,
  1227                                                       klassOop src_klass,
  1228                                                       BasicType dst_type,
  1229                                                       klassOop dst_klass,
  1230                                                       int argnum,
  1231                                                       bool raw) {
  1232   const char* err = NULL;
  1233   bool for_return = (argnum < 0);
  1235   // just in case:
  1236   if (src_type == T_ARRAY)  src_type = T_OBJECT;
  1237   if (dst_type == T_ARRAY)  dst_type = T_OBJECT;
  1239   // Produce some nice messages if VerifyMethodHandles is turned on:
  1240   if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
  1241     if (src_type == T_OBJECT) {
  1242       if (raw && dst_type == T_INT && is_always_null_type(src_klass))
  1243         return NULL;    // OK to convert a null pointer to a garbage int
  1244       err = ((argnum >= 0)
  1245              ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
  1246              : "type mismatch: returning a %s, but caller expects primitive %s");
  1247     } else if (dst_type == T_OBJECT) {
  1248       err = ((argnum >= 0)
  1249              ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
  1250              : "type mismatch: returning a primitive %s, but caller expects %s");
  1251     } else {
  1252       err = ((argnum >= 0)
  1253              ? "type mismatch: passing a %s for method argument #%d, which expects %s"
  1254              : "type mismatch: returning a %s, but caller expects %s");
  1256   } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
  1257              class_cast_needed(src_klass, dst_klass)) {
  1258     if (!class_cast_needed(dst_klass, src_klass)) {
  1259       if (raw)
  1260         return NULL;    // reverse cast is OK; the MH target is trusted to enforce it
  1261       err = ((argnum >= 0)
  1262              ? "cast required: passing a %s for method argument #%d, which expects %s"
  1263              : "cast required: returning a %s, but caller expects %s");
  1264     } else {
  1265       err = ((argnum >= 0)
  1266              ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
  1267              : "reference mismatch: returning a %s, but caller expects %s");
  1269   } else {
  1270     // passed the obstacle course
  1271     return NULL;
  1274   // format, format, format
  1275   const char* src_name = type2name(src_type);
  1276   const char* dst_name = type2name(dst_type);
  1277   if (src_type == T_OBJECT)  src_name = Klass::cast(src_klass)->external_name();
  1278   if (dst_type == T_OBJECT)  dst_name = Klass::cast(dst_klass)->external_name();
  1279   if (src_name == NULL)  src_name = "unknown type";
  1280   if (dst_name == NULL)  dst_name = "unknown type";
  1282   size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
  1283   char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
  1284   if (argnum >= 0) {
  1285     assert(strstr(err, "%d") != NULL, "");
  1286     jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
  1287   } else {
  1288     assert(strstr(err, "%d") == NULL, "");
  1289     jio_snprintf(msg, msglen, err, src_name,         dst_name);
  1291   return msg;
  1294 // Compute the depth within the stack of the given argument, i.e.,
  1295 // the combined size of arguments to the right of the given argument.
  1296 // For the last argument (ptypes.length-1) this will be zero.
  1297 // For the first argument (0) this will be the size of all
  1298 // arguments but that one.  For the special number -1, this
  1299 // will be the size of all arguments, including the first.
  1300 // If the argument is neither -1 nor a valid argument index,
  1301 // then return a negative number.  Otherwise, the result
  1302 // is in the range [0..vmslots] inclusive.
  1303 int MethodHandles::argument_slot(oop method_type, int arg) {
  1304   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1305   int argslot = 0;
  1306   int len = ptypes->length();
  1307   if (arg < -1 || arg >= len)  return -99;
  1308   for (int i = len-1; i > arg; i--) {
  1309     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1310     argslot += type2size[bt];
  1312   assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
  1313   return argslot;
  1316 // Given a slot number, return the argument number.
  1317 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
  1318   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1319   int argslot = 0;
  1320   int len = ptypes->length();
  1321   for (int i = len-1; i >= 0; i--) {
  1322     if (query_argslot == argslot)  return i;
  1323     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1324     argslot += type2size[bt];
  1326   // return pseudo-arg deepest in stack:
  1327   if (query_argslot == argslot)  return -1;
  1328   return -99;                   // oob slot, or splitting a double-slot arg
  1331 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
  1332                                                     KlassHandle receiver_limit,
  1333                                                     int decode_flags,
  1334                                                     KlassHandle receiver_klass,
  1335                                                     TRAPS) {
  1336   assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
  1337   assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
  1339   if (!m->is_static() &&
  1340       (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
  1341     // given type does not match class of method, or receiver is null!
  1342     // caller should have checked this, but let's be extra careful...
  1343     return methodHandle();
  1345   if (receiver_limit.not_null() &&
  1346       (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
  1347     // given type is not limited to the receiver type
  1348     // note that a null receiver can match any reference value, for a static method
  1349     return methodHandle();
  1351   if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
  1352     // pre-dispatched or static method (null receiver is OK for static)
  1353     return m;
  1355   } else if (receiver_klass.is_null()) {
  1356     // null receiver value; cannot dispatch
  1357     return methodHandle();
  1359   } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
  1360     // perform virtual dispatch
  1361     int vtable_index = m->vtable_index();
  1362     guarantee(vtable_index >= 0, "valid vtable index");
  1364     // receiver_klass might be an arrayKlassOop but all vtables start at
  1365     // the same place. The cast is to avoid virtual call and assertion.
  1366     // See also LinkResolver::runtime_resolve_virtual_method.
  1367     instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
  1368     DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
  1369     methodOop m_oop = inst->method_at_vtable(vtable_index);
  1370     return methodHandle(THREAD, m_oop);
  1372   } else {
  1373     // perform interface dispatch
  1374     int itable_index = klassItable::compute_itable_index(m());
  1375     guarantee(itable_index >= 0, "valid itable index");
  1376     instanceKlass* inst = instanceKlass::cast(receiver_klass());
  1377     methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
  1378     return methodHandle(THREAD, m_oop);
  1382 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
  1383   // Verify type.
  1384   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1385   verify_method_type(m, mtype, false, KlassHandle(), CHECK);
  1387   // Verify vmslots.
  1388   if (java_dyn_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
  1389     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
  1393 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
  1394   // Check arguments.
  1395   if (mh.is_null() || m.is_null() ||
  1396       (!do_dispatch && m->is_abstract())) {
  1397     THROW(vmSymbols::java_lang_InternalError());
  1400   java_dyn_MethodHandle::init_vmslots(mh());
  1402   if (VerifyMethodHandles) {
  1403     // The privileged code which invokes this routine should not make
  1404     // a mistake about types, but it's better to verify.
  1405     verify_DirectMethodHandle(mh, m, CHECK);
  1408   // Finally, after safety checks are done, link to the target method.
  1409   // We will follow the same path as the latter part of
  1410   // InterpreterRuntime::resolve_invoke(), which first finds the method
  1411   // and then decides how to populate the constant pool cache entry
  1412   // that links the interpreter calls to the method.  We need the same
  1413   // bits, and will use the same calling sequence code.
  1415   int vmindex = methodOopDesc::garbage_vtable_index;
  1416   oop vmtarget = NULL;
  1418   instanceKlass::cast(m->method_holder())->link_class(CHECK);
  1420   MethodHandleEntry* me = NULL;
  1421   if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
  1422     // We are simulating an invokeinterface instruction.
  1423     // (We might also be simulating an invokevirtual on a miranda method,
  1424     // but it is safe to treat it as an invokeinterface.)
  1425     assert(!m->can_be_statically_bound(), "no final methods on interfaces");
  1426     vmindex = klassItable::compute_itable_index(m());
  1427     assert(vmindex >= 0, "(>=0) == do_dispatch");
  1428     // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
  1429     vmtarget = m->method_holder(); // the interface
  1430     me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
  1431   } else if (!do_dispatch || m->can_be_statically_bound()) {
  1432     // We are simulating an invokestatic or invokespecial instruction.
  1433     // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
  1434     vmtarget = m();
  1435     // this does not help dispatch, but it will make it possible to parse this MH:
  1436     vmindex  = methodOopDesc::nonvirtual_vtable_index;
  1437     assert(vmindex < 0, "(>=0) == do_dispatch");
  1438     if (!m->is_static()) {
  1439       me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
  1440     } else {
  1441       me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
  1442       // Part of the semantics of a static call is an initialization barrier.
  1443       // For a DMH, it is done now, when the handle is created.
  1444       Klass* k = Klass::cast(m->method_holder());
  1445       if (k->should_be_initialized()) {
  1446         k->initialize(CHECK);
  1449   } else {
  1450     // We are simulating an invokevirtual instruction.
  1451     // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
  1452     // The key logic is LinkResolver::runtime_resolve_virtual_method.
  1453     vmindex  = m->vtable_index();
  1454     vmtarget = m->method_holder();
  1455     me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
  1458   if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  1460   sun_dyn_DirectMethodHandle::set_vmtarget(mh(), vmtarget);
  1461   sun_dyn_DirectMethodHandle::set_vmindex(mh(),  vmindex);
  1462   DEBUG_ONLY(int flags; klassOop rlimit);
  1463   assert(MethodHandles::decode_method(mh(), rlimit, flags) == m(),
  1464          "properly stored for later decoding");
  1465   DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
  1466   assert(!(actual_do_dispatch && !do_dispatch),
  1467          "do not perform dispatch if !do_dispatch specified");
  1468   assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
  1469   assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
  1471   // Done!
  1472   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1475 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
  1476                                                            methodHandle m,
  1477                                                            TRAPS) {
  1478   // Verify type.
  1479   oop receiver = sun_dyn_BoundMethodHandle::argument(mh());
  1480   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1481   KlassHandle bound_recv_type;
  1482   if (receiver != NULL)  bound_recv_type = KlassHandle(THREAD, receiver->klass());
  1483   verify_method_type(m, mtype, true, bound_recv_type, CHECK);
  1485   int receiver_pos = m->size_of_parameters() - 1;
  1487   // Verify MH.vmargslot, which should point at the bound receiver.
  1488   verify_vmargslot(mh, -1, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1489   //verify_vmslots(mh, CHECK);
  1491   // Verify vmslots.
  1492   if (java_dyn_MethodHandle::vmslots(mh()) != receiver_pos) {
  1493     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
  1497 // Initialize a BMH with a receiver bound directly to a methodOop.
  1498 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
  1499                                                          methodHandle original_m,
  1500                                                          KlassHandle receiver_limit,
  1501                                                          int decode_flags,
  1502                                                          TRAPS) {
  1503   // Check arguments.
  1504   if (mh.is_null() || original_m.is_null()) {
  1505     THROW(vmSymbols::java_lang_InternalError());
  1508   KlassHandle receiver_klass;
  1510     oop receiver_oop = sun_dyn_BoundMethodHandle::argument(mh());
  1511     if (receiver_oop != NULL)
  1512       receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
  1514   methodHandle m = dispatch_decoded_method(original_m,
  1515                                            receiver_limit, decode_flags,
  1516                                            receiver_klass,
  1517                                            CHECK);
  1518   if (m.is_null())      { THROW(vmSymbols::java_lang_InternalError()); }
  1519   if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
  1521   java_dyn_MethodHandle::init_vmslots(mh());
  1523   if (VerifyMethodHandles) {
  1524     verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
  1527   sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1529   DEBUG_ONLY(int junk; klassOop junk2);
  1530   assert(MethodHandles::decode_method(mh(), junk2, junk) == m(), "properly stored for later decoding");
  1531   assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
  1533   // Done!
  1534   java_dyn_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
  1537 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
  1538                                              bool direct_to_method, TRAPS) {
  1539   Handle ptype_handle(THREAD,
  1540                            java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum));
  1541   KlassHandle ptype_klass;
  1542   BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
  1543   int slots_pushed = type2size[ptype];
  1545   oop argument = sun_dyn_BoundMethodHandle::argument(mh());
  1547   const char* err = NULL;
  1549   switch (ptype) {
  1550   case T_OBJECT:
  1551     if (argument != NULL)
  1552       // we must implicitly convert from the arg type to the outgoing ptype
  1553       err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
  1554     break;
  1556   case T_ARRAY: case T_VOID:
  1557     assert(false, "array, void do not appear here");
  1558   default:
  1559     if (ptype != T_INT && !is_subword_type(ptype)) {
  1560       err = "unexpected parameter type";
  1561       break;
  1563     // check subrange of Integer.value, if necessary
  1564     if (argument == NULL || argument->klass() != SystemDictionary::Integer_klass()) {
  1565       err = "bound integer argument must be of type java.lang.Integer";
  1566       break;
  1568     if (ptype != T_INT) {
  1569       int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
  1570       jint value = argument->int_field(value_offset);
  1571       int vminfo = adapter_subword_vminfo(ptype);
  1572       jint subword = truncate_subword_from_vminfo(value, vminfo);
  1573       if (value != subword) {
  1574         err = "bound subword value does not fit into the subword type";
  1575         break;
  1578     break;
  1579   case T_FLOAT:
  1580   case T_DOUBLE:
  1581   case T_LONG:
  1583       // we must implicitly convert from the unboxed arg type to the outgoing ptype
  1584       BasicType argbox = java_lang_boxing_object::basic_type(argument);
  1585       if (argbox != ptype) {
  1586         err = check_argument_type_change(T_OBJECT, (argument == NULL
  1587                                                     ? SystemDictionary::Object_klass()
  1588                                                     : argument->klass()),
  1589                                          ptype, ptype_klass(), argnum);
  1590         assert(err != NULL, "this must be an error");
  1592       break;
  1596   if (err == NULL) {
  1597     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1598     if (direct_to_method) {
  1599       assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
  1600       assert(slots_pushed <= MethodHandlePushLimit, "");
  1601     } else {
  1602       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1603       assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
  1604       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1605       // FIXME
  1606       // if (slots_pushed + target_pushes > MethodHandlePushLimit)
  1607       //   err = "too many bound parameters";
  1611   if (err == NULL) {
  1612     // Verify the rest of the method type.
  1613     err = check_method_type_insertion(java_dyn_MethodHandle::type(mh()),
  1614                                       argnum, ptype_handle(),
  1615                                       java_dyn_MethodHandle::type(target()));
  1618   if (err != NULL) {
  1619     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1623 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1624   // Check arguments.
  1625   if (mh.is_null() || target.is_null() || !java_dyn_MethodHandle::is_instance(target())) {
  1626     THROW(vmSymbols::java_lang_InternalError());
  1629   java_dyn_MethodHandle::init_vmslots(mh());
  1631   if (VerifyMethodHandles) {
  1632     int insert_after = argnum - 1;
  1633     verify_vmargslot(mh, insert_after, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1634     verify_vmslots(mh, CHECK);
  1637   // Get bound type and required slots.
  1638   oop ptype_oop = java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum);
  1639   BasicType ptype = java_lang_Class::as_BasicType(ptype_oop);
  1640   int slots_pushed = type2size[ptype];
  1642   // If (a) the target is a direct non-dispatched method handle,
  1643   // or (b) the target is a dispatched direct method handle and we
  1644   // are binding the receiver, cut out the middle-man.
  1645   // Do this by decoding the DMH and using its methodOop directly as vmtarget.
  1646   bool direct_to_method = false;
  1647   if (OptimizeMethodHandles &&
  1648       target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
  1649       (argnum == 0 || sun_dyn_DirectMethodHandle::vmindex(target()) < 0)) {
  1650     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  1651     methodHandle m(THREAD, decode_method(target(), receiver_limit_oop, decode_flags));
  1652     if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
  1653     DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - slots_pushed); // pos. of 1st arg.
  1654     assert(sun_dyn_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
  1655     if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
  1656       KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  1657       init_BoundMethodHandle_with_receiver(mh, m,
  1658                                            receiver_limit, decode_flags,
  1659                                            CHECK);
  1660       return;
  1663     // Even if it is not a bound receiver, we still might be able
  1664     // to bind another argument and still invoke the methodOop directly.
  1665     if (!(decode_flags & _dmf_does_dispatch)) {
  1666       direct_to_method = true;
  1667       sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1670   if (!direct_to_method)
  1671     sun_dyn_BoundMethodHandle::set_vmtarget(mh(), target());
  1673   if (VerifyMethodHandles) {
  1674     verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
  1677   // Next question:  Is this a ref, int, or long bound value?
  1678   MethodHandleEntry* me = NULL;
  1679   if (ptype == T_OBJECT) {
  1680     if (direct_to_method)  me = MethodHandles::entry(_bound_ref_direct_mh);
  1681     else                   me = MethodHandles::entry(_bound_ref_mh);
  1682   } else if (slots_pushed == 2) {
  1683     if (direct_to_method)  me = MethodHandles::entry(_bound_long_direct_mh);
  1684     else                   me = MethodHandles::entry(_bound_long_mh);
  1685   } else if (slots_pushed == 1) {
  1686     if (direct_to_method)  me = MethodHandles::entry(_bound_int_direct_mh);
  1687     else                   me = MethodHandles::entry(_bound_int_mh);
  1688   } else {
  1689     assert(false, "");
  1692   // Done!
  1693   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1696 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
  1697   char msg[200];
  1698   jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
  1699   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
  1702 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
  1703   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1704   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1706   verify_vmargslot(mh, argnum, argslot, CHECK);
  1707   verify_vmslots(mh, CHECK);
  1709   jint conv_op    = adapter_conversion_op(conversion);
  1710   if (!conv_op_valid(conv_op)) {
  1711     throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
  1712     return;
  1714   EntryKind ek = adapter_entry_kind(conv_op);
  1716   int stack_move = adapter_conversion_stack_move(conversion);
  1717   BasicType src  = adapter_conversion_src_type(conversion);
  1718   BasicType dest = adapter_conversion_dest_type(conversion);
  1719   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1721   Handle argument(THREAD,  sun_dyn_AdapterMethodHandle::argument(mh()));
  1722   Handle target(THREAD,    sun_dyn_AdapterMethodHandle::vmtarget(mh()));
  1723   Handle src_mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1724   Handle dst_mtype(THREAD, java_dyn_MethodHandle::type(target()));
  1726   const char* err = NULL;
  1728   if (err == NULL) {
  1729     // Check that the correct argument is supplied, but only if it is required.
  1730     switch (ek) {
  1731     case _adapter_check_cast:     // target type of cast
  1732     case _adapter_ref_to_prim:    // wrapper type from which to unbox
  1733     case _adapter_prim_to_ref:    // wrapper type to box into
  1734     case _adapter_collect_args:   // array type to collect into
  1735     case _adapter_spread_args:    // array type to spread from
  1736       if (!java_lang_Class::is_instance(argument())
  1737           || java_lang_Class::is_primitive(argument()))
  1738         { err = "adapter requires argument of type java.lang.Class"; break; }
  1739       if (ek == _adapter_collect_args ||
  1740           ek == _adapter_spread_args) {
  1741         // Make sure it is a suitable collection type.  (Array, for now.)
  1742         Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
  1743         if (!ak->oop_is_objArray()) {
  1744           { err = "adapter requires argument of type java.lang.Class<Object[]>"; break; }
  1747       break;
  1748     case _adapter_flyby:
  1749     case _adapter_ricochet:
  1750       if (!java_dyn_MethodHandle::is_instance(argument()))
  1751         { err = "MethodHandle adapter argument required"; break; }
  1752       break;
  1753     default:
  1754       if (argument.not_null())
  1755         { err = "adapter has spurious argument"; break; }
  1756       break;
  1760   if (err == NULL) {
  1761     // Check that the src/dest types are supplied if needed.
  1762     switch (ek) {
  1763     case _adapter_check_cast:
  1764       if (src != T_OBJECT || dest != T_OBJECT) {
  1765         err = "adapter requires object src/dest conversion subfields";
  1767       break;
  1768     case _adapter_prim_to_prim:
  1769       if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
  1770         err = "adapter requires primitive src/dest conversion subfields"; break;
  1772       if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
  1773           !(src == T_FLOAT || src == T_DOUBLE) &&  (dest == T_FLOAT || dest == T_DOUBLE)) {
  1774         err = "adapter cannot convert beween floating and fixed-point"; break;
  1776       break;
  1777     case _adapter_ref_to_prim:
  1778       if (src != T_OBJECT || !is_java_primitive(dest)
  1779           || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
  1780         err = "adapter requires primitive dest conversion subfield"; break;
  1782       break;
  1783     case _adapter_prim_to_ref:
  1784       if (!is_java_primitive(src) || dest != T_OBJECT
  1785           || argument() != Klass::cast(SystemDictionary::box_klass(src))->java_mirror()) {
  1786         err = "adapter requires primitive src conversion subfield"; break;
  1788       break;
  1789     case _adapter_swap_args:
  1790     case _adapter_rot_args:
  1792         if (!src || src != dest) {
  1793           err = "adapter requires src/dest conversion subfields for swap"; break;
  1795         int swap_size = type2size[src];
  1796         oop src_mtype  = sun_dyn_AdapterMethodHandle::type(mh());
  1797         oop dest_mtype = sun_dyn_AdapterMethodHandle::type(target());
  1798         int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(target());
  1799         int src_slot   = argslot;
  1800         int dest_slot  = vminfo;
  1801         bool rotate_up = (src_slot > dest_slot); // upward rotation
  1802         int src_arg    = argnum;
  1803         int dest_arg   = argument_slot_to_argnum(dest_mtype, dest_slot);
  1804         verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
  1805         if (!(dest_slot >= src_slot + swap_size) &&
  1806             !(src_slot >= dest_slot + swap_size)) {
  1807           err = "source, destination slots must be distinct";
  1808         } else if (ek == _adapter_swap_args && !(src_slot > dest_slot)) {
  1809           err = "source of swap must be deeper in stack";
  1810         } else if (ek == _adapter_swap_args) {
  1811           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, dest_arg),
  1812                                            java_dyn_MethodType::ptype(dest_mtype, src_arg),
  1813                                            dest_arg);
  1814         } else if (ek == _adapter_rot_args) {
  1815           if (rotate_up) {
  1816             assert((src_slot > dest_slot) && (src_arg < dest_arg), "");
  1817             // rotate up: [dest_slot..src_slot-ss] --> [dest_slot+ss..src_slot]
  1818             // that is:   [src_arg+1..dest_arg] --> [src_arg..dest_arg-1]
  1819             for (int i = src_arg+1; i <= dest_arg && err == NULL; i++) {
  1820               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1821                                                java_dyn_MethodType::ptype(dest_mtype, i-1),
  1822                                                i);
  1824           } else { // rotate down
  1825             assert((src_slot < dest_slot) && (src_arg > dest_arg), "");
  1826             // rotate down: [src_slot+ss..dest_slot] --> [src_slot..dest_slot-ss]
  1827             // that is:     [dest_arg..src_arg-1] --> [dst_arg+1..src_arg]
  1828             for (int i = dest_arg; i <= src_arg-1 && err == NULL; i++) {
  1829               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1830                                                java_dyn_MethodType::ptype(dest_mtype, i+1),
  1831                                                i);
  1835         if (err == NULL)
  1836           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, src_arg),
  1837                                            java_dyn_MethodType::ptype(dest_mtype, dest_arg),
  1838                                            src_arg);
  1840       break;
  1841     case _adapter_collect_args:
  1842     case _adapter_spread_args:
  1844         BasicType coll_type = (ek == _adapter_collect_args) ? dest : src;
  1845         BasicType elem_type = (ek == _adapter_collect_args) ? src : dest;
  1846         if (coll_type != T_OBJECT || elem_type != T_OBJECT) {
  1847           err = "adapter requires src/dest subfields"; break;
  1848           // later:
  1849           // - consider making coll be a primitive array
  1850           // - consider making coll be a heterogeneous collection
  1853       break;
  1854     default:
  1855       if (src != 0 || dest != 0) {
  1856         err = "adapter has spurious src/dest conversion subfields"; break;
  1858       break;
  1862   if (err == NULL) {
  1863     // Check the stack_move subfield.
  1864     // It must always report the net change in stack size, positive or negative.
  1865     int slots_pushed = stack_move / stack_move_unit();
  1866     switch (ek) {
  1867     case _adapter_prim_to_prim:
  1868     case _adapter_ref_to_prim:
  1869     case _adapter_prim_to_ref:
  1870       if (slots_pushed != type2size[dest] - type2size[src]) {
  1871         err = "wrong stack motion for primitive conversion";
  1873       break;
  1874     case _adapter_dup_args:
  1875       if (slots_pushed <= 0) {
  1876         err = "adapter requires conversion subfield slots_pushed > 0";
  1878       break;
  1879     case _adapter_drop_args:
  1880       if (slots_pushed >= 0) {
  1881         err = "adapter requires conversion subfield slots_pushed < 0";
  1883       break;
  1884     case _adapter_collect_args:
  1885       if (slots_pushed > 1) {
  1886         err = "adapter requires conversion subfield slots_pushed <= 1";
  1888       break;
  1889     case _adapter_spread_args:
  1890       if (slots_pushed < -1) {
  1891         err = "adapter requires conversion subfield slots_pushed >= -1";
  1893       break;
  1894     default:
  1895       if (stack_move != 0) {
  1896         err = "adapter has spurious stack_move conversion subfield";
  1898       break;
  1900     if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
  1901       err = "stack_move conversion subfield must be multiple of stack_move_unit";
  1905   if (err == NULL) {
  1906     // Make sure this adapter does not push too deeply.
  1907     int slots_pushed = stack_move / stack_move_unit();
  1908     int this_vmslots = java_dyn_MethodHandle::vmslots(mh());
  1909     int target_vmslots = java_dyn_MethodHandle::vmslots(target());
  1910     if (slots_pushed != (target_vmslots - this_vmslots)) {
  1911       err = "stack_move inconsistent with previous and current MethodType vmslots";
  1912     } else if (slots_pushed > 0)  {
  1913       // verify stack_move against MethodHandlePushLimit
  1914       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1915       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1916       if (slots_pushed + target_pushes > MethodHandlePushLimit) {
  1917         err = "adapter pushes too many parameters";
  1921     // While we're at it, check that the stack motion decoder works:
  1922     DEBUG_ONLY(int target_pushes = decode_MethodHandle_stack_pushes(target()));
  1923     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1924     assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
  1927   if (err == NULL && vminfo != 0) {
  1928     switch (ek) {
  1929       case _adapter_swap_args:
  1930       case _adapter_rot_args:
  1931         break;                // OK
  1932     default:
  1933       err = "vminfo subfield is reserved to the JVM";
  1937   // Do additional ad hoc checks.
  1938   if (err == NULL) {
  1939     switch (ek) {
  1940     case _adapter_retype_only:
  1941       err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
  1942       break;
  1944     case _adapter_retype_raw:
  1945       err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
  1946       break;
  1948     case _adapter_check_cast:
  1950         // The actual value being checked must be a reference:
  1951         err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype(), argnum),
  1952                                          object_java_mirror(), argnum);
  1953         if (err != NULL)  break;
  1955         // The output of the cast must fit with the destination argument:
  1956         Handle cast_class = argument;
  1957         err = check_method_type_conversion(src_mtype(),
  1958                                            argnum, cast_class(),
  1959                                            dst_mtype());
  1961       break;
  1963       // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
  1967   if (err != NULL) {
  1968     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  1969     return;
  1974 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1975   oop  argument   = sun_dyn_AdapterMethodHandle::argument(mh());
  1976   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1977   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1978   jint conv_op    = adapter_conversion_op(conversion);
  1980   // adjust the adapter code to the internal EntryKind enumeration:
  1981   EntryKind ek_orig = adapter_entry_kind(conv_op);
  1982   EntryKind ek_opt  = ek_orig;  // may be optimized
  1984   // Finalize the vmtarget field (Java initialized it to null).
  1985   if (!java_dyn_MethodHandle::is_instance(target())) {
  1986     throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
  1987     return;
  1989   sun_dyn_AdapterMethodHandle::set_vmtarget(mh(), target());
  1991   if (VerifyMethodHandles) {
  1992     verify_AdapterMethodHandle(mh, argnum, CHECK);
  1995   int stack_move = adapter_conversion_stack_move(conversion);
  1996   BasicType src  = adapter_conversion_src_type(conversion);
  1997   BasicType dest = adapter_conversion_dest_type(conversion);
  1998   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  2000   const char* err = NULL;
  2002   // Now it's time to finish the case analysis and pick a MethodHandleEntry.
  2003   switch (ek_orig) {
  2004   case _adapter_retype_only:
  2005   case _adapter_retype_raw:
  2006   case _adapter_check_cast:
  2007   case _adapter_dup_args:
  2008   case _adapter_drop_args:
  2009     // these work fine via general case code
  2010     break;
  2012   case _adapter_prim_to_prim:
  2014       // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
  2015       // And, the {float,double} -> {int,long} cases must be handled by Java.
  2016       switch (type2size[src] *4+ type2size[dest]) {
  2017       case 1 *4+ 1:
  2018         assert(src == T_INT || is_subword_type(src), "source is not float");
  2019         // Subword-related cases are int -> {boolean,byte,char,short}.
  2020         ek_opt = _adapter_opt_i2i;
  2021         vminfo = adapter_subword_vminfo(dest);
  2022         break;
  2023       case 2 *4+ 1:
  2024         if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
  2025           ek_opt = _adapter_opt_l2i;
  2026           vminfo = adapter_subword_vminfo(dest);
  2027         } else if (src == T_DOUBLE && dest == T_FLOAT) {
  2028           ek_opt = _adapter_opt_d2f;
  2029         } else {
  2030           assert(false, "");
  2032         break;
  2033       case 1 *4+ 2:
  2034         if (src == T_INT && dest == T_LONG) {
  2035           ek_opt = _adapter_opt_i2l;
  2036         } else if (src == T_FLOAT && dest == T_DOUBLE) {
  2037           ek_opt = _adapter_opt_f2d;
  2038         } else {
  2039           assert(false, "");
  2041         break;
  2042       default:
  2043         assert(false, "");
  2044         break;
  2047     break;
  2049   case _adapter_ref_to_prim:
  2051       switch (type2size[dest]) {
  2052       case 1:
  2053         ek_opt = _adapter_opt_unboxi;
  2054         vminfo = adapter_subword_vminfo(dest);
  2055         break;
  2056       case 2:
  2057         ek_opt = _adapter_opt_unboxl;
  2058         break;
  2059       default:
  2060         assert(false, "");
  2061         break;
  2064     break;
  2066   case _adapter_prim_to_ref:
  2067     goto throw_not_impl;        // allocates, hence could block
  2069   case _adapter_swap_args:
  2070   case _adapter_rot_args:
  2072       int swap_slots = type2size[src];
  2073       int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(mh());
  2074       int src_slot   = argslot;
  2075       int dest_slot  = vminfo;
  2076       int rotate     = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
  2077       switch (swap_slots) {
  2078       case 1:
  2079         ek_opt = (!rotate    ? _adapter_opt_swap_1 :
  2080                   rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
  2081         break;
  2082       case 2:
  2083         ek_opt = (!rotate    ? _adapter_opt_swap_2 :
  2084                   rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
  2085         break;
  2086       default:
  2087         assert(false, "");
  2088         break;
  2091     break;
  2093   case _adapter_collect_args:
  2094     goto throw_not_impl;        // allocates, hence could block
  2096   case _adapter_spread_args:
  2098       // vminfo will be the required length of the array
  2099       int slots_pushed = stack_move / stack_move_unit();
  2100       int array_size   = slots_pushed + 1;
  2101       assert(array_size >= 0, "");
  2102       vminfo = array_size;
  2103       switch (array_size) {
  2104       case 0:   ek_opt = _adapter_opt_spread_0;       break;
  2105       case 1:   ek_opt = _adapter_opt_spread_1;       break;
  2106       default:  ek_opt = _adapter_opt_spread_more;    break;
  2108       if ((vminfo & CONV_VMINFO_MASK) != vminfo)
  2109         goto throw_not_impl;    // overflow
  2111     break;
  2113   case _adapter_flyby:
  2114   case _adapter_ricochet:
  2115     goto throw_not_impl;        // runs Java code, hence could block
  2117   default:
  2118     // should have failed much earlier; must be a missing case here
  2119     assert(false, "incomplete switch");
  2120     // and fall through:
  2122   throw_not_impl:
  2123     // FIXME: these adapters are NYI
  2124     err = "adapter not yet implemented in the JVM";
  2125     break;
  2128   if (err != NULL) {
  2129     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  2130     return;
  2133   // Rebuild the conversion value; maybe parts of it were changed.
  2134   jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
  2136   // Finalize the conversion field.  (Note that it is final to Java code.)
  2137   sun_dyn_AdapterMethodHandle::set_conversion(mh(), new_conversion);
  2139   // Done!
  2140   java_dyn_MethodHandle::set_vmentry(mh(), entry(ek_opt));
  2142   // There should be enough memory barriers on exit from native methods
  2143   // to ensure that the MH is fully initialized to all threads before
  2144   // Java code can publish it in global data structures.
  2147 //
  2148 // Here are the native methods on sun.dyn.MethodHandleImpl.
  2149 // They are the private interface between this JVM and the HotSpot-specific
  2150 // Java code that implements JSR 292 method handles.
  2151 //
  2152 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
  2153 // that intrinsic (non-JNI) native methods are defined in HotSpot.
  2154 //
  2156 // direct method handles for invokestatic or invokespecial
  2157 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
  2158 JVM_ENTRY(void, MHI_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2159                              jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
  2160   ResourceMark rm;              // for error messages
  2162   // This is the guy we are initializing:
  2163   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2164   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2166   // Early returns out of this method leave the DMH in an unfinished state.
  2167   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2169   // which method are we really talking about?
  2170   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2171   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2172   if (sun_dyn_MemberName::is_instance(target_oop) &&
  2173       sun_dyn_MemberName::vmindex(target_oop) == VM_INDEX_UNINITIALIZED) {
  2174     Handle mname(THREAD, target_oop);
  2175     MethodHandles::resolve_MemberName(mname, CHECK);
  2176     target_oop = mname(); // in case of GC
  2179   int decode_flags = 0; klassOop receiver_limit = NULL;
  2180   methodHandle m(THREAD,
  2181                  MethodHandles::decode_method(target_oop,
  2182                                               receiver_limit, decode_flags));
  2183   if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
  2185   // The trusted Java code that calls this method should already have performed
  2186   // access checks on behalf of the given caller.  But, we can verify this.
  2187   if (VerifyMethodHandles && caller_jh != NULL) {
  2188     KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
  2189     // If this were a bytecode, the first access check would be against
  2190     // the "reference class" mentioned in the CONSTANT_Methodref.
  2191     // We don't know at this point which class that was, and if we
  2192     // check against m.method_holder we might get the wrong answer.
  2193     // So we just make sure to handle this check when the resolution
  2194     // happens, when we call resolve_MemberName.
  2195     //
  2196     // (A public class can inherit public members from private supers,
  2197     // and it would be wrong to check access against the private super
  2198     // if the original symbolic reference was against the public class.)
  2199     //
  2200     // If there were a bytecode, the next step would be to lookup the method
  2201     // in the reference class, then then check the method's access bits.
  2202     // Emulate LinkResolver::check_method_accessability.
  2203     klassOop resolved_klass = m->method_holder();
  2204     if (!Reflection::verify_field_access(caller->as_klassOop(),
  2205                                          resolved_klass, resolved_klass,
  2206                                          m->access_flags(),
  2207                                          true)) {
  2208       // %%% following cutout belongs in Reflection::verify_field_access?
  2209       bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
  2210                                                         resolved_klass, THREAD);
  2211       if (!same_pm) {
  2212         THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
  2217   MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
  2219 JVM_END
  2221 // bound method handles
  2222 JVM_ENTRY(void, MHI_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2223                              jobject target_jh, int argnum)) {
  2224   ResourceMark rm;              // for error messages
  2226   // This is the guy we are initializing:
  2227   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2228   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2230   // Early returns out of this method leave the BMH in an unfinished state.
  2231   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2233   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2234   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2236   if (!java_dyn_MethodHandle::is_instance(target())) {
  2237     // Target object is a reflective method.  (%%% Do we need this alternate path?)
  2238     Untested("init_BMH of non-MH");
  2239     if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
  2240     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  2241     methodHandle m(THREAD,
  2242                    MethodHandles::decode_method(target(),
  2243                                                 receiver_limit_oop,
  2244                                                 decode_flags));
  2245     KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  2246     MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
  2247                                                        receiver_limit,
  2248                                                        decode_flags,
  2249                                                        CHECK);
  2250     return;
  2253   // Build a BMH on top of a DMH or another BMH:
  2254   MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
  2256 JVM_END
  2258 // adapter method handles
  2259 JVM_ENTRY(void, MHI_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2260                              jobject target_jh, int argnum)) {
  2261   // This is the guy we are initializing:
  2262   if (mh_jh == NULL || target_jh == NULL) {
  2263     THROW(vmSymbols::java_lang_InternalError());
  2265   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2266   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2268   // Early returns out of this method leave the AMH in an unfinished state.
  2269   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2271   MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
  2273 JVM_END
  2275 // method type forms
  2276 JVM_ENTRY(void, MHI_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
  2277   if (erased_jh == NULL)  return;
  2278   if (TraceMethodHandles) {
  2279     tty->print("creating MethodType form ");
  2280     if (WizardMode || Verbose) {   // Warning: this calls Java code on the MH!
  2281       // call Object.toString()
  2282       symbolOop name = vmSymbols::toString_name(), sig = vmSymbols::void_string_signature();
  2283       JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
  2284       JavaValue result(T_OBJECT);
  2285       JavaCalls::call_virtual(&result, SystemDictionary::Object_klass(), name, sig,
  2286                               &args, CHECK);
  2287       Handle str(THREAD, (oop)result.get_jobject());
  2288       java_lang_String::print(str, tty);
  2290     tty->cr();
  2293 JVM_END
  2295 // debugging and reflection
  2296 JVM_ENTRY(jobject, MHI_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
  2297   Handle mh(THREAD, JNIHandles::resolve(mh_jh));
  2298   if (!java_dyn_MethodHandle::is_instance(mh())) {
  2299     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
  2301   oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
  2302   return JNIHandles::make_local(THREAD, target);
  2304 JVM_END
  2306 JVM_ENTRY(jint, MHI_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  2307   switch (which) {
  2308   case MethodHandles::GC_JVM_PUSH_LIMIT:
  2309     guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
  2310               "MethodHandlePushLimit parameter must be in valid range");
  2311     return MethodHandlePushLimit;
  2312   case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
  2313     // return number of words per slot, signed according to stack direction
  2314     return MethodHandles::stack_move_unit();
  2315   case MethodHandles::GC_CONV_OP_IMPLEMENTED_MASK:
  2316     return MethodHandles::adapter_conversion_ops_supported_mask();
  2318   return 0;
  2320 JVM_END
  2322 #ifndef PRODUCT
  2323 #define EACH_NAMED_CON(template) \
  2324     template(MethodHandles,GC_JVM_PUSH_LIMIT) \
  2325     template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) \
  2326     template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
  2327     template(MethodHandles,ETF_DIRECT_HANDLE) \
  2328     template(MethodHandles,ETF_METHOD_NAME) \
  2329     template(MethodHandles,ETF_REFLECT_METHOD) \
  2330     template(sun_dyn_MemberName,MN_IS_METHOD) \
  2331     template(sun_dyn_MemberName,MN_IS_CONSTRUCTOR) \
  2332     template(sun_dyn_MemberName,MN_IS_FIELD) \
  2333     template(sun_dyn_MemberName,MN_IS_TYPE) \
  2334     template(sun_dyn_MemberName,MN_SEARCH_SUPERCLASSES) \
  2335     template(sun_dyn_MemberName,MN_SEARCH_INTERFACES) \
  2336     template(sun_dyn_MemberName,VM_INDEX_UNINITIALIZED) \
  2337     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_ONLY) \
  2338     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_RAW) \
  2339     template(sun_dyn_AdapterMethodHandle,OP_CHECK_CAST) \
  2340     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
  2341     template(sun_dyn_AdapterMethodHandle,OP_REF_TO_PRIM) \
  2342     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_REF) \
  2343     template(sun_dyn_AdapterMethodHandle,OP_SWAP_ARGS) \
  2344     template(sun_dyn_AdapterMethodHandle,OP_ROT_ARGS) \
  2345     template(sun_dyn_AdapterMethodHandle,OP_DUP_ARGS) \
  2346     template(sun_dyn_AdapterMethodHandle,OP_DROP_ARGS) \
  2347     template(sun_dyn_AdapterMethodHandle,OP_COLLECT_ARGS) \
  2348     template(sun_dyn_AdapterMethodHandle,OP_SPREAD_ARGS) \
  2349     template(sun_dyn_AdapterMethodHandle,OP_FLYBY) \
  2350     template(sun_dyn_AdapterMethodHandle,OP_RICOCHET) \
  2351     template(sun_dyn_AdapterMethodHandle,CONV_OP_LIMIT) \
  2352     template(sun_dyn_AdapterMethodHandle,CONV_OP_MASK) \
  2353     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_MASK) \
  2354     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
  2355     template(sun_dyn_AdapterMethodHandle,CONV_OP_SHIFT) \
  2356     template(sun_dyn_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
  2357     template(sun_dyn_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
  2358     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
  2359     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
  2360     /*end*/
  2362 #define ONE_PLUS(scope,value) 1+
  2363 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
  2364 #define VALUE_COMMA(scope,value) scope::value,
  2365 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
  2366 #define STRING_NULL(scope,value) #value "\0"
  2367 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
  2369 #undef ONE_PLUS
  2370 #undef VALUE_COMMA
  2371 #undef STRING_NULL
  2372 #undef EACH_NAMED_CON
  2373 #endif
  2375 JVM_ENTRY(jint, MHI_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
  2376 #ifndef PRODUCT
  2377   if (which >= 0 && which < con_value_count) {
  2378     int con = con_values[which];
  2379     objArrayOop box = (objArrayOop) JNIHandles::resolve(box_jh);
  2380     if (box != NULL && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
  2381       const char* str = &con_names[0];
  2382       for (int i = 0; i < which; i++)
  2383         str += strlen(str) + 1;   // skip name and null
  2384       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);
  2385       box->obj_at_put(0, name);
  2387     return con;
  2389 #endif
  2390   return 0;
  2392 JVM_END
  2394 // void init(MemberName self, AccessibleObject ref)
  2395 JVM_ENTRY(void, MHI_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
  2396   if (mname_jh == NULL || target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2397   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2398   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2399   MethodHandles::init_MemberName(mname(), target_oop);
  2401 JVM_END
  2403 // void expand(MemberName self)
  2404 JVM_ENTRY(void, MHI_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  2405   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2406   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2407   MethodHandles::expand_MemberName(mname, 0, CHECK);
  2409 JVM_END
  2411 // void resolve(MemberName self, Class<?> caller)
  2412 JVM_ENTRY(void, MHI_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  2413   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2414   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2416   // The trusted Java code that calls this method should already have performed
  2417   // access checks on behalf of the given caller.  But, we can verify this.
  2418   if (VerifyMethodHandles && caller_jh != NULL) {
  2419     klassOop reference_klass = java_lang_Class::as_klassOop(sun_dyn_MemberName::clazz(mname()));
  2420     if (reference_klass != NULL) {
  2421       // Emulate LinkResolver::check_klass_accessability.
  2422       klassOop caller = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh));
  2423       if (!Reflection::verify_class_access(caller,
  2424                                            reference_klass,
  2425                                            true)) {
  2426         THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(reference_klass)->external_name());
  2431   MethodHandles::resolve_MemberName(mname, CHECK);
  2433 JVM_END
  2435 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2436 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2437 JVM_ENTRY(jint, MHI_getMembers(JNIEnv *env, jobject igcls,
  2438                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
  2439                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  2440   if (clazz_jh == NULL || results_jh == NULL)  return -1;
  2441   klassOop k_oop = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh));
  2443   objArrayOop results = (objArrayOop) JNIHandles::resolve(results_jh);
  2444   if (results == NULL || !results->is_objArray())       return -1;
  2446   symbolOop name = NULL, sig = NULL;
  2447   if (name_jh != NULL) {
  2448     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
  2449     if (name == NULL)  return 0; // a match is not possible
  2451   if (sig_jh != NULL) {
  2452     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
  2453     if (sig == NULL)  return 0; // a match is not possible
  2456   klassOop caller = NULL;
  2457   if (caller_jh != NULL) {
  2458     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
  2459     if (!java_lang_Class::is_instance(caller_oop))  return -1;
  2460     caller = java_lang_Class::as_klassOop(caller_oop);
  2463   if (name != NULL && sig != NULL && results != NULL) {
  2464     // try a direct resolve
  2465     // %%% TO DO
  2468   int res = MethodHandles::find_MemberNames(k_oop, name, sig, mflags,
  2469                                             caller, skip, results);
  2470   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  2471   return res;
  2473 JVM_END
  2475 JVM_ENTRY(void, MHI_registerBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh, jobject bsm_jh)) {
  2476   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2477   if (!AllowTransitionalJSR292) {
  2478     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  2479               "registerBootstrapMethod is only supported in JSR 292 EDR");
  2481   ik->link_class(CHECK);
  2482   if (!java_dyn_MethodHandle::is_instance(JNIHandles::resolve(bsm_jh))) {
  2483     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "method handle");
  2485   const char* err = NULL;
  2486   if (ik->is_initialized() || ik->is_in_error_state()) {
  2487     err = "too late: class is already initialized";
  2488   } else {
  2489     ObjectLocker ol(ik, THREAD);  // note:  this should be a recursive lock
  2490     if (ik->is_not_initialized() ||
  2491         (ik->is_being_initialized() && ik->is_reentrant_initialization(THREAD))) {
  2492       if (ik->bootstrap_method() != NULL) {
  2493         err = "class is already equipped with a bootstrap method";
  2494       } else {
  2495         ik->set_bootstrap_method(JNIHandles::resolve_non_null(bsm_jh));
  2496         err = NULL;
  2498     } else {
  2499       err = "class is already initialized";
  2500       if (ik->is_being_initialized())
  2501         err = "class is already being initialized in a different thread";
  2504   if (err != NULL) {
  2505     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), err);
  2508 JVM_END
  2510 JVM_ENTRY(jobject, MHI_getBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh)) {
  2511   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2512   return JNIHandles::make_local(THREAD, ik->bootstrap_method());
  2514 JVM_END
  2516 JVM_ENTRY(void, MHI_setCallSiteTarget(JNIEnv *env, jobject igcls, jobject site_jh, jobject target_jh)) {
  2517   // No special action required, yet.
  2518   oop site_oop = JNIHandles::resolve(site_jh);
  2519   if (!java_dyn_CallSite::is_instance(site_oop))
  2520     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "not a CallSite");
  2521   java_dyn_CallSite::set_target(site_oop, JNIHandles::resolve(target_jh));
  2523 JVM_END
  2526 /// JVM_RegisterMethodHandleMethods
  2528 #define ADR "J"
  2530 #define LANG "Ljava/lang/"
  2531 #define JDYN "Ljava/dyn/"
  2532 #define IDYN "Lsun/dyn/"
  2534 #define OBJ   LANG"Object;"
  2535 #define CLS   LANG"Class;"
  2536 #define STRG  LANG"String;"
  2537 #define CST   JDYN"CallSite;"
  2538 #define MT    JDYN"MethodType;"
  2539 #define MH    JDYN"MethodHandle;"
  2540 #define MHI   IDYN"MethodHandleImpl;"
  2541 #define MEM   IDYN"MemberName;"
  2542 #define AMH   IDYN"AdapterMethodHandle;"
  2543 #define BMH   IDYN"BoundMethodHandle;"
  2544 #define DMH   IDYN"DirectMethodHandle;"
  2546 #define CC (char*)  /*cast a literal from (const char*)*/
  2547 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
  2549 // These are the native methods on sun.dyn.MethodHandleNatives.
  2550 static JNINativeMethod methods[] = {
  2551   // void init(MemberName self, AccessibleObject ref)
  2552   {CC"init",                    CC"("AMH""MH"I)V",              FN_PTR(MHI_init_AMH)},
  2553   {CC"init",                    CC"("BMH""OBJ"I)V",             FN_PTR(MHI_init_BMH)},
  2554   {CC"init",                    CC"("DMH""OBJ"Z"CLS")V",        FN_PTR(MHI_init_DMH)},
  2555   {CC"init",                    CC"("MT")V",                    FN_PTR(MHI_init_MT)},
  2556   {CC"init",                    CC"("MEM""OBJ")V",              FN_PTR(MHI_init_Mem)},
  2557   {CC"expand",                  CC"("MEM")V",                   FN_PTR(MHI_expand_Mem)},
  2558   {CC"resolve",                 CC"("MEM""CLS")V",              FN_PTR(MHI_resolve_Mem)},
  2559   {CC"getTarget",               CC"("MH"I)"OBJ,                 FN_PTR(MHI_getTarget)},
  2560   {CC"getConstant",             CC"(I)I",                       FN_PTR(MHI_getConstant)},
  2561   //  static native int getNamedCon(int which, Object[] name)
  2562   {CC"getNamedCon",             CC"(I["OBJ")I",                 FN_PTR(MHI_getNamedCon)},
  2563   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2564   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2565   {CC"getMembers",              CC"("CLS""STRG""STRG"I"CLS"I["MEM")I",  FN_PTR(MHI_getMembers)}
  2566 };
  2568 // More entry points specifically for EnableInvokeDynamic.
  2569 static JNINativeMethod methods2[] = {
  2570   {CC"registerBootstrap",       CC"("CLS MH")V",                FN_PTR(MHI_registerBootstrap)},
  2571   {CC"getBootstrap",            CC"("CLS")"MH,                  FN_PTR(MHI_getBootstrap)},
  2572   {CC"setCallSiteTarget",       CC"("CST MH")V",                FN_PTR(MHI_setCallSiteTarget)}
  2573 };
  2576 // This one function is exported, used by NativeLookup.
  2578 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
  2579   assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
  2581   // note: this explicit warning-producing stuff will be replaced by auto-detection of the JSR 292 classes
  2583   if (!EnableMethodHandles) {
  2584     warning("JSR 292 method handles are disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles to enable.");
  2585     return;  // bind nothing
  2588   bool enable_MH = true;
  2591     ThreadToNativeFromVM ttnfv(thread);
  2593     int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
  2594     if (env->ExceptionOccurred()) {
  2595       MethodHandles::set_enabled(false);
  2596       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2597       enable_MH = false;
  2598       env->ExceptionClear();
  2602   if (enable_MH) {
  2603     KlassHandle MHI_klass = SystemDictionaryHandles::MethodHandleImpl_klass();
  2604     if (MHI_klass.not_null()) {
  2605       symbolHandle raiseException_name = oopFactory::new_symbol_handle("raiseException", CHECK);
  2606       symbolHandle raiseException_sig  = oopFactory::new_symbol_handle("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK);
  2607       methodOop raiseException_method  = instanceKlass::cast(MHI_klass->as_klassOop())
  2608                     ->find_method(raiseException_name(), raiseException_sig());
  2609       if (raiseException_method != NULL && raiseException_method->is_static()) {
  2610         MethodHandles::set_raise_exception_method(raiseException_method);
  2611       } else {
  2612         warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2613         enable_MH = false;
  2618   if (enable_MH) {
  2619     MethodHandles::set_enabled(true);
  2622   if (!EnableInvokeDynamic) {
  2623     warning("JSR 292 invokedynamic is disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic to enable.");
  2624     return;  // bind nothing
  2628     ThreadToNativeFromVM ttnfv(thread);
  2630     int status = env->RegisterNatives(MHN_class, methods2, sizeof(methods2)/sizeof(JNINativeMethod));
  2631     if (env->ExceptionOccurred()) {
  2632       MethodHandles::set_enabled(false);
  2633       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2634       env->ExceptionClear();
  2635     } else {
  2636       MethodHandles::set_enabled(true);
  2640 JVM_END

mercurial