src/share/vm/prims/methodHandles.cpp

Sat, 30 Oct 2010 12:19:07 -0700

author
jrose
date
Sat, 30 Oct 2010 12:19:07 -0700
changeset 2267
8213b0f5c92d
parent 2204
5beba6174298
child 2314
f95d63e2154a
permissions
-rw-r--r--

6981777: implement JSR 292 EG adjustments from summer 2010
Summary: Small bug fix to make "raw" adapters work for JDK changes under 6981777
Reviewed-by: twisti

     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   if (src == T_OBJECT || dst == T_OBJECT)  return false;
   978   if (raw)  return true;  // bitwise reinterpretation; caller guarantees safety
   979   // allow reinterpretation casts for integral widening
   980   if (is_subword_type(src)) { // subwords can fit in int or other subwords
   981     if (dst == T_INT)         // any subword fits in an int
   982       return true;
   983     if (src == T_BOOLEAN)     // boolean fits in any subword
   984       return is_subword_type(dst);
   985     if (src == T_BYTE && dst == T_SHORT)
   986       return true;            // remaining case: byte fits in short
   987   }
   988   // allow float/fixed reinterpretation casts
   989   if (src == T_FLOAT)   return dst == T_INT;
   990   if (src == T_INT)     return dst == T_FLOAT;
   991   if (src == T_DOUBLE)  return dst == T_LONG;
   992   if (src == T_LONG)    return dst == T_DOUBLE;
   993   return false;
   994 }
   996 const char* MethodHandles::check_method_receiver(methodOop m,
   997                                                  klassOop passed_recv_type) {
   998   assert(!m->is_static(), "caller resp.");
   999   if (passed_recv_type == NULL)
  1000     return "receiver type is primitive";
  1001   if (class_cast_needed(passed_recv_type, m->method_holder())) {
  1002     Klass* formal = Klass::cast(m->method_holder());
  1003     return SharedRuntime::generate_class_cast_message("receiver type",
  1004                                                       formal->external_name());
  1006   return NULL;                  // checks passed
  1009 // Verify that m's signature can be called type-safely by a method handle
  1010 // of the given method type 'mtype'.
  1011 // It takes a TRAPS argument because it must perform symbol lookups.
  1012 void MethodHandles::verify_method_signature(methodHandle m,
  1013                                             Handle mtype,
  1014                                             int first_ptype_pos,
  1015                                             KlassHandle insert_ptype,
  1016                                             TRAPS) {
  1017   objArrayHandle ptypes(THREAD, java_dyn_MethodType::ptypes(mtype()));
  1018   int pnum = first_ptype_pos;
  1019   int pmax = ptypes->length();
  1020   int mnum = 0;                 // method argument
  1021   const char* err = NULL;
  1022   for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
  1023     oop ptype_oop = NULL;
  1024     if (ss.at_return_type()) {
  1025       if (pnum != pmax)
  1026         { err = "too many arguments"; break; }
  1027       ptype_oop = java_dyn_MethodType::rtype(mtype());
  1028     } else {
  1029       if (pnum >= pmax)
  1030         { err = "not enough arguments"; break; }
  1031       if (pnum >= 0)
  1032         ptype_oop = ptypes->obj_at(pnum);
  1033       else if (insert_ptype.is_null())
  1034         ptype_oop = NULL;
  1035       else
  1036         ptype_oop = insert_ptype->java_mirror();
  1037       pnum += 1;
  1038       mnum += 1;
  1040     klassOop  pklass = NULL;
  1041     BasicType ptype  = T_OBJECT;
  1042     if (ptype_oop != NULL)
  1043       ptype = java_lang_Class::as_BasicType(ptype_oop, &pklass);
  1044     else
  1045       // null does not match any non-reference; use Object to report the error
  1046       pklass = SystemDictionary::Object_klass();
  1047     klassOop  mklass = NULL;
  1048     BasicType mtype  = ss.type();
  1049     if (mtype == T_ARRAY)  mtype = T_OBJECT; // fold all refs to T_OBJECT
  1050     if (mtype == T_OBJECT) {
  1051       if (ptype_oop == NULL) {
  1052         // null matches any reference
  1053         continue;
  1055       KlassHandle pklass_handle(THREAD, pklass); pklass = NULL;
  1056       // If we fail to resolve types at this point, we will throw an error.
  1057       symbolOop    name_oop = ss.as_symbol(CHECK);
  1058       symbolHandle name(THREAD, name_oop);
  1059       instanceKlass* mk = instanceKlass::cast(m->method_holder());
  1060       Handle loader(THREAD, mk->class_loader());
  1061       Handle domain(THREAD, mk->protection_domain());
  1062       mklass = SystemDictionary::resolve_or_null(name, loader, domain, CHECK);
  1063       pklass = pklass_handle();
  1064       if (mklass == NULL && pklass != NULL &&
  1065           Klass::cast(pklass)->name() == name() &&
  1066           m->is_method_handle_invoke()) {
  1067         // Assume a match.  We can't really decode the signature of MH.invoke*.
  1068         continue;
  1071     if (!ss.at_return_type()) {
  1072       err = check_argument_type_change(ptype, pklass, mtype, mklass, mnum);
  1073     } else {
  1074       err = check_return_type_change(mtype, mklass, ptype, pklass); // note reversal!
  1076     if (err != NULL)  break;
  1079   if (err != NULL) {
  1080     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1084 // Main routine for verifying the MethodHandle.type of a proposed
  1085 // direct or bound-direct method handle.
  1086 void MethodHandles::verify_method_type(methodHandle m,
  1087                                        Handle mtype,
  1088                                        bool has_bound_recv,
  1089                                        KlassHandle bound_recv_type,
  1090                                        TRAPS) {
  1091   bool m_needs_receiver = !m->is_static();
  1093   const char* err = NULL;
  1095   int first_ptype_pos = m_needs_receiver ? 1 : 0;
  1096   if (has_bound_recv) {
  1097     first_ptype_pos -= 1;  // ptypes do not include the bound argument; start earlier in them
  1098     if (m_needs_receiver && bound_recv_type.is_null())
  1099       { err = "bound receiver is not an object"; goto die; }
  1102   if (m_needs_receiver && err == NULL) {
  1103     objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype());
  1104     if (ptypes->length() < first_ptype_pos)
  1105       { err = "receiver argument is missing"; goto die; }
  1106     if (has_bound_recv)
  1107       err = check_method_receiver(m(), bound_recv_type->as_klassOop());
  1108     else
  1109       err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
  1110     if (err != NULL)  goto die;
  1113   // Check the other arguments for mistypes.
  1114   verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
  1115   return;
  1117  die:
  1118   THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1121 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
  1122   // Verify vmslots.
  1123   int check_slots = argument_slot_count(java_dyn_MethodHandle::type(mh()));
  1124   if (java_dyn_MethodHandle::vmslots(mh()) != check_slots) {
  1125     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
  1129 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
  1130   // Verify that argslot points at the given argnum.
  1131   int check_slot = argument_slot(java_dyn_MethodHandle::type(mh()), argnum);
  1132   if (argslot != check_slot || argslot < 0) {
  1133     const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
  1134     size_t msglen = strlen(fmt) + 3*11 + 1;
  1135     char* msg = NEW_RESOURCE_ARRAY(char, msglen);
  1136     jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
  1137     THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
  1141 // Verify the correspondence between two method types.
  1142 // Apart from the advertised changes, caller method type X must
  1143 // be able to invoke the callee method Y type with no violations
  1144 // of type integrity.
  1145 // Return NULL if all is well, else a short error message.
  1146 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
  1147                                                     int insert_argnum, oop insert_type,
  1148                                                     int change_argnum, oop change_type,
  1149                                                     int delete_argnum,
  1150                                                     oop dst_mtype, int dst_beg, int dst_end,
  1151                                                     bool raw) {
  1152   objArrayOop src_ptypes = java_dyn_MethodType::ptypes(src_mtype);
  1153   objArrayOop dst_ptypes = java_dyn_MethodType::ptypes(dst_mtype);
  1155   int src_max = src_ptypes->length();
  1156   int dst_max = dst_ptypes->length();
  1158   if (src_end == -1)  src_end = src_max;
  1159   if (dst_end == -1)  dst_end = dst_max;
  1161   assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
  1162   assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
  1164   // pending actions; set to -1 when done:
  1165   int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
  1167   const char* err = NULL;
  1169   // Walk along each array of parameter types, including a virtual
  1170   // NULL end marker at the end of each.
  1171   for (int src_idx = src_beg, dst_idx = dst_beg;
  1172        (src_idx <= src_end && dst_idx <= dst_end);
  1173        src_idx++, dst_idx++) {
  1174     oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
  1175     oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
  1176     bool fix_null_src_type = false;
  1178     // Perform requested edits.
  1179     if (ins_idx == src_idx) {
  1180       // note that the inserted guy is never affected by a change or deletion
  1181       ins_idx = -1;
  1182       src_type = insert_type;
  1183       fix_null_src_type = true;
  1184       --src_idx;                // back up to process src type on next loop
  1185       src_idx = src_end;
  1186     } else {
  1187       // note that the changed guy can be immediately deleted
  1188       if (chg_idx == src_idx) {
  1189         chg_idx = -1;
  1190         assert(src_idx < src_end, "oob");
  1191         src_type = change_type;
  1192         fix_null_src_type = true;
  1194       if (del_idx == src_idx) {
  1195         del_idx = -1;
  1196         assert(src_idx < src_end, "oob");
  1197         --dst_idx;
  1198         continue;               // rerun loop after skipping this position
  1202     if (src_type == NULL && fix_null_src_type)
  1203       // explicit null in this case matches any dest reference
  1204       src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
  1206     // Compare the two argument types.
  1207     if (src_type != dst_type) {
  1208       if (src_type == NULL)  return "not enough arguments";
  1209       if (dst_type == NULL)  return "too many arguments";
  1210       err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
  1211       if (err != NULL)  return err;
  1215   // Now compare return types also.
  1216   oop src_rtype = java_dyn_MethodType::rtype(src_mtype);
  1217   oop dst_rtype = java_dyn_MethodType::rtype(dst_mtype);
  1218   if (src_rtype != dst_rtype) {
  1219     err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
  1220     if (err != NULL)  return err;
  1223   assert(err == NULL, "");
  1224   return NULL;  // all is well
  1228 const char* MethodHandles::check_argument_type_change(BasicType src_type,
  1229                                                       klassOop src_klass,
  1230                                                       BasicType dst_type,
  1231                                                       klassOop dst_klass,
  1232                                                       int argnum,
  1233                                                       bool raw) {
  1234   const char* err = NULL;
  1235   bool for_return = (argnum < 0);
  1237   // just in case:
  1238   if (src_type == T_ARRAY)  src_type = T_OBJECT;
  1239   if (dst_type == T_ARRAY)  dst_type = T_OBJECT;
  1241   // Produce some nice messages if VerifyMethodHandles is turned on:
  1242   if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
  1243     if (src_type == T_OBJECT) {
  1244       if (raw && dst_type == T_INT && is_always_null_type(src_klass))
  1245         return NULL;    // OK to convert a null pointer to a garbage int
  1246       err = ((argnum >= 0)
  1247              ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
  1248              : "type mismatch: returning a %s, but caller expects primitive %s");
  1249     } else if (dst_type == T_OBJECT) {
  1250       err = ((argnum >= 0)
  1251              ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
  1252              : "type mismatch: returning a primitive %s, but caller expects %s");
  1253     } else {
  1254       err = ((argnum >= 0)
  1255              ? "type mismatch: passing a %s for method argument #%d, which expects %s"
  1256              : "type mismatch: returning a %s, but caller expects %s");
  1258   } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
  1259              class_cast_needed(src_klass, dst_klass)) {
  1260     if (!class_cast_needed(dst_klass, src_klass)) {
  1261       if (raw)
  1262         return NULL;    // reverse cast is OK; the MH target is trusted to enforce it
  1263       err = ((argnum >= 0)
  1264              ? "cast required: passing a %s for method argument #%d, which expects %s"
  1265              : "cast required: returning a %s, but caller expects %s");
  1266     } else {
  1267       err = ((argnum >= 0)
  1268              ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
  1269              : "reference mismatch: returning a %s, but caller expects %s");
  1271   } else {
  1272     // passed the obstacle course
  1273     return NULL;
  1276   // format, format, format
  1277   const char* src_name = type2name(src_type);
  1278   const char* dst_name = type2name(dst_type);
  1279   if (src_type == T_OBJECT)  src_name = Klass::cast(src_klass)->external_name();
  1280   if (dst_type == T_OBJECT)  dst_name = Klass::cast(dst_klass)->external_name();
  1281   if (src_name == NULL)  src_name = "unknown type";
  1282   if (dst_name == NULL)  dst_name = "unknown type";
  1284   size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
  1285   char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
  1286   if (argnum >= 0) {
  1287     assert(strstr(err, "%d") != NULL, "");
  1288     jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
  1289   } else {
  1290     assert(strstr(err, "%d") == NULL, "");
  1291     jio_snprintf(msg, msglen, err, src_name,         dst_name);
  1293   return msg;
  1296 // Compute the depth within the stack of the given argument, i.e.,
  1297 // the combined size of arguments to the right of the given argument.
  1298 // For the last argument (ptypes.length-1) this will be zero.
  1299 // For the first argument (0) this will be the size of all
  1300 // arguments but that one.  For the special number -1, this
  1301 // will be the size of all arguments, including the first.
  1302 // If the argument is neither -1 nor a valid argument index,
  1303 // then return a negative number.  Otherwise, the result
  1304 // is in the range [0..vmslots] inclusive.
  1305 int MethodHandles::argument_slot(oop method_type, int arg) {
  1306   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1307   int argslot = 0;
  1308   int len = ptypes->length();
  1309   if (arg < -1 || arg >= len)  return -99;
  1310   for (int i = len-1; i > arg; i--) {
  1311     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1312     argslot += type2size[bt];
  1314   assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
  1315   return argslot;
  1318 // Given a slot number, return the argument number.
  1319 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
  1320   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1321   int argslot = 0;
  1322   int len = ptypes->length();
  1323   for (int i = len-1; i >= 0; i--) {
  1324     if (query_argslot == argslot)  return i;
  1325     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1326     argslot += type2size[bt];
  1328   // return pseudo-arg deepest in stack:
  1329   if (query_argslot == argslot)  return -1;
  1330   return -99;                   // oob slot, or splitting a double-slot arg
  1333 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
  1334                                                     KlassHandle receiver_limit,
  1335                                                     int decode_flags,
  1336                                                     KlassHandle receiver_klass,
  1337                                                     TRAPS) {
  1338   assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
  1339   assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
  1341   if (!m->is_static() &&
  1342       (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
  1343     // given type does not match class of method, or receiver is null!
  1344     // caller should have checked this, but let's be extra careful...
  1345     return methodHandle();
  1347   if (receiver_limit.not_null() &&
  1348       (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
  1349     // given type is not limited to the receiver type
  1350     // note that a null receiver can match any reference value, for a static method
  1351     return methodHandle();
  1353   if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
  1354     // pre-dispatched or static method (null receiver is OK for static)
  1355     return m;
  1357   } else if (receiver_klass.is_null()) {
  1358     // null receiver value; cannot dispatch
  1359     return methodHandle();
  1361   } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
  1362     // perform virtual dispatch
  1363     int vtable_index = m->vtable_index();
  1364     guarantee(vtable_index >= 0, "valid vtable index");
  1366     // receiver_klass might be an arrayKlassOop but all vtables start at
  1367     // the same place. The cast is to avoid virtual call and assertion.
  1368     // See also LinkResolver::runtime_resolve_virtual_method.
  1369     instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
  1370     DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
  1371     methodOop m_oop = inst->method_at_vtable(vtable_index);
  1372     return methodHandle(THREAD, m_oop);
  1374   } else {
  1375     // perform interface dispatch
  1376     int itable_index = klassItable::compute_itable_index(m());
  1377     guarantee(itable_index >= 0, "valid itable index");
  1378     instanceKlass* inst = instanceKlass::cast(receiver_klass());
  1379     methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
  1380     return methodHandle(THREAD, m_oop);
  1384 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
  1385   // Verify type.
  1386   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1387   verify_method_type(m, mtype, false, KlassHandle(), CHECK);
  1389   // Verify vmslots.
  1390   if (java_dyn_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
  1391     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
  1395 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
  1396   // Check arguments.
  1397   if (mh.is_null() || m.is_null() ||
  1398       (!do_dispatch && m->is_abstract())) {
  1399     THROW(vmSymbols::java_lang_InternalError());
  1402   java_dyn_MethodHandle::init_vmslots(mh());
  1404   if (VerifyMethodHandles) {
  1405     // The privileged code which invokes this routine should not make
  1406     // a mistake about types, but it's better to verify.
  1407     verify_DirectMethodHandle(mh, m, CHECK);
  1410   // Finally, after safety checks are done, link to the target method.
  1411   // We will follow the same path as the latter part of
  1412   // InterpreterRuntime::resolve_invoke(), which first finds the method
  1413   // and then decides how to populate the constant pool cache entry
  1414   // that links the interpreter calls to the method.  We need the same
  1415   // bits, and will use the same calling sequence code.
  1417   int vmindex = methodOopDesc::garbage_vtable_index;
  1418   oop vmtarget = NULL;
  1420   instanceKlass::cast(m->method_holder())->link_class(CHECK);
  1422   MethodHandleEntry* me = NULL;
  1423   if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
  1424     // We are simulating an invokeinterface instruction.
  1425     // (We might also be simulating an invokevirtual on a miranda method,
  1426     // but it is safe to treat it as an invokeinterface.)
  1427     assert(!m->can_be_statically_bound(), "no final methods on interfaces");
  1428     vmindex = klassItable::compute_itable_index(m());
  1429     assert(vmindex >= 0, "(>=0) == do_dispatch");
  1430     // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
  1431     vmtarget = m->method_holder(); // the interface
  1432     me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
  1433   } else if (!do_dispatch || m->can_be_statically_bound()) {
  1434     // We are simulating an invokestatic or invokespecial instruction.
  1435     // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
  1436     vmtarget = m();
  1437     // this does not help dispatch, but it will make it possible to parse this MH:
  1438     vmindex  = methodOopDesc::nonvirtual_vtable_index;
  1439     assert(vmindex < 0, "(>=0) == do_dispatch");
  1440     if (!m->is_static()) {
  1441       me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
  1442     } else {
  1443       me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
  1444       // Part of the semantics of a static call is an initialization barrier.
  1445       // For a DMH, it is done now, when the handle is created.
  1446       Klass* k = Klass::cast(m->method_holder());
  1447       if (k->should_be_initialized()) {
  1448         k->initialize(CHECK);
  1451   } else {
  1452     // We are simulating an invokevirtual instruction.
  1453     // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
  1454     // The key logic is LinkResolver::runtime_resolve_virtual_method.
  1455     vmindex  = m->vtable_index();
  1456     vmtarget = m->method_holder();
  1457     me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
  1460   if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  1462   sun_dyn_DirectMethodHandle::set_vmtarget(mh(), vmtarget);
  1463   sun_dyn_DirectMethodHandle::set_vmindex(mh(),  vmindex);
  1464   DEBUG_ONLY(int flags; klassOop rlimit);
  1465   assert(MethodHandles::decode_method(mh(), rlimit, flags) == m(),
  1466          "properly stored for later decoding");
  1467   DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
  1468   assert(!(actual_do_dispatch && !do_dispatch),
  1469          "do not perform dispatch if !do_dispatch specified");
  1470   assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
  1471   assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
  1473   // Done!
  1474   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1477 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
  1478                                                            methodHandle m,
  1479                                                            TRAPS) {
  1480   // Verify type.
  1481   oop receiver = sun_dyn_BoundMethodHandle::argument(mh());
  1482   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1483   KlassHandle bound_recv_type;
  1484   if (receiver != NULL)  bound_recv_type = KlassHandle(THREAD, receiver->klass());
  1485   verify_method_type(m, mtype, true, bound_recv_type, CHECK);
  1487   int receiver_pos = m->size_of_parameters() - 1;
  1489   // Verify MH.vmargslot, which should point at the bound receiver.
  1490   verify_vmargslot(mh, -1, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1491   //verify_vmslots(mh, CHECK);
  1493   // Verify vmslots.
  1494   if (java_dyn_MethodHandle::vmslots(mh()) != receiver_pos) {
  1495     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
  1499 // Initialize a BMH with a receiver bound directly to a methodOop.
  1500 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
  1501                                                          methodHandle original_m,
  1502                                                          KlassHandle receiver_limit,
  1503                                                          int decode_flags,
  1504                                                          TRAPS) {
  1505   // Check arguments.
  1506   if (mh.is_null() || original_m.is_null()) {
  1507     THROW(vmSymbols::java_lang_InternalError());
  1510   KlassHandle receiver_klass;
  1512     oop receiver_oop = sun_dyn_BoundMethodHandle::argument(mh());
  1513     if (receiver_oop != NULL)
  1514       receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
  1516   methodHandle m = dispatch_decoded_method(original_m,
  1517                                            receiver_limit, decode_flags,
  1518                                            receiver_klass,
  1519                                            CHECK);
  1520   if (m.is_null())      { THROW(vmSymbols::java_lang_InternalError()); }
  1521   if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
  1523   java_dyn_MethodHandle::init_vmslots(mh());
  1525   if (VerifyMethodHandles) {
  1526     verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
  1529   sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1531   DEBUG_ONLY(int junk; klassOop junk2);
  1532   assert(MethodHandles::decode_method(mh(), junk2, junk) == m(), "properly stored for later decoding");
  1533   assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
  1535   // Done!
  1536   java_dyn_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
  1539 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
  1540                                              bool direct_to_method, TRAPS) {
  1541   Handle ptype_handle(THREAD,
  1542                            java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum));
  1543   KlassHandle ptype_klass;
  1544   BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
  1545   int slots_pushed = type2size[ptype];
  1547   oop argument = sun_dyn_BoundMethodHandle::argument(mh());
  1549   const char* err = NULL;
  1551   switch (ptype) {
  1552   case T_OBJECT:
  1553     if (argument != NULL)
  1554       // we must implicitly convert from the arg type to the outgoing ptype
  1555       err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
  1556     break;
  1558   case T_ARRAY: case T_VOID:
  1559     assert(false, "array, void do not appear here");
  1560   default:
  1561     if (ptype != T_INT && !is_subword_type(ptype)) {
  1562       err = "unexpected parameter type";
  1563       break;
  1565     // check subrange of Integer.value, if necessary
  1566     if (argument == NULL || argument->klass() != SystemDictionary::Integer_klass()) {
  1567       err = "bound integer argument must be of type java.lang.Integer";
  1568       break;
  1570     if (ptype != T_INT) {
  1571       int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
  1572       jint value = argument->int_field(value_offset);
  1573       int vminfo = adapter_unbox_subword_vminfo(ptype);
  1574       jint subword = truncate_subword_from_vminfo(value, vminfo);
  1575       if (value != subword) {
  1576         err = "bound subword value does not fit into the subword type";
  1577         break;
  1580     break;
  1581   case T_FLOAT:
  1582   case T_DOUBLE:
  1583   case T_LONG:
  1585       // we must implicitly convert from the unboxed arg type to the outgoing ptype
  1586       BasicType argbox = java_lang_boxing_object::basic_type(argument);
  1587       if (argbox != ptype) {
  1588         err = check_argument_type_change(T_OBJECT, (argument == NULL
  1589                                                     ? SystemDictionary::Object_klass()
  1590                                                     : argument->klass()),
  1591                                          ptype, ptype_klass(), argnum);
  1592         assert(err != NULL, "this must be an error");
  1594       break;
  1598   if (err == NULL) {
  1599     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1600     if (direct_to_method) {
  1601       assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
  1602       assert(slots_pushed <= MethodHandlePushLimit, "");
  1603     } else {
  1604       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1605       assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
  1606       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1607       // FIXME
  1608       // if (slots_pushed + target_pushes > MethodHandlePushLimit)
  1609       //   err = "too many bound parameters";
  1613   if (err == NULL) {
  1614     // Verify the rest of the method type.
  1615     err = check_method_type_insertion(java_dyn_MethodHandle::type(mh()),
  1616                                       argnum, ptype_handle(),
  1617                                       java_dyn_MethodHandle::type(target()));
  1620   if (err != NULL) {
  1621     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1625 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1626   // Check arguments.
  1627   if (mh.is_null() || target.is_null() || !java_dyn_MethodHandle::is_instance(target())) {
  1628     THROW(vmSymbols::java_lang_InternalError());
  1631   java_dyn_MethodHandle::init_vmslots(mh());
  1633   if (VerifyMethodHandles) {
  1634     int insert_after = argnum - 1;
  1635     verify_vmargslot(mh, insert_after, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1636     verify_vmslots(mh, CHECK);
  1639   // Get bound type and required slots.
  1640   oop ptype_oop = java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum);
  1641   BasicType ptype = java_lang_Class::as_BasicType(ptype_oop);
  1642   int slots_pushed = type2size[ptype];
  1644   // If (a) the target is a direct non-dispatched method handle,
  1645   // or (b) the target is a dispatched direct method handle and we
  1646   // are binding the receiver, cut out the middle-man.
  1647   // Do this by decoding the DMH and using its methodOop directly as vmtarget.
  1648   bool direct_to_method = false;
  1649   if (OptimizeMethodHandles &&
  1650       target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
  1651       (argnum == 0 || sun_dyn_DirectMethodHandle::vmindex(target()) < 0)) {
  1652     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  1653     methodHandle m(THREAD, decode_method(target(), receiver_limit_oop, decode_flags));
  1654     if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
  1655     DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - slots_pushed); // pos. of 1st arg.
  1656     assert(sun_dyn_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
  1657     if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
  1658       KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  1659       init_BoundMethodHandle_with_receiver(mh, m,
  1660                                            receiver_limit, decode_flags,
  1661                                            CHECK);
  1662       return;
  1665     // Even if it is not a bound receiver, we still might be able
  1666     // to bind another argument and still invoke the methodOop directly.
  1667     if (!(decode_flags & _dmf_does_dispatch)) {
  1668       direct_to_method = true;
  1669       sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1672   if (!direct_to_method)
  1673     sun_dyn_BoundMethodHandle::set_vmtarget(mh(), target());
  1675   if (VerifyMethodHandles) {
  1676     verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
  1679   // Next question:  Is this a ref, int, or long bound value?
  1680   MethodHandleEntry* me = NULL;
  1681   if (ptype == T_OBJECT) {
  1682     if (direct_to_method)  me = MethodHandles::entry(_bound_ref_direct_mh);
  1683     else                   me = MethodHandles::entry(_bound_ref_mh);
  1684   } else if (slots_pushed == 2) {
  1685     if (direct_to_method)  me = MethodHandles::entry(_bound_long_direct_mh);
  1686     else                   me = MethodHandles::entry(_bound_long_mh);
  1687   } else if (slots_pushed == 1) {
  1688     if (direct_to_method)  me = MethodHandles::entry(_bound_int_direct_mh);
  1689     else                   me = MethodHandles::entry(_bound_int_mh);
  1690   } else {
  1691     assert(false, "");
  1694   // Done!
  1695   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1698 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
  1699   char msg[200];
  1700   jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
  1701   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
  1704 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
  1705   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1706   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1708   verify_vmargslot(mh, argnum, argslot, CHECK);
  1709   verify_vmslots(mh, CHECK);
  1711   jint conv_op    = adapter_conversion_op(conversion);
  1712   if (!conv_op_valid(conv_op)) {
  1713     throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
  1714     return;
  1716   EntryKind ek = adapter_entry_kind(conv_op);
  1718   int stack_move = adapter_conversion_stack_move(conversion);
  1719   BasicType src  = adapter_conversion_src_type(conversion);
  1720   BasicType dest = adapter_conversion_dest_type(conversion);
  1721   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1723   Handle argument(THREAD,  sun_dyn_AdapterMethodHandle::argument(mh()));
  1724   Handle target(THREAD,    sun_dyn_AdapterMethodHandle::vmtarget(mh()));
  1725   Handle src_mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1726   Handle dst_mtype(THREAD, java_dyn_MethodHandle::type(target()));
  1728   const char* err = NULL;
  1730   if (err == NULL) {
  1731     // Check that the correct argument is supplied, but only if it is required.
  1732     switch (ek) {
  1733     case _adapter_check_cast:     // target type of cast
  1734     case _adapter_ref_to_prim:    // wrapper type from which to unbox
  1735     case _adapter_prim_to_ref:    // wrapper type to box into
  1736     case _adapter_collect_args:   // array type to collect into
  1737     case _adapter_spread_args:    // array type to spread from
  1738       if (!java_lang_Class::is_instance(argument())
  1739           || java_lang_Class::is_primitive(argument()))
  1740         { err = "adapter requires argument of type java.lang.Class"; break; }
  1741       if (ek == _adapter_collect_args ||
  1742           ek == _adapter_spread_args) {
  1743         // Make sure it is a suitable collection type.  (Array, for now.)
  1744         Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
  1745         if (!ak->oop_is_objArray()) {
  1746           { err = "adapter requires argument of type java.lang.Class<Object[]>"; break; }
  1749       break;
  1750     case _adapter_flyby:
  1751     case _adapter_ricochet:
  1752       if (!java_dyn_MethodHandle::is_instance(argument()))
  1753         { err = "MethodHandle adapter argument required"; break; }
  1754       break;
  1755     default:
  1756       if (argument.not_null())
  1757         { err = "adapter has spurious argument"; break; }
  1758       break;
  1762   if (err == NULL) {
  1763     // Check that the src/dest types are supplied if needed.
  1764     switch (ek) {
  1765     case _adapter_check_cast:
  1766       if (src != T_OBJECT || dest != T_OBJECT) {
  1767         err = "adapter requires object src/dest conversion subfields";
  1769       break;
  1770     case _adapter_prim_to_prim:
  1771       if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
  1772         err = "adapter requires primitive src/dest conversion subfields"; break;
  1774       if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
  1775           !(src == T_FLOAT || src == T_DOUBLE) &&  (dest == T_FLOAT || dest == T_DOUBLE)) {
  1776         err = "adapter cannot convert beween floating and fixed-point"; break;
  1778       break;
  1779     case _adapter_ref_to_prim:
  1780       if (src != T_OBJECT || !is_java_primitive(dest)
  1781           || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
  1782         err = "adapter requires primitive dest conversion subfield"; break;
  1784       break;
  1785     case _adapter_prim_to_ref:
  1786       if (!is_java_primitive(src) || dest != T_OBJECT
  1787           || argument() != Klass::cast(SystemDictionary::box_klass(src))->java_mirror()) {
  1788         err = "adapter requires primitive src conversion subfield"; break;
  1790       break;
  1791     case _adapter_swap_args:
  1792     case _adapter_rot_args:
  1794         if (!src || src != dest) {
  1795           err = "adapter requires src/dest conversion subfields for swap"; break;
  1797         int swap_size = type2size[src];
  1798         oop src_mtype  = sun_dyn_AdapterMethodHandle::type(mh());
  1799         oop dest_mtype = sun_dyn_AdapterMethodHandle::type(target());
  1800         int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(target());
  1801         int src_slot   = argslot;
  1802         int dest_slot  = vminfo;
  1803         bool rotate_up = (src_slot > dest_slot); // upward rotation
  1804         int src_arg    = argnum;
  1805         int dest_arg   = argument_slot_to_argnum(dest_mtype, dest_slot);
  1806         verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
  1807         if (!(dest_slot >= src_slot + swap_size) &&
  1808             !(src_slot >= dest_slot + swap_size)) {
  1809           err = "source, destination slots must be distinct";
  1810         } else if (ek == _adapter_swap_args && !(src_slot > dest_slot)) {
  1811           err = "source of swap must be deeper in stack";
  1812         } else if (ek == _adapter_swap_args) {
  1813           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, dest_arg),
  1814                                            java_dyn_MethodType::ptype(dest_mtype, src_arg),
  1815                                            dest_arg);
  1816         } else if (ek == _adapter_rot_args) {
  1817           if (rotate_up) {
  1818             assert((src_slot > dest_slot) && (src_arg < dest_arg), "");
  1819             // rotate up: [dest_slot..src_slot-ss] --> [dest_slot+ss..src_slot]
  1820             // that is:   [src_arg+1..dest_arg] --> [src_arg..dest_arg-1]
  1821             for (int i = src_arg+1; i <= dest_arg && err == NULL; i++) {
  1822               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1823                                                java_dyn_MethodType::ptype(dest_mtype, i-1),
  1824                                                i);
  1826           } else { // rotate down
  1827             assert((src_slot < dest_slot) && (src_arg > dest_arg), "");
  1828             // rotate down: [src_slot+ss..dest_slot] --> [src_slot..dest_slot-ss]
  1829             // that is:     [dest_arg..src_arg-1] --> [dst_arg+1..src_arg]
  1830             for (int i = dest_arg; i <= src_arg-1 && err == NULL; i++) {
  1831               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1832                                                java_dyn_MethodType::ptype(dest_mtype, i+1),
  1833                                                i);
  1837         if (err == NULL)
  1838           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, src_arg),
  1839                                            java_dyn_MethodType::ptype(dest_mtype, dest_arg),
  1840                                            src_arg);
  1842       break;
  1843     case _adapter_collect_args:
  1844     case _adapter_spread_args:
  1846         BasicType coll_type = (ek == _adapter_collect_args) ? dest : src;
  1847         BasicType elem_type = (ek == _adapter_collect_args) ? src : dest;
  1848         if (coll_type != T_OBJECT || elem_type != T_OBJECT) {
  1849           err = "adapter requires src/dest subfields"; break;
  1850           // later:
  1851           // - consider making coll be a primitive array
  1852           // - consider making coll be a heterogeneous collection
  1855       break;
  1856     default:
  1857       if (src != 0 || dest != 0) {
  1858         err = "adapter has spurious src/dest conversion subfields"; break;
  1860       break;
  1864   if (err == NULL) {
  1865     // Check the stack_move subfield.
  1866     // It must always report the net change in stack size, positive or negative.
  1867     int slots_pushed = stack_move / stack_move_unit();
  1868     switch (ek) {
  1869     case _adapter_prim_to_prim:
  1870     case _adapter_ref_to_prim:
  1871     case _adapter_prim_to_ref:
  1872       if (slots_pushed != type2size[dest] - type2size[src]) {
  1873         err = "wrong stack motion for primitive conversion";
  1875       break;
  1876     case _adapter_dup_args:
  1877       if (slots_pushed <= 0) {
  1878         err = "adapter requires conversion subfield slots_pushed > 0";
  1880       break;
  1881     case _adapter_drop_args:
  1882       if (slots_pushed >= 0) {
  1883         err = "adapter requires conversion subfield slots_pushed < 0";
  1885       break;
  1886     case _adapter_collect_args:
  1887       if (slots_pushed > 1) {
  1888         err = "adapter requires conversion subfield slots_pushed <= 1";
  1890       break;
  1891     case _adapter_spread_args:
  1892       if (slots_pushed < -1) {
  1893         err = "adapter requires conversion subfield slots_pushed >= -1";
  1895       break;
  1896     default:
  1897       if (stack_move != 0) {
  1898         err = "adapter has spurious stack_move conversion subfield";
  1900       break;
  1902     if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
  1903       err = "stack_move conversion subfield must be multiple of stack_move_unit";
  1907   if (err == NULL) {
  1908     // Make sure this adapter does not push too deeply.
  1909     int slots_pushed = stack_move / stack_move_unit();
  1910     int this_vmslots = java_dyn_MethodHandle::vmslots(mh());
  1911     int target_vmslots = java_dyn_MethodHandle::vmslots(target());
  1912     if (slots_pushed != (target_vmslots - this_vmslots)) {
  1913       err = "stack_move inconsistent with previous and current MethodType vmslots";
  1914     } else if (slots_pushed > 0)  {
  1915       // verify stack_move against MethodHandlePushLimit
  1916       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1917       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1918       if (slots_pushed + target_pushes > MethodHandlePushLimit) {
  1919         err = "adapter pushes too many parameters";
  1923     // While we're at it, check that the stack motion decoder works:
  1924     DEBUG_ONLY(int target_pushes = decode_MethodHandle_stack_pushes(target()));
  1925     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1926     assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
  1929   if (err == NULL && vminfo != 0) {
  1930     switch (ek) {
  1931       case _adapter_swap_args:
  1932       case _adapter_rot_args:
  1933         break;                // OK
  1934     default:
  1935       err = "vminfo subfield is reserved to the JVM";
  1939   // Do additional ad hoc checks.
  1940   if (err == NULL) {
  1941     switch (ek) {
  1942     case _adapter_retype_only:
  1943       err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
  1944       break;
  1946     case _adapter_retype_raw:
  1947       err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
  1948       break;
  1950     case _adapter_check_cast:
  1952         // The actual value being checked must be a reference:
  1953         err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype(), argnum),
  1954                                          object_java_mirror(), argnum);
  1955         if (err != NULL)  break;
  1957         // The output of the cast must fit with the destination argument:
  1958         Handle cast_class = argument;
  1959         err = check_method_type_conversion(src_mtype(),
  1960                                            argnum, cast_class(),
  1961                                            dst_mtype());
  1963       break;
  1965       // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
  1969   if (err != NULL) {
  1970     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  1971     return;
  1976 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1977   oop  argument   = sun_dyn_AdapterMethodHandle::argument(mh());
  1978   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1979   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1980   jint conv_op    = adapter_conversion_op(conversion);
  1982   // adjust the adapter code to the internal EntryKind enumeration:
  1983   EntryKind ek_orig = adapter_entry_kind(conv_op);
  1984   EntryKind ek_opt  = ek_orig;  // may be optimized
  1986   // Finalize the vmtarget field (Java initialized it to null).
  1987   if (!java_dyn_MethodHandle::is_instance(target())) {
  1988     throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
  1989     return;
  1991   sun_dyn_AdapterMethodHandle::set_vmtarget(mh(), target());
  1993   if (VerifyMethodHandles) {
  1994     verify_AdapterMethodHandle(mh, argnum, CHECK);
  1997   int stack_move = adapter_conversion_stack_move(conversion);
  1998   BasicType src  = adapter_conversion_src_type(conversion);
  1999   BasicType dest = adapter_conversion_dest_type(conversion);
  2000   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  2002   const char* err = NULL;
  2004   // Now it's time to finish the case analysis and pick a MethodHandleEntry.
  2005   switch (ek_orig) {
  2006   case _adapter_retype_only:
  2007   case _adapter_retype_raw:
  2008   case _adapter_check_cast:
  2009   case _adapter_dup_args:
  2010   case _adapter_drop_args:
  2011     // these work fine via general case code
  2012     break;
  2014   case _adapter_prim_to_prim:
  2016       // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
  2017       // And, the {float,double} -> {int,long} cases must be handled by Java.
  2018       switch (type2size[src] *4+ type2size[dest]) {
  2019       case 1 *4+ 1:
  2020         assert(src == T_INT || is_subword_type(src), "source is not float");
  2021         // Subword-related cases are int -> {boolean,byte,char,short}.
  2022         ek_opt = _adapter_opt_i2i;
  2023         vminfo = adapter_prim_to_prim_subword_vminfo(dest);
  2024         break;
  2025       case 2 *4+ 1:
  2026         if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
  2027           ek_opt = _adapter_opt_l2i;
  2028           vminfo = adapter_prim_to_prim_subword_vminfo(dest);
  2029         } else if (src == T_DOUBLE && dest == T_FLOAT) {
  2030           ek_opt = _adapter_opt_d2f;
  2031         } else {
  2032           assert(false, "");
  2034         break;
  2035       case 1 *4+ 2:
  2036         if (src == T_INT && dest == T_LONG) {
  2037           ek_opt = _adapter_opt_i2l;
  2038         } else if (src == T_FLOAT && dest == T_DOUBLE) {
  2039           ek_opt = _adapter_opt_f2d;
  2040         } else {
  2041           assert(false, "");
  2043         break;
  2044       default:
  2045         assert(false, "");
  2046         break;
  2049     break;
  2051   case _adapter_ref_to_prim:
  2053       switch (type2size[dest]) {
  2054       case 1:
  2055         ek_opt = _adapter_opt_unboxi;
  2056         vminfo = adapter_unbox_subword_vminfo(dest);
  2057         break;
  2058       case 2:
  2059         ek_opt = _adapter_opt_unboxl;
  2060         break;
  2061       default:
  2062         assert(false, "");
  2063         break;
  2066     break;
  2068   case _adapter_prim_to_ref:
  2069     goto throw_not_impl;        // allocates, hence could block
  2071   case _adapter_swap_args:
  2072   case _adapter_rot_args:
  2074       int swap_slots = type2size[src];
  2075       int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(mh());
  2076       int src_slot   = argslot;
  2077       int dest_slot  = vminfo;
  2078       int rotate     = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
  2079       switch (swap_slots) {
  2080       case 1:
  2081         ek_opt = (!rotate    ? _adapter_opt_swap_1 :
  2082                   rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
  2083         break;
  2084       case 2:
  2085         ek_opt = (!rotate    ? _adapter_opt_swap_2 :
  2086                   rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
  2087         break;
  2088       default:
  2089         assert(false, "");
  2090         break;
  2093     break;
  2095   case _adapter_collect_args:
  2096     goto throw_not_impl;        // allocates, hence could block
  2098   case _adapter_spread_args:
  2100       // vminfo will be the required length of the array
  2101       int slots_pushed = stack_move / stack_move_unit();
  2102       int array_size   = slots_pushed + 1;
  2103       assert(array_size >= 0, "");
  2104       vminfo = array_size;
  2105       switch (array_size) {
  2106       case 0:   ek_opt = _adapter_opt_spread_0;       break;
  2107       case 1:   ek_opt = _adapter_opt_spread_1;       break;
  2108       default:  ek_opt = _adapter_opt_spread_more;    break;
  2110       if ((vminfo & CONV_VMINFO_MASK) != vminfo)
  2111         goto throw_not_impl;    // overflow
  2113     break;
  2115   case _adapter_flyby:
  2116   case _adapter_ricochet:
  2117     goto throw_not_impl;        // runs Java code, hence could block
  2119   default:
  2120     // should have failed much earlier; must be a missing case here
  2121     assert(false, "incomplete switch");
  2122     // and fall through:
  2124   throw_not_impl:
  2125     // FIXME: these adapters are NYI
  2126     err = "adapter not yet implemented in the JVM";
  2127     break;
  2130   if (err != NULL) {
  2131     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  2132     return;
  2135   // Rebuild the conversion value; maybe parts of it were changed.
  2136   jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
  2138   // Finalize the conversion field.  (Note that it is final to Java code.)
  2139   sun_dyn_AdapterMethodHandle::set_conversion(mh(), new_conversion);
  2141   // Done!
  2142   java_dyn_MethodHandle::set_vmentry(mh(), entry(ek_opt));
  2144   // There should be enough memory barriers on exit from native methods
  2145   // to ensure that the MH is fully initialized to all threads before
  2146   // Java code can publish it in global data structures.
  2149 //
  2150 // Here are the native methods on sun.dyn.MethodHandleImpl.
  2151 // They are the private interface between this JVM and the HotSpot-specific
  2152 // Java code that implements JSR 292 method handles.
  2153 //
  2154 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
  2155 // that intrinsic (non-JNI) native methods are defined in HotSpot.
  2156 //
  2158 // direct method handles for invokestatic or invokespecial
  2159 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
  2160 JVM_ENTRY(void, MHI_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2161                              jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
  2162   ResourceMark rm;              // for error messages
  2164   // This is the guy we are initializing:
  2165   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2166   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2168   // Early returns out of this method leave the DMH in an unfinished state.
  2169   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2171   // which method are we really talking about?
  2172   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2173   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2174   if (sun_dyn_MemberName::is_instance(target_oop) &&
  2175       sun_dyn_MemberName::vmindex(target_oop) == VM_INDEX_UNINITIALIZED) {
  2176     Handle mname(THREAD, target_oop);
  2177     MethodHandles::resolve_MemberName(mname, CHECK);
  2178     target_oop = mname(); // in case of GC
  2181   int decode_flags = 0; klassOop receiver_limit = NULL;
  2182   methodHandle m(THREAD,
  2183                  MethodHandles::decode_method(target_oop,
  2184                                               receiver_limit, decode_flags));
  2185   if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
  2187   // The trusted Java code that calls this method should already have performed
  2188   // access checks on behalf of the given caller.  But, we can verify this.
  2189   if (VerifyMethodHandles && caller_jh != NULL) {
  2190     KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
  2191     // If this were a bytecode, the first access check would be against
  2192     // the "reference class" mentioned in the CONSTANT_Methodref.
  2193     // We don't know at this point which class that was, and if we
  2194     // check against m.method_holder we might get the wrong answer.
  2195     // So we just make sure to handle this check when the resolution
  2196     // happens, when we call resolve_MemberName.
  2197     //
  2198     // (A public class can inherit public members from private supers,
  2199     // and it would be wrong to check access against the private super
  2200     // if the original symbolic reference was against the public class.)
  2201     //
  2202     // If there were a bytecode, the next step would be to lookup the method
  2203     // in the reference class, then then check the method's access bits.
  2204     // Emulate LinkResolver::check_method_accessability.
  2205     klassOop resolved_klass = m->method_holder();
  2206     if (!Reflection::verify_field_access(caller->as_klassOop(),
  2207                                          resolved_klass, resolved_klass,
  2208                                          m->access_flags(),
  2209                                          true)) {
  2210       // %%% following cutout belongs in Reflection::verify_field_access?
  2211       bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
  2212                                                         resolved_klass, THREAD);
  2213       if (!same_pm) {
  2214         THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
  2219   MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
  2221 JVM_END
  2223 // bound method handles
  2224 JVM_ENTRY(void, MHI_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2225                              jobject target_jh, int argnum)) {
  2226   ResourceMark rm;              // for error messages
  2228   // This is the guy we are initializing:
  2229   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2230   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2232   // Early returns out of this method leave the BMH in an unfinished state.
  2233   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2235   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2236   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2238   if (!java_dyn_MethodHandle::is_instance(target())) {
  2239     // Target object is a reflective method.  (%%% Do we need this alternate path?)
  2240     Untested("init_BMH of non-MH");
  2241     if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
  2242     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  2243     methodHandle m(THREAD,
  2244                    MethodHandles::decode_method(target(),
  2245                                                 receiver_limit_oop,
  2246                                                 decode_flags));
  2247     KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  2248     MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
  2249                                                        receiver_limit,
  2250                                                        decode_flags,
  2251                                                        CHECK);
  2252     return;
  2255   // Build a BMH on top of a DMH or another BMH:
  2256   MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
  2258 JVM_END
  2260 // adapter method handles
  2261 JVM_ENTRY(void, MHI_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2262                              jobject target_jh, int argnum)) {
  2263   // This is the guy we are initializing:
  2264   if (mh_jh == NULL || target_jh == NULL) {
  2265     THROW(vmSymbols::java_lang_InternalError());
  2267   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2268   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2270   // Early returns out of this method leave the AMH in an unfinished state.
  2271   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2273   MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
  2275 JVM_END
  2277 // method type forms
  2278 JVM_ENTRY(void, MHI_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
  2279   if (erased_jh == NULL)  return;
  2280   if (TraceMethodHandles) {
  2281     tty->print("creating MethodType form ");
  2282     if (WizardMode || Verbose) {   // Warning: this calls Java code on the MH!
  2283       // call Object.toString()
  2284       symbolOop name = vmSymbols::toString_name(), sig = vmSymbols::void_string_signature();
  2285       JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
  2286       JavaValue result(T_OBJECT);
  2287       JavaCalls::call_virtual(&result, SystemDictionary::Object_klass(), name, sig,
  2288                               &args, CHECK);
  2289       Handle str(THREAD, (oop)result.get_jobject());
  2290       java_lang_String::print(str, tty);
  2292     tty->cr();
  2295 JVM_END
  2297 // debugging and reflection
  2298 JVM_ENTRY(jobject, MHI_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
  2299   Handle mh(THREAD, JNIHandles::resolve(mh_jh));
  2300   if (!java_dyn_MethodHandle::is_instance(mh())) {
  2301     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
  2303   oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
  2304   return JNIHandles::make_local(THREAD, target);
  2306 JVM_END
  2308 JVM_ENTRY(jint, MHI_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  2309   switch (which) {
  2310   case MethodHandles::GC_JVM_PUSH_LIMIT:
  2311     guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
  2312               "MethodHandlePushLimit parameter must be in valid range");
  2313     return MethodHandlePushLimit;
  2314   case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
  2315     // return number of words per slot, signed according to stack direction
  2316     return MethodHandles::stack_move_unit();
  2317   case MethodHandles::GC_CONV_OP_IMPLEMENTED_MASK:
  2318     return MethodHandles::adapter_conversion_ops_supported_mask();
  2320   return 0;
  2322 JVM_END
  2324 #ifndef PRODUCT
  2325 #define EACH_NAMED_CON(template) \
  2326     template(MethodHandles,GC_JVM_PUSH_LIMIT) \
  2327     template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) \
  2328     template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
  2329     template(MethodHandles,ETF_DIRECT_HANDLE) \
  2330     template(MethodHandles,ETF_METHOD_NAME) \
  2331     template(MethodHandles,ETF_REFLECT_METHOD) \
  2332     template(sun_dyn_MemberName,MN_IS_METHOD) \
  2333     template(sun_dyn_MemberName,MN_IS_CONSTRUCTOR) \
  2334     template(sun_dyn_MemberName,MN_IS_FIELD) \
  2335     template(sun_dyn_MemberName,MN_IS_TYPE) \
  2336     template(sun_dyn_MemberName,MN_SEARCH_SUPERCLASSES) \
  2337     template(sun_dyn_MemberName,MN_SEARCH_INTERFACES) \
  2338     template(sun_dyn_MemberName,VM_INDEX_UNINITIALIZED) \
  2339     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_ONLY) \
  2340     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_RAW) \
  2341     template(sun_dyn_AdapterMethodHandle,OP_CHECK_CAST) \
  2342     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
  2343     template(sun_dyn_AdapterMethodHandle,OP_REF_TO_PRIM) \
  2344     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_REF) \
  2345     template(sun_dyn_AdapterMethodHandle,OP_SWAP_ARGS) \
  2346     template(sun_dyn_AdapterMethodHandle,OP_ROT_ARGS) \
  2347     template(sun_dyn_AdapterMethodHandle,OP_DUP_ARGS) \
  2348     template(sun_dyn_AdapterMethodHandle,OP_DROP_ARGS) \
  2349     template(sun_dyn_AdapterMethodHandle,OP_COLLECT_ARGS) \
  2350     template(sun_dyn_AdapterMethodHandle,OP_SPREAD_ARGS) \
  2351     template(sun_dyn_AdapterMethodHandle,OP_FLYBY) \
  2352     template(sun_dyn_AdapterMethodHandle,OP_RICOCHET) \
  2353     template(sun_dyn_AdapterMethodHandle,CONV_OP_LIMIT) \
  2354     template(sun_dyn_AdapterMethodHandle,CONV_OP_MASK) \
  2355     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_MASK) \
  2356     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
  2357     template(sun_dyn_AdapterMethodHandle,CONV_OP_SHIFT) \
  2358     template(sun_dyn_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
  2359     template(sun_dyn_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
  2360     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
  2361     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
  2362     /*end*/
  2364 #define ONE_PLUS(scope,value) 1+
  2365 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
  2366 #define VALUE_COMMA(scope,value) scope::value,
  2367 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
  2368 #define STRING_NULL(scope,value) #value "\0"
  2369 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
  2371 #undef ONE_PLUS
  2372 #undef VALUE_COMMA
  2373 #undef STRING_NULL
  2374 #undef EACH_NAMED_CON
  2375 #endif
  2377 JVM_ENTRY(jint, MHI_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
  2378 #ifndef PRODUCT
  2379   if (which >= 0 && which < con_value_count) {
  2380     int con = con_values[which];
  2381     objArrayOop box = (objArrayOop) JNIHandles::resolve(box_jh);
  2382     if (box != NULL && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
  2383       const char* str = &con_names[0];
  2384       for (int i = 0; i < which; i++)
  2385         str += strlen(str) + 1;   // skip name and null
  2386       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);
  2387       box->obj_at_put(0, name);
  2389     return con;
  2391 #endif
  2392   return 0;
  2394 JVM_END
  2396 // void init(MemberName self, AccessibleObject ref)
  2397 JVM_ENTRY(void, MHI_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
  2398   if (mname_jh == NULL || target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2399   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2400   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2401   MethodHandles::init_MemberName(mname(), target_oop);
  2403 JVM_END
  2405 // void expand(MemberName self)
  2406 JVM_ENTRY(void, MHI_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  2407   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2408   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2409   MethodHandles::expand_MemberName(mname, 0, CHECK);
  2411 JVM_END
  2413 // void resolve(MemberName self, Class<?> caller)
  2414 JVM_ENTRY(void, MHI_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  2415   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2416   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2418   // The trusted Java code that calls this method should already have performed
  2419   // access checks on behalf of the given caller.  But, we can verify this.
  2420   if (VerifyMethodHandles && caller_jh != NULL) {
  2421     klassOop reference_klass = java_lang_Class::as_klassOop(sun_dyn_MemberName::clazz(mname()));
  2422     if (reference_klass != NULL) {
  2423       // Emulate LinkResolver::check_klass_accessability.
  2424       klassOop caller = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh));
  2425       if (!Reflection::verify_class_access(caller,
  2426                                            reference_klass,
  2427                                            true)) {
  2428         THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(reference_klass)->external_name());
  2433   MethodHandles::resolve_MemberName(mname, CHECK);
  2435 JVM_END
  2437 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2438 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2439 JVM_ENTRY(jint, MHI_getMembers(JNIEnv *env, jobject igcls,
  2440                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
  2441                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  2442   if (clazz_jh == NULL || results_jh == NULL)  return -1;
  2443   klassOop k_oop = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh));
  2445   objArrayOop results = (objArrayOop) JNIHandles::resolve(results_jh);
  2446   if (results == NULL || !results->is_objArray())       return -1;
  2448   symbolOop name = NULL, sig = NULL;
  2449   if (name_jh != NULL) {
  2450     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
  2451     if (name == NULL)  return 0; // a match is not possible
  2453   if (sig_jh != NULL) {
  2454     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
  2455     if (sig == NULL)  return 0; // a match is not possible
  2458   klassOop caller = NULL;
  2459   if (caller_jh != NULL) {
  2460     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
  2461     if (!java_lang_Class::is_instance(caller_oop))  return -1;
  2462     caller = java_lang_Class::as_klassOop(caller_oop);
  2465   if (name != NULL && sig != NULL && results != NULL) {
  2466     // try a direct resolve
  2467     // %%% TO DO
  2470   int res = MethodHandles::find_MemberNames(k_oop, name, sig, mflags,
  2471                                             caller, skip, results);
  2472   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  2473   return res;
  2475 JVM_END
  2477 JVM_ENTRY(void, MHI_registerBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh, jobject bsm_jh)) {
  2478   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2479   if (!AllowTransitionalJSR292) {
  2480     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  2481               "registerBootstrapMethod is only supported in JSR 292 EDR");
  2483   ik->link_class(CHECK);
  2484   if (!java_dyn_MethodHandle::is_instance(JNIHandles::resolve(bsm_jh))) {
  2485     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "method handle");
  2487   const char* err = NULL;
  2488   if (ik->is_initialized() || ik->is_in_error_state()) {
  2489     err = "too late: class is already initialized";
  2490   } else {
  2491     ObjectLocker ol(ik, THREAD);  // note:  this should be a recursive lock
  2492     if (ik->is_not_initialized() ||
  2493         (ik->is_being_initialized() && ik->is_reentrant_initialization(THREAD))) {
  2494       if (ik->bootstrap_method() != NULL) {
  2495         err = "class is already equipped with a bootstrap method";
  2496       } else {
  2497         ik->set_bootstrap_method(JNIHandles::resolve_non_null(bsm_jh));
  2498         err = NULL;
  2500     } else {
  2501       err = "class is already initialized";
  2502       if (ik->is_being_initialized())
  2503         err = "class is already being initialized in a different thread";
  2506   if (err != NULL) {
  2507     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), err);
  2510 JVM_END
  2512 JVM_ENTRY(jobject, MHI_getBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh)) {
  2513   instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD);
  2514   return JNIHandles::make_local(THREAD, ik->bootstrap_method());
  2516 JVM_END
  2518 JVM_ENTRY(void, MHI_setCallSiteTarget(JNIEnv *env, jobject igcls, jobject site_jh, jobject target_jh)) {
  2519   // No special action required, yet.
  2520   oop site_oop = JNIHandles::resolve(site_jh);
  2521   if (!java_dyn_CallSite::is_instance(site_oop))
  2522     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "not a CallSite");
  2523   java_dyn_CallSite::set_target(site_oop, JNIHandles::resolve(target_jh));
  2525 JVM_END
  2528 /// JVM_RegisterMethodHandleMethods
  2530 #define ADR "J"
  2532 #define LANG "Ljava/lang/"
  2533 #define JDYN "Ljava/dyn/"
  2534 #define IDYN "Lsun/dyn/"
  2536 #define OBJ   LANG"Object;"
  2537 #define CLS   LANG"Class;"
  2538 #define STRG  LANG"String;"
  2539 #define CST   JDYN"CallSite;"
  2540 #define MT    JDYN"MethodType;"
  2541 #define MH    JDYN"MethodHandle;"
  2542 #define MHI   IDYN"MethodHandleImpl;"
  2543 #define MEM   IDYN"MemberName;"
  2544 #define AMH   IDYN"AdapterMethodHandle;"
  2545 #define BMH   IDYN"BoundMethodHandle;"
  2546 #define DMH   IDYN"DirectMethodHandle;"
  2548 #define CC (char*)  /*cast a literal from (const char*)*/
  2549 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
  2551 // These are the native methods on sun.dyn.MethodHandleNatives.
  2552 static JNINativeMethod methods[] = {
  2553   // void init(MemberName self, AccessibleObject ref)
  2554   {CC"init",                    CC"("AMH""MH"I)V",              FN_PTR(MHI_init_AMH)},
  2555   {CC"init",                    CC"("BMH""OBJ"I)V",             FN_PTR(MHI_init_BMH)},
  2556   {CC"init",                    CC"("DMH""OBJ"Z"CLS")V",        FN_PTR(MHI_init_DMH)},
  2557   {CC"init",                    CC"("MT")V",                    FN_PTR(MHI_init_MT)},
  2558   {CC"init",                    CC"("MEM""OBJ")V",              FN_PTR(MHI_init_Mem)},
  2559   {CC"expand",                  CC"("MEM")V",                   FN_PTR(MHI_expand_Mem)},
  2560   {CC"resolve",                 CC"("MEM""CLS")V",              FN_PTR(MHI_resolve_Mem)},
  2561   {CC"getTarget",               CC"("MH"I)"OBJ,                 FN_PTR(MHI_getTarget)},
  2562   {CC"getConstant",             CC"(I)I",                       FN_PTR(MHI_getConstant)},
  2563   //  static native int getNamedCon(int which, Object[] name)
  2564   {CC"getNamedCon",             CC"(I["OBJ")I",                 FN_PTR(MHI_getNamedCon)},
  2565   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2566   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2567   {CC"getMembers",              CC"("CLS""STRG""STRG"I"CLS"I["MEM")I",  FN_PTR(MHI_getMembers)}
  2568 };
  2570 // More entry points specifically for EnableInvokeDynamic.
  2571 static JNINativeMethod methods2[] = {
  2572   {CC"registerBootstrap",       CC"("CLS MH")V",                FN_PTR(MHI_registerBootstrap)},
  2573   {CC"getBootstrap",            CC"("CLS")"MH,                  FN_PTR(MHI_getBootstrap)},
  2574   {CC"setCallSiteTarget",       CC"("CST MH")V",                FN_PTR(MHI_setCallSiteTarget)}
  2575 };
  2578 // This one function is exported, used by NativeLookup.
  2580 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
  2581   assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
  2583   // note: this explicit warning-producing stuff will be replaced by auto-detection of the JSR 292 classes
  2585   if (!EnableMethodHandles) {
  2586     warning("JSR 292 method handles are disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles to enable.");
  2587     return;  // bind nothing
  2590   bool enable_MH = true;
  2593     ThreadToNativeFromVM ttnfv(thread);
  2595     int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
  2596     if (env->ExceptionOccurred()) {
  2597       MethodHandles::set_enabled(false);
  2598       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2599       enable_MH = false;
  2600       env->ExceptionClear();
  2604   if (enable_MH) {
  2605     KlassHandle MHI_klass = SystemDictionaryHandles::MethodHandleImpl_klass();
  2606     if (MHI_klass.not_null()) {
  2607       symbolHandle raiseException_name = oopFactory::new_symbol_handle("raiseException", CHECK);
  2608       symbolHandle raiseException_sig  = oopFactory::new_symbol_handle("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK);
  2609       methodOop raiseException_method  = instanceKlass::cast(MHI_klass->as_klassOop())
  2610                     ->find_method(raiseException_name(), raiseException_sig());
  2611       if (raiseException_method != NULL && raiseException_method->is_static()) {
  2612         MethodHandles::set_raise_exception_method(raiseException_method);
  2613       } else {
  2614         warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2615         enable_MH = false;
  2620   if (enable_MH) {
  2621     MethodHandles::set_enabled(true);
  2624   if (!EnableInvokeDynamic) {
  2625     warning("JSR 292 invokedynamic is disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic to enable.");
  2626     return;  // bind nothing
  2630     ThreadToNativeFromVM ttnfv(thread);
  2632     int status = env->RegisterNatives(MHN_class, methods2, sizeof(methods2)/sizeof(JNINativeMethod));
  2633     if (env->ExceptionOccurred()) {
  2634       MethodHandles::set_enabled(false);
  2635       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2636       env->ExceptionClear();
  2637     } else {
  2638       MethodHandles::set_enabled(true);
  2642 JVM_END

mercurial