src/share/vm/prims/methodHandles.cpp

Mon, 14 Dec 2009 13:26:29 -0700

author
dcubed
date
Mon, 14 Dec 2009 13:26:29 -0700
changeset 1557
dcb15a6f342d
parent 1494
389049f3f393
child 1573
dd57230ba8fe
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 /*
    26  * JSR 292 reference implementation: method handles
    27  */
    29 #include "incls/_precompiled.incl"
    30 #include "incls/_methodHandles.cpp.incl"
    32 bool MethodHandles::_enabled = false; // set true after successful native linkage
    34 MethodHandleEntry* MethodHandles::_entries[MethodHandles::_EK_LIMIT] = {NULL};
    35 const char*        MethodHandles::_entry_names[_EK_LIMIT+1] = {
    36   "raise_exception",
    37   "invokestatic",               // how a MH emulates invokestatic
    38   "invokespecial",              // ditto for the other invokes...
    39   "invokevirtual",
    40   "invokeinterface",
    41   "bound_ref",                  // these are for BMH...
    42   "bound_int",
    43   "bound_long",
    44   "bound_ref_direct",           // (direct versions have a direct methodOop)
    45   "bound_int_direct",
    46   "bound_long_direct",
    48   // starting at _adapter_mh_first:
    49   "adapter_retype_only",       // these are for AMH...
    50   "adapter_retype_raw",
    51   "adapter_check_cast",
    52   "adapter_prim_to_prim",
    53   "adapter_ref_to_prim",
    54   "adapter_prim_to_ref",
    55   "adapter_swap_args",
    56   "adapter_rot_args",
    57   "adapter_dup_args",
    58   "adapter_drop_args",
    59   "adapter_collect_args",
    60   "adapter_spread_args",
    61   "adapter_flyby",
    62   "adapter_ricochet",
    64   // optimized adapter types:
    65   "adapter_swap_args/1",
    66   "adapter_swap_args/2",
    67   "adapter_rot_args/1,up",
    68   "adapter_rot_args/1,down",
    69   "adapter_rot_args/2,up",
    70   "adapter_rot_args/2,down",
    71   "adapter_prim_to_prim/i2i",
    72   "adapter_prim_to_prim/l2i",
    73   "adapter_prim_to_prim/d2f",
    74   "adapter_prim_to_prim/i2l",
    75   "adapter_prim_to_prim/f2d",
    76   "adapter_ref_to_prim/unboxi",
    77   "adapter_ref_to_prim/unboxl",
    78   "adapter_spread_args/0",
    79   "adapter_spread_args/1",
    80   "adapter_spread_args/more",
    82   NULL
    83 };
    85 jobject MethodHandles::_raise_exception_method;
    87 #ifdef ASSERT
    88 bool MethodHandles::spot_check_entry_names() {
    89   assert(!strcmp(entry_name(_invokestatic_mh), "invokestatic"), "");
    90   assert(!strcmp(entry_name(_bound_ref_mh), "bound_ref"), "");
    91   assert(!strcmp(entry_name(_adapter_retype_only), "adapter_retype_only"), "");
    92   assert(!strcmp(entry_name(_adapter_ricochet), "adapter_ricochet"), "");
    93   assert(!strcmp(entry_name(_adapter_opt_unboxi), "adapter_ref_to_prim/unboxi"), "");
    94   return true;
    95 }
    96 #endif
    98 void MethodHandles::set_enabled(bool z) {
    99   if (_enabled != z) {
   100     guarantee(z && EnableMethodHandles, "can only enable once, and only if -XX:+EnableMethodHandles");
   101     _enabled = z;
   102   }
   103 }
   105 // Note: A method which does not have a TRAPS argument cannot block in the GC
   106 // or throw exceptions.  Such methods are used in this file to do something quick
   107 // and local, like parse a data structure.  For speed, such methods work on plain
   108 // oops, not handles.  Trapping methods uniformly operate on handles.
   110 methodOop MethodHandles::decode_vmtarget(oop vmtarget, int vmindex, oop mtype,
   111                                          klassOop& receiver_limit_result, int& decode_flags_result) {
   112   if (vmtarget == NULL)  return NULL;
   113   assert(methodOopDesc::nonvirtual_vtable_index < 0, "encoding");
   114   if (vmindex < 0) {
   115     // this DMH performs no dispatch; it is directly bound to a methodOop
   116     // A MemberName may either be directly bound to a methodOop,
   117     // or it may use the klass/index form; both forms mean the same thing.
   118     methodOop m = decode_methodOop(methodOop(vmtarget), decode_flags_result);
   119     if ((decode_flags_result & _dmf_has_receiver) != 0
   120         && java_dyn_MethodType::is_instance(mtype)) {
   121       // Extract receiver type restriction from mtype.ptypes[0].
   122       objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype);
   123       oop ptype0 = (ptypes == NULL || ptypes->length() < 1) ? oop(NULL) : ptypes->obj_at(0);
   124       if (java_lang_Class::is_instance(ptype0))
   125         receiver_limit_result = java_lang_Class::as_klassOop(ptype0);
   126     }
   127     if (vmindex == methodOopDesc::nonvirtual_vtable_index) {
   128       // this DMH can be an "invokespecial" version
   129       decode_flags_result &= ~_dmf_does_dispatch;
   130     } else {
   131       assert(vmindex == methodOopDesc::invalid_vtable_index, "random vmindex?");
   132     }
   133     return m;
   134   } else {
   135     decode_flags_result |= MethodHandles::_dmf_does_dispatch;
   136     assert(vmtarget->is_klass(), "must be class or interface");
   137     receiver_limit_result = (klassOop)vmtarget;
   138     Klass* tk = Klass::cast((klassOop)vmtarget);
   139     if (tk->is_interface()) {
   140       // an itable linkage is <interface, itable index>
   141       decode_flags_result |= MethodHandles::_dmf_from_interface;
   142       return klassItable::method_for_itable_index((klassOop)vmtarget, vmindex);
   143     } else {
   144       if (!tk->oop_is_instance())
   145         tk = instanceKlass::cast(SystemDictionary::object_klass());
   146       return ((instanceKlass*)tk)->method_at_vtable(vmindex);
   147     }
   148   }
   149 }
   151 // MemberName and DirectMethodHandle have the same linkage to the JVM internals.
   152 // (MemberName is the non-operational name used for queries and setup.)
   154 methodOop MethodHandles::decode_DirectMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   155   oop vmtarget = sun_dyn_DirectMethodHandle::vmtarget(mh);
   156   int vmindex  = sun_dyn_DirectMethodHandle::vmindex(mh);
   157   oop mtype    = sun_dyn_DirectMethodHandle::type(mh);
   158   return decode_vmtarget(vmtarget, vmindex, mtype, receiver_limit_result, decode_flags_result);
   159 }
   161 methodOop MethodHandles::decode_BoundMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   162   assert(sun_dyn_BoundMethodHandle::is_instance(mh), "");
   163   assert(mh->klass() != SystemDictionary::AdapterMethodHandle_klass(), "");
   164   for (oop bmh = mh;;) {
   165     // Bound MHs can be stacked to bind several arguments.
   166     oop target = java_dyn_MethodHandle::vmtarget(bmh);
   167     if (target == NULL)  return NULL;
   168     decode_flags_result |= MethodHandles::_dmf_binds_argument;
   169     klassOop tk = target->klass();
   170     if (tk == SystemDictionary::BoundMethodHandle_klass()) {
   171       bmh = target;
   172       continue;
   173     } else {
   174       if (java_dyn_MethodHandle::is_subclass(tk)) {
   175         //assert(tk == SystemDictionary::DirectMethodHandle_klass(), "end of BMH chain must be DMH");
   176         return decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   177       } else {
   178         // Optimized case:  binding a receiver to a non-dispatched DMH
   179         // short-circuits directly to the methodOop.
   180         // (It might be another argument besides a receiver also.)
   181         assert(target->is_method(), "must be a simple method");
   182         methodOop m = (methodOop) target;
   183         decode_flags_result |= MethodHandles::_dmf_binds_method;
   184         return m;
   185       }
   186     }
   187   }
   188 }
   190 methodOop MethodHandles::decode_AdapterMethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   191   assert(mh->klass() == SystemDictionary::AdapterMethodHandle_klass(), "");
   192   for (oop amh = mh;;) {
   193     // Adapter MHs can be stacked to convert several arguments.
   194     int conv_op = adapter_conversion_op(sun_dyn_AdapterMethodHandle::conversion(amh));
   195     decode_flags_result |= (_dmf_adapter_lsb << conv_op) & _DMF_ADAPTER_MASK;
   196     oop target = java_dyn_MethodHandle::vmtarget(amh);
   197     if (target == NULL)  return NULL;
   198     klassOop tk = target->klass();
   199     if (tk == SystemDictionary::AdapterMethodHandle_klass()) {
   200       amh = target;
   201       continue;
   202     } else {
   203       // must be a BMH (which will bind some more arguments) or a DMH (for the final call)
   204       return MethodHandles::decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
   205     }
   206   }
   207 }
   209 methodOop MethodHandles::decode_MethodHandle(oop mh, klassOop& receiver_limit_result, int& decode_flags_result) {
   210   if (mh == NULL)  return NULL;
   211   klassOop mhk = mh->klass();
   212   assert(java_dyn_MethodHandle::is_subclass(mhk), "must be a MethodHandle");
   213   if (mhk == SystemDictionary::DirectMethodHandle_klass()) {
   214     return decode_DirectMethodHandle(mh, receiver_limit_result, decode_flags_result);
   215   } else if (mhk == SystemDictionary::BoundMethodHandle_klass()) {
   216     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   217   } else if (mhk == SystemDictionary::AdapterMethodHandle_klass()) {
   218     return decode_AdapterMethodHandle(mh, receiver_limit_result, decode_flags_result);
   219   } else if (sun_dyn_BoundMethodHandle::is_subclass(mhk)) {
   220     // could be a JavaMethodHandle (but not an adapter MH)
   221     return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
   222   } else {
   223     assert(false, "cannot parse this MH");
   224     return NULL;              // random MH?
   225   }
   226 }
   228 methodOop MethodHandles::decode_methodOop(methodOop m, int& decode_flags_result) {
   229   assert(m->is_method(), "");
   230   if (m->is_static()) {
   231     // check that signature begins '(L' or '([' (not '(I', '()', etc.)
   232     symbolOop sig = m->signature();
   233     BasicType recv_bt = char2type(sig->byte_at(1));
   234     // Note: recv_bt might be T_ILLEGAL if byte_at(2) is ')'
   235     assert(sig->byte_at(0) == '(', "must be method sig");
   236     if (recv_bt == T_OBJECT || recv_bt == T_ARRAY)
   237       decode_flags_result |= _dmf_has_receiver;
   238   } else {
   239     // non-static method
   240     decode_flags_result |= _dmf_has_receiver;
   241     if (!m->can_be_statically_bound() && !m->is_initializer()) {
   242       decode_flags_result |= _dmf_does_dispatch;
   243       if (Klass::cast(m->method_holder())->is_interface())
   244         decode_flags_result |= _dmf_from_interface;
   245     }
   246   }
   247   return m;
   248 }
   251 // A trusted party is handing us a cookie to determine a method.
   252 // Let's boil it down to the method oop they really want.
   253 methodOop MethodHandles::decode_method(oop x, klassOop& receiver_limit_result, int& decode_flags_result) {
   254   decode_flags_result = 0;
   255   receiver_limit_result = NULL;
   256   klassOop xk = x->klass();
   257   if (xk == Universe::methodKlassObj()) {
   258     return decode_methodOop((methodOop) x, decode_flags_result);
   259   } else if (xk == SystemDictionary::MemberName_klass()) {
   260     // Note: This only works if the MemberName has already been resolved.
   261     return decode_MemberName(x, receiver_limit_result, decode_flags_result);
   262   } else if (java_dyn_MethodHandle::is_subclass(xk)) {
   263     return decode_MethodHandle(x, receiver_limit_result, decode_flags_result);
   264   } else if (xk == SystemDictionary::reflect_method_klass()) {
   265     oop clazz  = java_lang_reflect_Method::clazz(x);
   266     int slot   = java_lang_reflect_Method::slot(x);
   267     klassOop k = java_lang_Class::as_klassOop(clazz);
   268     if (k != NULL && Klass::cast(k)->oop_is_instance())
   269       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   270                               decode_flags_result);
   271   } else if (xk == SystemDictionary::reflect_constructor_klass()) {
   272     oop clazz  = java_lang_reflect_Constructor::clazz(x);
   273     int slot   = java_lang_reflect_Constructor::slot(x);
   274     klassOop k = java_lang_Class::as_klassOop(clazz);
   275     if (k != NULL && Klass::cast(k)->oop_is_instance())
   276       return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
   277                               decode_flags_result);
   278   } else {
   279     // unrecognized object
   280     assert(!x->is_method(), "already checked");
   281     assert(!sun_dyn_MemberName::is_instance(x), "already checked");
   282   }
   283   return NULL;
   284 }
   287 int MethodHandles::decode_MethodHandle_stack_pushes(oop mh) {
   288   if (mh->klass() == SystemDictionary::DirectMethodHandle_klass())
   289     return 0;                   // no push/pop
   290   int this_vmslots = java_dyn_MethodHandle::vmslots(mh);
   291   int last_vmslots = 0;
   292   oop last_mh = mh;
   293   for (;;) {
   294     oop target = java_dyn_MethodHandle::vmtarget(last_mh);
   295     if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   296       last_vmslots = java_dyn_MethodHandle::vmslots(target);
   297       break;
   298     } else if (!java_dyn_MethodHandle::is_instance(target)) {
   299       // might be klass or method
   300       assert(target->is_method(), "must get here with a direct ref to method");
   301       last_vmslots = methodOop(target)->size_of_parameters();
   302       break;
   303     }
   304     last_mh = target;
   305   }
   306   // If I am called with fewer VM slots than my ultimate callee,
   307   // it must be that I push the additionally needed slots.
   308   // Likewise if am called with more VM slots, I will pop them.
   309   return (last_vmslots - this_vmslots);
   310 }
   313 // MemberName support
   315 // import sun_dyn_MemberName.*
   316 enum {
   317   IS_METHOD      = sun_dyn_MemberName::MN_IS_METHOD,
   318   IS_CONSTRUCTOR = sun_dyn_MemberName::MN_IS_CONSTRUCTOR,
   319   IS_FIELD       = sun_dyn_MemberName::MN_IS_FIELD,
   320   IS_TYPE        = sun_dyn_MemberName::MN_IS_TYPE,
   321   SEARCH_SUPERCLASSES = sun_dyn_MemberName::MN_SEARCH_SUPERCLASSES,
   322   SEARCH_INTERFACES   = sun_dyn_MemberName::MN_SEARCH_INTERFACES,
   323   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE,
   324   VM_INDEX_UNINITIALIZED = sun_dyn_MemberName::VM_INDEX_UNINITIALIZED
   325 };
   327 void MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
   328   if (target_oop->klass() == SystemDictionary::reflect_field_klass()) {
   329     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
   330     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
   331     int mods  = java_lang_reflect_Field::modifiers(target_oop);
   332     klassOop k = java_lang_Class::as_klassOop(clazz);
   333     int offset = instanceKlass::cast(k)->offset_from_fields(slot);
   334     init_MemberName(mname_oop, k, accessFlags_from(mods), offset);
   335   } else {
   336     int decode_flags = 0; klassOop receiver_limit = NULL;
   337     methodOop m = MethodHandles::decode_method(target_oop,
   338                                                receiver_limit, decode_flags);
   339     bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   340     init_MemberName(mname_oop, m, do_dispatch);
   341   }
   342 }
   344 void MethodHandles::init_MemberName(oop mname_oop, methodOop m, bool do_dispatch) {
   345   int flags = ((m->is_initializer() ? IS_CONSTRUCTOR : IS_METHOD)
   346                | (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS ));
   347   oop vmtarget = m;
   348   int vmindex  = methodOopDesc::invalid_vtable_index;  // implies no info yet
   349   if (!do_dispatch || (flags & IS_CONSTRUCTOR) || m->can_be_statically_bound())
   350     vmindex = methodOopDesc::nonvirtual_vtable_index; // implies never any dispatch
   351   assert(vmindex != VM_INDEX_UNINITIALIZED, "Java sentinel value");
   352   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   353   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   354   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   355 }
   357 void MethodHandles::init_MemberName(oop mname_oop, klassOop field_holder, AccessFlags mods, int offset) {
   358   int flags = (IS_FIELD | (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS ));
   359   oop vmtarget = field_holder;
   360   int vmindex  = offset;  // implies no info yet
   361   assert(vmindex != VM_INDEX_UNINITIALIZED, "bad alias on vmindex");
   362   sun_dyn_MemberName::set_vmtarget(mname_oop, vmtarget);
   363   sun_dyn_MemberName::set_vmindex(mname_oop,  vmindex);
   364   sun_dyn_MemberName::set_flags(mname_oop,    flags);
   365 }
   368 methodOop MethodHandles::decode_MemberName(oop mname, klassOop& receiver_limit_result, int& decode_flags_result) {
   369   int flags  = sun_dyn_MemberName::flags(mname);
   370   if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) == 0)  return NULL;  // not invocable
   371   oop vmtarget = sun_dyn_MemberName::vmtarget(mname);
   372   int vmindex  = sun_dyn_MemberName::vmindex(mname);
   373   if (vmindex == VM_INDEX_UNINITIALIZED)  return NULL; // not resolved
   374   methodOop m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit_result, decode_flags_result);
   375   oop clazz = sun_dyn_MemberName::clazz(mname);
   376   if (clazz != NULL && java_lang_Class::is_instance(clazz)) {
   377     klassOop klass = java_lang_Class::as_klassOop(clazz);
   378     if (klass != NULL)  receiver_limit_result = klass;
   379   }
   380   return m;
   381 }
   383 // An unresolved member name is a mere symbolic reference.
   384 // Resolving it plants a vmtarget/vmindex in it,
   385 // which refers dirctly to JVM internals.
   386 void MethodHandles::resolve_MemberName(Handle mname, TRAPS) {
   387   assert(sun_dyn_MemberName::is_instance(mname()), "");
   388 #ifdef ASSERT
   389   // If this assert throws, renegotiate the sentinel value used by the Java code,
   390   // so that it is distinct from any valid vtable index value, and any special
   391   // values defined in methodOopDesc::VtableIndexFlag.
   392   // The point of the slop is to give the Java code and the JVM some room
   393   // to independently specify sentinel values.
   394   const int sentinel_slop  = 10;
   395   const int sentinel_limit = methodOopDesc::highest_unused_vtable_index_value - sentinel_slop;
   396   assert(VM_INDEX_UNINITIALIZED < sentinel_limit, "Java sentinel != JVM sentinels");
   397 #endif
   398   if (sun_dyn_MemberName::vmindex(mname()) != VM_INDEX_UNINITIALIZED)
   399     return;  // already resolved
   400   oop defc_oop = sun_dyn_MemberName::clazz(mname());
   401   oop name_str = sun_dyn_MemberName::name(mname());
   402   oop type_str = sun_dyn_MemberName::type(mname());
   403   int flags    = sun_dyn_MemberName::flags(mname());
   405   if (defc_oop == NULL || name_str == NULL || type_str == NULL) {
   406     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve");
   407   }
   408   klassOop defc_klassOop = java_lang_Class::as_klassOop(defc_oop);
   409   defc_oop = NULL;  // safety
   410   if (defc_klassOop == NULL)  return;  // a primitive; no resolution possible
   411   if (!Klass::cast(defc_klassOop)->oop_is_instance()) {
   412     if (!Klass::cast(defc_klassOop)->oop_is_array())  return;
   413     defc_klassOop = SystemDictionary::object_klass();
   414   }
   415   instanceKlassHandle defc(THREAD, defc_klassOop);
   416   defc_klassOop = NULL;  // safety
   417   if (defc.is_null()) {
   418     THROW_MSG(vmSymbols::java_lang_InternalError(), "primitive class");
   419   }
   420   defc->link_class(CHECK);
   422   // convert the external string name to an internal symbol
   423   symbolHandle name(THREAD, java_lang_String::as_symbol_or_null(name_str));
   424   if (name.is_null())  return;  // no such name
   425   name_str = NULL;  // safety
   427   // convert the external string or reflective type to an internal signature
   428   bool force_signature = (name() == vmSymbols::invoke_name());
   429   symbolHandle type; {
   430     symbolOop type_sym = NULL;
   431     if (java_dyn_MethodType::is_instance(type_str)) {
   432       type_sym = java_dyn_MethodType::as_signature(type_str, force_signature, CHECK);
   433     } else if (java_lang_Class::is_instance(type_str)) {
   434       type_sym = java_lang_Class::as_signature(type_str, force_signature, CHECK);
   435     } else if (java_lang_String::is_instance(type_str)) {
   436       if (force_signature) {
   437         type     = java_lang_String::as_symbol(type_str, CHECK);
   438       } else {
   439         type_sym = java_lang_String::as_symbol_or_null(type_str);
   440       }
   441     } else {
   442       THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized type");
   443     }
   444     if (type_sym != NULL)
   445       type = symbolHandle(THREAD, type_sym);
   446   }
   447   if (type.is_null())  return;  // no such signature exists in the VM
   448   type_str = NULL; // safety
   450   // Time to do the lookup.
   451   switch (flags & ALL_KINDS) {
   452   case IS_METHOD:
   453     {
   454       CallInfo result;
   455       {
   456         EXCEPTION_MARK;
   457         if ((flags & JVM_ACC_STATIC) != 0) {
   458           LinkResolver::resolve_static_call(result,
   459                         defc, name, type, KlassHandle(), false, false, THREAD);
   460         } else if (defc->is_interface()) {
   461           LinkResolver::resolve_interface_call(result, Handle(), defc,
   462                         defc, name, type, KlassHandle(), false, false, THREAD);
   463         } else {
   464           LinkResolver::resolve_virtual_call(result, Handle(), defc,
   465                         defc, name, type, KlassHandle(), false, false, THREAD);
   466         }
   467         if (HAS_PENDING_EXCEPTION) {
   468           CLEAR_PENDING_EXCEPTION;
   469           return;
   470         }
   471       }
   472       methodHandle m = result.resolved_method();
   473       oop vmtarget = NULL;
   474       int vmindex = methodOopDesc::nonvirtual_vtable_index;
   475       if (defc->is_interface()) {
   476         vmindex = klassItable::compute_itable_index(m());
   477         assert(vmindex >= 0, "");
   478       } else if (result.has_vtable_index()) {
   479         vmindex = result.vtable_index();
   480         assert(vmindex >= 0, "");
   481       }
   482       assert(vmindex != VM_INDEX_UNINITIALIZED, "");
   483       if (vmindex < 0) {
   484         assert(result.is_statically_bound(), "");
   485         vmtarget = m();
   486       } else {
   487         vmtarget = result.resolved_klass()->as_klassOop();
   488       }
   489       int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   490       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   491       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   492       sun_dyn_MemberName::set_modifiers(mname(), mods);
   493       DEBUG_ONLY(int junk; klassOop junk2);
   494       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   495              "properly stored for later decoding");
   496       return;
   497     }
   498   case IS_CONSTRUCTOR:
   499     {
   500       CallInfo result;
   501       {
   502         EXCEPTION_MARK;
   503         if (name() == vmSymbols::object_initializer_name()) {
   504           LinkResolver::resolve_special_call(result,
   505                         defc, name, type, KlassHandle(), false, THREAD);
   506         } else {
   507           break;                // will throw after end of switch
   508         }
   509         if (HAS_PENDING_EXCEPTION) {
   510           CLEAR_PENDING_EXCEPTION;
   511           return;
   512         }
   513       }
   514       assert(result.is_statically_bound(), "");
   515       methodHandle m = result.resolved_method();
   516       oop vmtarget = m();
   517       int vmindex  = methodOopDesc::nonvirtual_vtable_index;
   518       int mods     = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
   519       sun_dyn_MemberName::set_vmtarget(mname(), vmtarget);
   520       sun_dyn_MemberName::set_vmindex(mname(),  vmindex);
   521       sun_dyn_MemberName::set_modifiers(mname(), mods);
   522       DEBUG_ONLY(int junk; klassOop junk2);
   523       assert(decode_MemberName(mname(), junk2, junk) == result.resolved_method()(),
   524              "properly stored for later decoding");
   525       return;
   526     }
   527   case IS_FIELD:
   528     {
   529       // This is taken from LinkResolver::resolve_field, sans access checks.
   530       fieldDescriptor fd; // find_field initializes fd if found
   531       KlassHandle sel_klass(THREAD, instanceKlass::cast(defc())->find_field(name(), type(), &fd));
   532       // check if field exists; i.e., if a klass containing the field def has been selected
   533       if (sel_klass.is_null())  return;
   534       oop vmtarget = sel_klass->as_klassOop();
   535       int vmindex  = fd.offset();
   536       int mods     = (fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS);
   537       if (vmindex == VM_INDEX_UNINITIALIZED)  break;  // should not happen
   538       sun_dyn_MemberName::set_vmtarget(mname(),  vmtarget);
   539       sun_dyn_MemberName::set_vmindex(mname(),   vmindex);
   540       sun_dyn_MemberName::set_modifiers(mname(), mods);
   541       return;
   542     }
   543   }
   544   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   545 }
   547 // Conversely, a member name which is only initialized from JVM internals
   548 // may have null defc, name, and type fields.
   549 // Resolving it plants a vmtarget/vmindex in it,
   550 // which refers directly to JVM internals.
   551 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
   552   assert(sun_dyn_MemberName::is_instance(mname()), "");
   553   oop vmtarget = sun_dyn_MemberName::vmtarget(mname());
   554   int vmindex  = sun_dyn_MemberName::vmindex(mname());
   555   if (vmtarget == NULL || vmindex == VM_INDEX_UNINITIALIZED) {
   556     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
   557   }
   559   bool have_defc = (sun_dyn_MemberName::clazz(mname()) != NULL);
   560   bool have_name = (sun_dyn_MemberName::name(mname()) != NULL);
   561   bool have_type = (sun_dyn_MemberName::type(mname()) != NULL);
   562   int flags      = sun_dyn_MemberName::flags(mname());
   564   if (suppress != 0) {
   565     if (suppress & _suppress_defc)  have_defc = true;
   566     if (suppress & _suppress_name)  have_name = true;
   567     if (suppress & _suppress_type)  have_type = true;
   568   }
   570   if (have_defc && have_name && have_type)  return;  // nothing needed
   572   switch (flags & ALL_KINDS) {
   573   case IS_METHOD:
   574   case IS_CONSTRUCTOR:
   575     {
   576       klassOop receiver_limit = NULL;
   577       int      decode_flags   = 0;
   578       methodHandle m(THREAD, decode_vmtarget(vmtarget, vmindex, NULL,
   579                                              receiver_limit, decode_flags));
   580       if (m.is_null())  break;
   581       if (!have_defc) {
   582         klassOop defc = m->method_holder();
   583         if (receiver_limit != NULL && receiver_limit != defc
   584             && Klass::cast(receiver_limit)->is_subtype_of(defc))
   585           defc = receiver_limit;
   586         sun_dyn_MemberName::set_clazz(mname(), Klass::cast(defc)->java_mirror());
   587       }
   588       if (!have_name) {
   589         //not java_lang_String::create_from_symbol; let's intern member names
   590         Handle name = StringTable::intern(m->name(), CHECK);
   591         sun_dyn_MemberName::set_name(mname(), name());
   592       }
   593       if (!have_type) {
   594         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
   595         sun_dyn_MemberName::set_type(mname(), type());
   596       }
   597       return;
   598     }
   599   case IS_FIELD:
   600     {
   601       // This is taken from LinkResolver::resolve_field, sans access checks.
   602       if (!vmtarget->is_klass())  break;
   603       if (!Klass::cast((klassOop) vmtarget)->oop_is_instance())  break;
   604       instanceKlassHandle defc(THREAD, (klassOop) vmtarget);
   605       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
   606       fieldDescriptor fd; // find_field initializes fd if found
   607       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
   608         break;                  // cannot expand
   609       if (!have_defc) {
   610         sun_dyn_MemberName::set_clazz(mname(), defc->java_mirror());
   611       }
   612       if (!have_name) {
   613         //not java_lang_String::create_from_symbol; let's intern member names
   614         Handle name = StringTable::intern(fd.name(), CHECK);
   615         sun_dyn_MemberName::set_name(mname(), name());
   616       }
   617       if (!have_type) {
   618         Handle type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
   619         sun_dyn_MemberName::set_type(mname(), type());
   620       }
   621       return;
   622     }
   623   }
   624   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
   625 }
   627 int MethodHandles::find_MemberNames(klassOop k,
   628                                     symbolOop name, symbolOop sig,
   629                                     int mflags, klassOop caller,
   630                                     int skip, objArrayOop results) {
   631   DEBUG_ONLY(No_Safepoint_Verifier nsv);
   632   // this code contains no safepoints!
   634   // %%% take caller into account!
   636   if (k == NULL || !Klass::cast(k)->oop_is_instance())  return -1;
   638   int rfill = 0, rlimit = results->length(), rskip = skip;
   639   // overflow measurement:
   640   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
   642   int match_flags = mflags;
   643   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
   644   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
   645   bool local_only = !(search_superc | search_intfc);
   646   bool classes_only = false;
   648   if (name != NULL) {
   649     if (name->utf8_length() == 0)  return 0; // a match is not possible
   650   }
   651   if (sig != NULL) {
   652     if (sig->utf8_length() == 0)  return 0; // a match is not possible
   653     if (sig->byte_at(0) == '(')
   654       match_flags &= ~(IS_FIELD | IS_TYPE);
   655     else
   656       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
   657   }
   659   if ((match_flags & IS_TYPE) != 0) {
   660     // NYI, and Core Reflection works quite well for this query
   661   }
   663   if ((match_flags & IS_FIELD) != 0) {
   664     for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   665       if (name != NULL && st.name() != name)
   666           continue;
   667       if (sig != NULL && st.signature() != sig)
   668         continue;
   669       // passed the filters
   670       if (rskip > 0) {
   671         --rskip;
   672       } else if (rfill < rlimit) {
   673         oop result = results->obj_at(rfill++);
   674         if (!sun_dyn_MemberName::is_instance(result))
   675           return -99;  // caller bug!
   676         MethodHandles::init_MemberName(result, st.klass()->as_klassOop(), st.access_flags(), st.offset());
   677       } else if (++overflow >= overflow_limit) {
   678         match_flags = 0; break; // got tired of looking at overflow
   679       }
   680     }
   681   }
   683   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
   684     // watch out for these guys:
   685     symbolOop init_name   = vmSymbols::object_initializer_name();
   686     symbolOop clinit_name = vmSymbols::class_initializer_name();
   687     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
   688     bool negate_name_test = false;
   689     // fix name so that it captures the intention of IS_CONSTRUCTOR
   690     if (!(match_flags & IS_METHOD)) {
   691       // constructors only
   692       if (name == NULL) {
   693         name = init_name;
   694       } else if (name != init_name) {
   695         return 0;               // no constructors of this method name
   696       }
   697     } else if (!(match_flags & IS_CONSTRUCTOR)) {
   698       // methods only
   699       if (name == NULL) {
   700         name = init_name;
   701         negate_name_test = true; // if we see the name, we *omit* the entry
   702       } else if (name == init_name) {
   703         return 0;               // no methods of this constructor name
   704       }
   705     } else {
   706       // caller will accept either sort; no need to adjust name
   707     }
   708     for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
   709       methodOop m = st.method();
   710       symbolOop m_name = m->name();
   711       if (m_name == clinit_name)
   712         continue;
   713       if (name != NULL && ((m_name != name) ^ negate_name_test))
   714           continue;
   715       if (sig != NULL && m->signature() != sig)
   716         continue;
   717       // passed the filters
   718       if (rskip > 0) {
   719         --rskip;
   720       } else if (rfill < rlimit) {
   721         oop result = results->obj_at(rfill++);
   722         if (!sun_dyn_MemberName::is_instance(result))
   723           return -99;  // caller bug!
   724         MethodHandles::init_MemberName(result, m, true);
   725       } else if (++overflow >= overflow_limit) {
   726         match_flags = 0; break; // got tired of looking at overflow
   727       }
   728     }
   729   }
   731   // return number of elements we at leasted wanted to initialize
   732   return rfill + overflow;
   733 }
   738 // Decode the vmtarget field of a method handle.
   739 // Sanitize out methodOops, klassOops, and any other non-Java data.
   740 // This is for debugging and reflection.
   741 oop MethodHandles::encode_target(Handle mh, int format, TRAPS) {
   742   assert(java_dyn_MethodHandle::is_instance(mh()), "must be a MH");
   743   if (format == ETF_HANDLE_OR_METHOD_NAME) {
   744     oop target = java_dyn_MethodHandle::vmtarget(mh());
   745     if (target == NULL) {
   746       return NULL;                // unformed MH
   747     }
   748     klassOop tklass = target->klass();
   749     if (Klass::cast(tklass)->is_subclass_of(SystemDictionary::object_klass())) {
   750       return target;              // target is another MH (or something else?)
   751     }
   752   }
   753   if (format == ETF_DIRECT_HANDLE) {
   754     oop target = mh();
   755     for (;;) {
   756       if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
   757         return target;
   758       }
   759       if (!java_dyn_MethodHandle::is_instance(target)){
   760         return NULL;                // unformed MH
   761       }
   762       target = java_dyn_MethodHandle::vmtarget(target);
   763     }
   764   }
   765   // cases of metadata in MH.vmtarget:
   766   // - AMH can have methodOop for static invoke with bound receiver
   767   // - DMH can have methodOop for static invoke (on variable receiver)
   768   // - DMH can have klassOop for dispatched (non-static) invoke
   769   klassOop receiver_limit = NULL;
   770   int decode_flags = 0;
   771   methodOop m = decode_MethodHandle(mh(), receiver_limit, decode_flags);
   772   if (m == NULL)  return NULL;
   773   switch (format) {
   774   case ETF_REFLECT_METHOD:
   775     // same as jni_ToReflectedMethod:
   776     if (m->is_initializer()) {
   777       return Reflection::new_constructor(m, THREAD);
   778     } else {
   779       return Reflection::new_method(m, UseNewReflection, false, THREAD);
   780     }
   782   case ETF_HANDLE_OR_METHOD_NAME:   // method, not handle
   783   case ETF_METHOD_NAME:
   784     {
   785       if (SystemDictionary::MemberName_klass() == NULL)  break;
   786       instanceKlassHandle mname_klass(THREAD, SystemDictionary::MemberName_klass());
   787       mname_klass->initialize(CHECK_NULL);
   788       Handle mname = mname_klass->allocate_instance_handle(CHECK_NULL);
   789       sun_dyn_MemberName::set_vmindex(mname(), VM_INDEX_UNINITIALIZED);
   790       bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
   791       init_MemberName(mname(), m, do_dispatch);
   792       expand_MemberName(mname, 0, CHECK_NULL);
   793       return mname();
   794     }
   795   }
   797   // Unknown format code.
   798   char msg[50];
   799   jio_snprintf(msg, sizeof(msg), "unknown getTarget format=%d", format);
   800   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), msg);
   801 }
   803 static const char* always_null_names[] = {
   804   "java/lang/Void",
   805   "java/lang/Null",
   806   //"java/lang/Nothing",
   807   "sun/dyn/empty/Empty",
   808   NULL
   809 };
   811 static bool is_always_null_type(klassOop klass) {
   812   if (!Klass::cast(klass)->oop_is_instance())  return false;
   813   instanceKlass* ik = instanceKlass::cast(klass);
   814   // Must be on the boot class path:
   815   if (ik->class_loader() != NULL)  return false;
   816   // Check the name.
   817   symbolOop name = ik->name();
   818   for (int i = 0; ; i++) {
   819     const char* test_name = always_null_names[i];
   820     if (test_name == NULL)  break;
   821     if (name->equals(test_name, (int) strlen(test_name)))
   822       return true;
   823   }
   824   return false;
   825 }
   827 bool MethodHandles::class_cast_needed(klassOop src, klassOop dst) {
   828   if (src == dst || dst == SystemDictionary::object_klass())
   829     return false;                               // quickest checks
   830   Klass* srck = Klass::cast(src);
   831   Klass* dstk = Klass::cast(dst);
   832   if (dstk->is_interface()) {
   833     // interface receivers can safely be viewed as untyped,
   834     // because interface calls always include a dynamic check
   835     //dstk = Klass::cast(SystemDictionary::object_klass());
   836     return false;
   837   }
   838   if (srck->is_interface()) {
   839     // interface arguments must be viewed as untyped
   840     //srck = Klass::cast(SystemDictionary::object_klass());
   841     return true;
   842   }
   843   if (is_always_null_type(src)) {
   844     // some source types are known to be never instantiated;
   845     // they represent references which are always null
   846     // such null references never fail to convert safely
   847     return false;
   848   }
   849   return !srck->is_subclass_of(dstk->as_klassOop());
   850 }
   852 static oop object_java_mirror() {
   853   return Klass::cast(SystemDictionary::object_klass())->java_mirror();
   854 }
   856 bool MethodHandles::same_basic_type_for_arguments(BasicType src,
   857                                                   BasicType dst,
   858                                                   bool raw,
   859                                                   bool for_return) {
   860   if (for_return) {
   861     // return values can always be forgotten:
   862     if (dst == T_VOID)  return true;
   863     if (src == T_VOID)  return raw && (dst == T_INT);
   864     // We allow caller to receive a garbage int, which is harmless.
   865     // This trick is pulled by trusted code (see VerifyType.canPassRaw).
   866   }
   867   assert(src != T_VOID && dst != T_VOID, "should not be here");
   868   if (src == dst)  return true;
   869   if (type2size[src] != type2size[dst])  return false;
   870   // allow reinterpretation casts for integral widening
   871   if (is_subword_type(src)) { // subwords can fit in int or other subwords
   872     if (dst == T_INT)         // any subword fits in an int
   873       return true;
   874     if (src == T_BOOLEAN)     // boolean fits in any subword
   875       return is_subword_type(dst);
   876     if (src == T_BYTE && dst == T_SHORT)
   877       return true;            // remaining case: byte fits in short
   878   }
   879   // allow float/fixed reinterpretation casts
   880   if (src == T_FLOAT)   return dst == T_INT;
   881   if (src == T_INT)     return dst == T_FLOAT;
   882   if (src == T_DOUBLE)  return dst == T_LONG;
   883   if (src == T_LONG)    return dst == T_DOUBLE;
   884   return false;
   885 }
   887 const char* MethodHandles::check_method_receiver(methodOop m,
   888                                                  klassOop passed_recv_type) {
   889   assert(!m->is_static(), "caller resp.");
   890   if (passed_recv_type == NULL)
   891     return "receiver type is primitive";
   892   if (class_cast_needed(passed_recv_type, m->method_holder())) {
   893     Klass* formal = Klass::cast(m->method_holder());
   894     return SharedRuntime::generate_class_cast_message("receiver type",
   895                                                       formal->external_name());
   896   }
   897   return NULL;                  // checks passed
   898 }
   900 // Verify that m's signature can be called type-safely by a method handle
   901 // of the given method type 'mtype'.
   902 // It takes a TRAPS argument because it must perform symbol lookups.
   903 void MethodHandles::verify_method_signature(methodHandle m,
   904                                             Handle mtype,
   905                                             int first_ptype_pos,
   906                                             KlassHandle insert_ptype,
   907                                             TRAPS) {
   908   objArrayHandle ptypes(THREAD, java_dyn_MethodType::ptypes(mtype()));
   909   int pnum = first_ptype_pos;
   910   int pmax = ptypes->length();
   911   int mnum = 0;                 // method argument
   912   const char* err = NULL;
   913   for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
   914     oop ptype_oop = NULL;
   915     if (ss.at_return_type()) {
   916       if (pnum != pmax)
   917         { err = "too many arguments"; break; }
   918       ptype_oop = java_dyn_MethodType::rtype(mtype());
   919     } else {
   920       if (pnum >= pmax)
   921         { err = "not enough arguments"; break; }
   922       if (pnum >= 0)
   923         ptype_oop = ptypes->obj_at(pnum);
   924       else if (insert_ptype.is_null())
   925         ptype_oop = NULL;
   926       else
   927         ptype_oop = insert_ptype->java_mirror();
   928       pnum += 1;
   929       mnum += 1;
   930     }
   931     klassOop  mklass = NULL;
   932     BasicType mtype  = ss.type();
   933     if (mtype == T_ARRAY)  mtype = T_OBJECT; // fold all refs to T_OBJECT
   934     if (mtype == T_OBJECT) {
   935       if (ptype_oop == NULL) {
   936         // null matches any reference
   937         continue;
   938       }
   939       // If we fail to resolve types at this point, we will throw an error.
   940       symbolOop    name_oop = ss.as_symbol(CHECK);
   941       symbolHandle name(THREAD, name_oop);
   942       instanceKlass* mk = instanceKlass::cast(m->method_holder());
   943       Handle loader(THREAD, mk->class_loader());
   944       Handle domain(THREAD, mk->protection_domain());
   945       mklass = SystemDictionary::resolve_or_fail(name, loader, domain,
   946                                                  true, CHECK);
   947     }
   948     if (ptype_oop == NULL) {
   949       // null does not match any non-reference; use Object to report the error
   950       ptype_oop = object_java_mirror();
   951     }
   952     klassOop  pklass = NULL;
   953     BasicType ptype  = java_lang_Class::as_BasicType(ptype_oop, &pklass);
   954     if (!ss.at_return_type()) {
   955       err = check_argument_type_change(ptype, pklass, mtype, mklass, mnum);
   956     } else {
   957       err = check_return_type_change(mtype, mklass, ptype, pklass); // note reversal!
   958     }
   959     if (err != NULL)  break;
   960   }
   962   if (err != NULL) {
   963     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
   964   }
   965 }
   967 // Main routine for verifying the MethodHandle.type of a proposed
   968 // direct or bound-direct method handle.
   969 void MethodHandles::verify_method_type(methodHandle m,
   970                                        Handle mtype,
   971                                        bool has_bound_recv,
   972                                        KlassHandle bound_recv_type,
   973                                        TRAPS) {
   974   bool m_needs_receiver = !m->is_static();
   976   const char* err = NULL;
   978   int first_ptype_pos = m_needs_receiver ? 1 : 0;
   979   if (has_bound_recv) {
   980     first_ptype_pos -= 1;  // ptypes do not include the bound argument; start earlier in them
   981     if (m_needs_receiver && bound_recv_type.is_null())
   982       { err = "bound receiver is not an object"; goto die; }
   983   }
   985   if (m_needs_receiver && err == NULL) {
   986     objArrayOop ptypes = java_dyn_MethodType::ptypes(mtype());
   987     if (ptypes->length() < first_ptype_pos)
   988       { err = "receiver argument is missing"; goto die; }
   989     if (has_bound_recv)
   990       err = check_method_receiver(m(), bound_recv_type->as_klassOop());
   991     else
   992       err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
   993     if (err != NULL)  goto die;
   994   }
   996   // Check the other arguments for mistypes.
   997   verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
   998   return;
  1000  die:
  1001   THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1004 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
  1005   // Verify vmslots.
  1006   int check_slots = argument_slot_count(java_dyn_MethodHandle::type(mh()));
  1007   if (java_dyn_MethodHandle::vmslots(mh()) != check_slots) {
  1008     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
  1012 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
  1013   // Verify that argslot points at the given argnum.
  1014   int check_slot = argument_slot(java_dyn_MethodHandle::type(mh()), argnum);
  1015   if (argslot != check_slot || argslot < 0) {
  1016     const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
  1017     size_t msglen = strlen(fmt) + 3*11 + 1;
  1018     char* msg = NEW_RESOURCE_ARRAY(char, msglen);
  1019     jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
  1020     THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
  1024 // Verify the correspondence between two method types.
  1025 // Apart from the advertised changes, caller method type X must
  1026 // be able to invoke the callee method Y type with no violations
  1027 // of type integrity.
  1028 // Return NULL if all is well, else a short error message.
  1029 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
  1030                                                     int insert_argnum, oop insert_type,
  1031                                                     int change_argnum, oop change_type,
  1032                                                     int delete_argnum,
  1033                                                     oop dst_mtype, int dst_beg, int dst_end,
  1034                                                     bool raw) {
  1035   objArrayOop src_ptypes = java_dyn_MethodType::ptypes(src_mtype);
  1036   objArrayOop dst_ptypes = java_dyn_MethodType::ptypes(dst_mtype);
  1038   int src_max = src_ptypes->length();
  1039   int dst_max = dst_ptypes->length();
  1041   if (src_end == -1)  src_end = src_max;
  1042   if (dst_end == -1)  dst_end = dst_max;
  1044   assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
  1045   assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
  1047   // pending actions; set to -1 when done:
  1048   int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
  1050   const char* err = NULL;
  1052   // Walk along each array of parameter types, including a virtual
  1053   // NULL end marker at the end of each.
  1054   for (int src_idx = src_beg, dst_idx = dst_beg;
  1055        (src_idx <= src_end && dst_idx <= dst_end);
  1056        src_idx++, dst_idx++) {
  1057     oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
  1058     oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
  1059     bool fix_null_src_type = false;
  1061     // Perform requested edits.
  1062     if (ins_idx == src_idx) {
  1063       // note that the inserted guy is never affected by a change or deletion
  1064       ins_idx = -1;
  1065       src_type = insert_type;
  1066       fix_null_src_type = true;
  1067       --src_idx;                // back up to process src type on next loop
  1068       src_idx = src_end;
  1069     } else {
  1070       // note that the changed guy can be immediately deleted
  1071       if (chg_idx == src_idx) {
  1072         chg_idx = -1;
  1073         assert(src_idx < src_end, "oob");
  1074         src_type = change_type;
  1075         fix_null_src_type = true;
  1077       if (del_idx == src_idx) {
  1078         del_idx = -1;
  1079         assert(src_idx < src_end, "oob");
  1080         --dst_idx;
  1081         continue;               // rerun loop after skipping this position
  1085     if (src_type == NULL && fix_null_src_type)
  1086       // explicit null in this case matches any dest reference
  1087       src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
  1089     // Compare the two argument types.
  1090     if (src_type != dst_type) {
  1091       if (src_type == NULL)  return "not enough arguments";
  1092       if (dst_type == NULL)  return "too many arguments";
  1093       err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
  1094       if (err != NULL)  return err;
  1098   // Now compare return types also.
  1099   oop src_rtype = java_dyn_MethodType::rtype(src_mtype);
  1100   oop dst_rtype = java_dyn_MethodType::rtype(dst_mtype);
  1101   if (src_rtype != dst_rtype) {
  1102     err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
  1103     if (err != NULL)  return err;
  1106   assert(err == NULL, "");
  1107   return NULL;  // all is well
  1111 const char* MethodHandles::check_argument_type_change(BasicType src_type,
  1112                                                       klassOop src_klass,
  1113                                                       BasicType dst_type,
  1114                                                       klassOop dst_klass,
  1115                                                       int argnum,
  1116                                                       bool raw) {
  1117   const char* err = NULL;
  1118   bool for_return = (argnum < 0);
  1120   // just in case:
  1121   if (src_type == T_ARRAY)  src_type = T_OBJECT;
  1122   if (dst_type == T_ARRAY)  dst_type = T_OBJECT;
  1124   // Produce some nice messages if VerifyMethodHandles is turned on:
  1125   if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
  1126     if (src_type == T_OBJECT) {
  1127       if (raw && dst_type == T_INT && is_always_null_type(src_klass))
  1128         return NULL;    // OK to convert a null pointer to a garbage int
  1129       err = ((argnum >= 0)
  1130              ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
  1131              : "type mismatch: returning a %s, but caller expects primitive %s");
  1132     } else if (dst_type == T_OBJECT) {
  1133       err = ((argnum >= 0)
  1134              ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
  1135              : "type mismatch: returning a primitive %s, but caller expects %s");
  1136     } else {
  1137       err = ((argnum >= 0)
  1138              ? "type mismatch: passing a %s for method argument #%d, which expects %s"
  1139              : "type mismatch: returning a %s, but caller expects %s");
  1141   } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
  1142              class_cast_needed(src_klass, dst_klass)) {
  1143     if (!class_cast_needed(dst_klass, src_klass)) {
  1144       if (raw)
  1145         return NULL;    // reverse cast is OK; the MH target is trusted to enforce it
  1146       err = ((argnum >= 0)
  1147              ? "cast required: passing a %s for method argument #%d, which expects %s"
  1148              : "cast required: returning a %s, but caller expects %s");
  1149     } else {
  1150       err = ((argnum >= 0)
  1151              ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
  1152              : "reference mismatch: returning a %s, but caller expects %s");
  1154   } else {
  1155     // passed the obstacle course
  1156     return NULL;
  1159   // format, format, format
  1160   const char* src_name = type2name(src_type);
  1161   const char* dst_name = type2name(dst_type);
  1162   if (src_type == T_OBJECT)  src_name = Klass::cast(src_klass)->external_name();
  1163   if (dst_type == T_OBJECT)  dst_name = Klass::cast(dst_klass)->external_name();
  1164   if (src_name == NULL)  src_name = "unknown type";
  1165   if (dst_name == NULL)  dst_name = "unknown type";
  1167   size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
  1168   char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
  1169   if (argnum >= 0) {
  1170     assert(strstr(err, "%d") != NULL, "");
  1171     jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
  1172   } else {
  1173     assert(strstr(err, "%d") == NULL, "");
  1174     jio_snprintf(msg, msglen, err, src_name,         dst_name);
  1176   return msg;
  1179 // Compute the depth within the stack of the given argument, i.e.,
  1180 // the combined size of arguments to the right of the given argument.
  1181 // For the last argument (ptypes.length-1) this will be zero.
  1182 // For the first argument (0) this will be the size of all
  1183 // arguments but that one.  For the special number -1, this
  1184 // will be the size of all arguments, including the first.
  1185 // If the argument is neither -1 nor a valid argument index,
  1186 // then return a negative number.  Otherwise, the result
  1187 // is in the range [0..vmslots] inclusive.
  1188 int MethodHandles::argument_slot(oop method_type, int arg) {
  1189   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1190   int argslot = 0;
  1191   int len = ptypes->length();
  1192   if (arg < -1 || arg >= len)  return -99;
  1193   for (int i = len-1; i > arg; i--) {
  1194     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1195     argslot += type2size[bt];
  1197   assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
  1198   return argslot;
  1201 // Given a slot number, return the argument number.
  1202 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
  1203   objArrayOop ptypes = java_dyn_MethodType::ptypes(method_type);
  1204   int argslot = 0;
  1205   int len = ptypes->length();
  1206   for (int i = len-1; i >= 0; i--) {
  1207     if (query_argslot == argslot)  return i;
  1208     BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
  1209     argslot += type2size[bt];
  1211   // return pseudo-arg deepest in stack:
  1212   if (query_argslot == argslot)  return -1;
  1213   return -99;                   // oob slot, or splitting a double-slot arg
  1216 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
  1217                                                     KlassHandle receiver_limit,
  1218                                                     int decode_flags,
  1219                                                     KlassHandle receiver_klass,
  1220                                                     TRAPS) {
  1221   assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
  1222   assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
  1224   if (!m->is_static() &&
  1225       (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
  1226     // given type does not match class of method, or receiver is null!
  1227     // caller should have checked this, but let's be extra careful...
  1228     return methodHandle();
  1230   if (receiver_limit.not_null() &&
  1231       (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
  1232     // given type is not limited to the receiver type
  1233     // note that a null receiver can match any reference value, for a static method
  1234     return methodHandle();
  1236   if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
  1237     // pre-dispatched or static method (null receiver is OK for static)
  1238     return m;
  1240   } else if (receiver_klass.is_null()) {
  1241     // null receiver value; cannot dispatch
  1242     return methodHandle();
  1244   } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
  1245     // perform virtual dispatch
  1246     int vtable_index = m->vtable_index();
  1247     guarantee(vtable_index >= 0, "valid vtable index");
  1249     // receiver_klass might be an arrayKlassOop but all vtables start at
  1250     // the same place. The cast is to avoid virtual call and assertion.
  1251     // See also LinkResolver::runtime_resolve_virtual_method.
  1252     instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
  1253     DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
  1254     methodOop m_oop = inst->method_at_vtable(vtable_index);
  1255     return methodHandle(THREAD, m_oop);
  1257   } else {
  1258     // perform interface dispatch
  1259     int itable_index = klassItable::compute_itable_index(m());
  1260     guarantee(itable_index >= 0, "valid itable index");
  1261     instanceKlass* inst = instanceKlass::cast(receiver_klass());
  1262     methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
  1263     return methodHandle(THREAD, m_oop);
  1267 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
  1268   // Verify type.
  1269   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1270   verify_method_type(m, mtype, false, KlassHandle(), CHECK);
  1272   // Verify vmslots.
  1273   if (java_dyn_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
  1274     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
  1278 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
  1279   // Check arguments.
  1280   if (mh.is_null() || m.is_null() ||
  1281       (!do_dispatch && m->is_abstract())) {
  1282     THROW(vmSymbols::java_lang_InternalError());
  1285   java_dyn_MethodHandle::init_vmslots(mh());
  1287   if (VerifyMethodHandles) {
  1288     // The privileged code which invokes this routine should not make
  1289     // a mistake about types, but it's better to verify.
  1290     verify_DirectMethodHandle(mh, m, CHECK);
  1293   // Finally, after safety checks are done, link to the target method.
  1294   // We will follow the same path as the latter part of
  1295   // InterpreterRuntime::resolve_invoke(), which first finds the method
  1296   // and then decides how to populate the constant pool cache entry
  1297   // that links the interpreter calls to the method.  We need the same
  1298   // bits, and will use the same calling sequence code.
  1300   int vmindex = methodOopDesc::garbage_vtable_index;
  1301   oop vmtarget = NULL;
  1303   instanceKlass::cast(m->method_holder())->link_class(CHECK);
  1305   MethodHandleEntry* me = NULL;
  1306   if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
  1307     // We are simulating an invokeinterface instruction.
  1308     // (We might also be simulating an invokevirtual on a miranda method,
  1309     // but it is safe to treat it as an invokeinterface.)
  1310     assert(!m->can_be_statically_bound(), "no final methods on interfaces");
  1311     vmindex = klassItable::compute_itable_index(m());
  1312     assert(vmindex >= 0, "(>=0) == do_dispatch");
  1313     // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
  1314     vmtarget = m->method_holder(); // the interface
  1315     me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
  1316   } else if (!do_dispatch || m->can_be_statically_bound()) {
  1317     // We are simulating an invokestatic or invokespecial instruction.
  1318     // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
  1319     vmtarget = m();
  1320     // this does not help dispatch, but it will make it possible to parse this MH:
  1321     vmindex  = methodOopDesc::nonvirtual_vtable_index;
  1322     assert(vmindex < 0, "(>=0) == do_dispatch");
  1323     if (!m->is_static()) {
  1324       me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
  1325     } else {
  1326       me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
  1327       // Part of the semantics of a static call is an initialization barrier.
  1328       // For a DMH, it is done now, when the handle is created.
  1329       Klass* k = Klass::cast(m->method_holder());
  1330       if (k->should_be_initialized()) {
  1331         k->initialize(CHECK);
  1334   } else {
  1335     // We are simulating an invokevirtual instruction.
  1336     // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
  1337     // The key logic is LinkResolver::runtime_resolve_virtual_method.
  1338     vmindex  = m->vtable_index();
  1339     vmtarget = m->method_holder();
  1340     me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
  1343   if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  1345   sun_dyn_DirectMethodHandle::set_vmtarget(mh(), vmtarget);
  1346   sun_dyn_DirectMethodHandle::set_vmindex(mh(),  vmindex);
  1347   DEBUG_ONLY(int flags; klassOop rlimit);
  1348   assert(MethodHandles::decode_method(mh(), rlimit, flags) == m(),
  1349          "properly stored for later decoding");
  1350   DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
  1351   assert(!(actual_do_dispatch && !do_dispatch),
  1352          "do not perform dispatch if !do_dispatch specified");
  1353   assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
  1354   assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
  1356   // Done!
  1357   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1360 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
  1361                                                            methodHandle m,
  1362                                                            TRAPS) {
  1363   // Verify type.
  1364   oop receiver = sun_dyn_BoundMethodHandle::argument(mh());
  1365   Handle mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1366   KlassHandle bound_recv_type;
  1367   if (receiver != NULL)  bound_recv_type = KlassHandle(THREAD, receiver->klass());
  1368   verify_method_type(m, mtype, true, bound_recv_type, CHECK);
  1370   int receiver_pos = m->size_of_parameters() - 1;
  1372   // Verify MH.vmargslot, which should point at the bound receiver.
  1373   verify_vmargslot(mh, -1, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1374   //verify_vmslots(mh, CHECK);
  1376   // Verify vmslots.
  1377   if (java_dyn_MethodHandle::vmslots(mh()) != receiver_pos) {
  1378     THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
  1382 // Initialize a BMH with a receiver bound directly to a methodOop.
  1383 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
  1384                                                          methodHandle original_m,
  1385                                                          KlassHandle receiver_limit,
  1386                                                          int decode_flags,
  1387                                                          TRAPS) {
  1388   // Check arguments.
  1389   if (mh.is_null() || original_m.is_null()) {
  1390     THROW(vmSymbols::java_lang_InternalError());
  1393   KlassHandle receiver_klass;
  1395     oop receiver_oop = sun_dyn_BoundMethodHandle::argument(mh());
  1396     if (receiver_oop != NULL)
  1397       receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
  1399   methodHandle m = dispatch_decoded_method(original_m,
  1400                                            receiver_limit, decode_flags,
  1401                                            receiver_klass,
  1402                                            CHECK);
  1403   if (m.is_null())      { THROW(vmSymbols::java_lang_InternalError()); }
  1404   if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
  1406   java_dyn_MethodHandle::init_vmslots(mh());
  1408   if (VerifyMethodHandles) {
  1409     verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
  1412   sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1414   DEBUG_ONLY(int junk; klassOop junk2);
  1415   assert(MethodHandles::decode_method(mh(), junk2, junk) == m(), "properly stored for later decoding");
  1416   assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
  1418   // Done!
  1419   java_dyn_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
  1422 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
  1423                                              bool direct_to_method, TRAPS) {
  1424   Handle ptype_handle(THREAD,
  1425                            java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum));
  1426   KlassHandle ptype_klass;
  1427   BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
  1428   int slots_pushed = type2size[ptype];
  1430   oop argument = sun_dyn_BoundMethodHandle::argument(mh());
  1432   const char* err = NULL;
  1434   switch (ptype) {
  1435   case T_OBJECT:
  1436     if (argument != NULL)
  1437       // we must implicitly convert from the arg type to the outgoing ptype
  1438       err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
  1439     break;
  1441   case T_ARRAY: case T_VOID:
  1442     assert(false, "array, void do not appear here");
  1443   default:
  1444     if (ptype != T_INT && !is_subword_type(ptype)) {
  1445       err = "unexpected parameter type";
  1446       break;
  1448     // check subrange of Integer.value, if necessary
  1449     if (argument == NULL || argument->klass() != SystemDictionary::int_klass()) {
  1450       err = "bound integer argument must be of type java.lang.Integer";
  1451       break;
  1453     if (ptype != T_INT) {
  1454       int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
  1455       jint value = argument->int_field(value_offset);
  1456       int vminfo = adapter_subword_vminfo(ptype);
  1457       jint subword = truncate_subword_from_vminfo(value, vminfo);
  1458       if (value != subword) {
  1459         err = "bound subword value does not fit into the subword type";
  1460         break;
  1463     break;
  1464   case T_FLOAT:
  1465   case T_DOUBLE:
  1466   case T_LONG:
  1468       // we must implicitly convert from the unboxed arg type to the outgoing ptype
  1469       BasicType argbox = java_lang_boxing_object::basic_type(argument);
  1470       if (argbox != ptype) {
  1471         err = check_argument_type_change(T_OBJECT, (argument == NULL
  1472                                                     ? SystemDictionary::object_klass()
  1473                                                     : argument->klass()),
  1474                                          ptype, ptype_klass(), argnum);
  1475         assert(err != NULL, "this must be an error");
  1477       break;
  1481   if (err == NULL) {
  1482     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1483     if (direct_to_method) {
  1484       assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
  1485       assert(slots_pushed <= MethodHandlePushLimit, "");
  1486     } else {
  1487       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1488       assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
  1489       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1490       if (slots_pushed + target_pushes > MethodHandlePushLimit)
  1491         err = "too many bound parameters";
  1495   if (err == NULL) {
  1496     // Verify the rest of the method type.
  1497     err = check_method_type_insertion(java_dyn_MethodHandle::type(mh()),
  1498                                       argnum, ptype_handle(),
  1499                                       java_dyn_MethodHandle::type(target()));
  1502   if (err != NULL) {
  1503     THROW_MSG(vmSymbols::java_lang_InternalError(), err);
  1507 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1508   // Check arguments.
  1509   if (mh.is_null() || target.is_null() || !java_dyn_MethodHandle::is_instance(target())) {
  1510     THROW(vmSymbols::java_lang_InternalError());
  1513   java_dyn_MethodHandle::init_vmslots(mh());
  1515   if (VerifyMethodHandles) {
  1516     int insert_after = argnum - 1;
  1517     verify_vmargslot(mh, insert_after, sun_dyn_BoundMethodHandle::vmargslot(mh()), CHECK);
  1518     verify_vmslots(mh, CHECK);
  1521   // If (a) the target is a direct non-dispatched method handle,
  1522   // or (b) the target is a dispatched direct method handle and we
  1523   // are binding the receiver, cut out the middle-man.
  1524   // Do this by decoding the DMH and using its methodOop directly as vmtarget.
  1525   bool direct_to_method = false;
  1526   if (OptimizeMethodHandles &&
  1527       target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
  1528       (argnum == 0 || sun_dyn_DirectMethodHandle::vmindex(target()) < 0)) {
  1529     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  1530     methodHandle m(THREAD, decode_method(target(), receiver_limit_oop, decode_flags));
  1531     if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
  1532     DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - 1); // pos. of 1st arg.
  1533     assert(sun_dyn_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
  1534     if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
  1535       KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  1536       init_BoundMethodHandle_with_receiver(mh, m,
  1537                                            receiver_limit, decode_flags,
  1538                                            CHECK);
  1539       return;
  1542     // Even if it is not a bound receiver, we still might be able
  1543     // to bind another argument and still invoke the methodOop directly.
  1544     if (!(decode_flags & _dmf_does_dispatch)) {
  1545       direct_to_method = true;
  1546       sun_dyn_BoundMethodHandle::set_vmtarget(mh(), m());
  1549   if (!direct_to_method)
  1550     sun_dyn_BoundMethodHandle::set_vmtarget(mh(), target());
  1552   if (VerifyMethodHandles) {
  1553     verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
  1556   // Next question:  Is this a ref, int, or long bound value?
  1557   oop ptype_oop = java_dyn_MethodType::ptype(java_dyn_MethodHandle::type(target()), argnum);
  1558   BasicType ptype = java_lang_Class::as_BasicType(ptype_oop);
  1559   int slots_pushed = type2size[ptype];
  1561   MethodHandleEntry* me = NULL;
  1562   if (ptype == T_OBJECT) {
  1563     if (direct_to_method)  me = MethodHandles::entry(_bound_ref_direct_mh);
  1564     else                   me = MethodHandles::entry(_bound_ref_mh);
  1565   } else if (slots_pushed == 2) {
  1566     if (direct_to_method)  me = MethodHandles::entry(_bound_long_direct_mh);
  1567     else                   me = MethodHandles::entry(_bound_long_mh);
  1568   } else if (slots_pushed == 1) {
  1569     if (direct_to_method)  me = MethodHandles::entry(_bound_int_direct_mh);
  1570     else                   me = MethodHandles::entry(_bound_int_mh);
  1571   } else {
  1572     assert(false, "");
  1575   // Done!
  1576   java_dyn_MethodHandle::set_vmentry(mh(), me);
  1579 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
  1580   char msg[200];
  1581   jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
  1582   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
  1585 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
  1586   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1587   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1589   verify_vmargslot(mh, argnum, argslot, CHECK);
  1590   verify_vmslots(mh, CHECK);
  1592   jint conv_op    = adapter_conversion_op(conversion);
  1593   if (!conv_op_valid(conv_op)) {
  1594     throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
  1595     return;
  1597   EntryKind ek = adapter_entry_kind(conv_op);
  1599   int stack_move = adapter_conversion_stack_move(conversion);
  1600   BasicType src  = adapter_conversion_src_type(conversion);
  1601   BasicType dest = adapter_conversion_dest_type(conversion);
  1602   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1604   Handle argument(THREAD,  sun_dyn_AdapterMethodHandle::argument(mh()));
  1605   Handle target(THREAD,    sun_dyn_AdapterMethodHandle::vmtarget(mh()));
  1606   Handle src_mtype(THREAD, java_dyn_MethodHandle::type(mh()));
  1607   Handle dst_mtype(THREAD, java_dyn_MethodHandle::type(target()));
  1609   const char* err = NULL;
  1611   if (err == NULL) {
  1612     // Check that the correct argument is supplied, but only if it is required.
  1613     switch (ek) {
  1614     case _adapter_check_cast:     // target type of cast
  1615     case _adapter_ref_to_prim:    // wrapper type from which to unbox
  1616     case _adapter_prim_to_ref:    // wrapper type to box into
  1617     case _adapter_collect_args:   // array type to collect into
  1618     case _adapter_spread_args:    // array type to spread from
  1619       if (!java_lang_Class::is_instance(argument())
  1620           || java_lang_Class::is_primitive(argument()))
  1621         { err = "adapter requires argument of type java.lang.Class"; break; }
  1622       if (ek == _adapter_collect_args ||
  1623           ek == _adapter_spread_args) {
  1624         // Make sure it is a suitable collection type.  (Array, for now.)
  1625         Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
  1626         if (!ak->oop_is_objArray()) {
  1627           { err = "adapter requires argument of type java.lang.Class<Object[]>"; break; }
  1630       break;
  1631     case _adapter_flyby:
  1632     case _adapter_ricochet:
  1633       if (!java_dyn_MethodHandle::is_instance(argument()))
  1634         { err = "MethodHandle adapter argument required"; break; }
  1635       break;
  1636     default:
  1637       if (argument.not_null())
  1638         { err = "adapter has spurious argument"; break; }
  1639       break;
  1643   if (err == NULL) {
  1644     // Check that the src/dest types are supplied if needed.
  1645     switch (ek) {
  1646     case _adapter_check_cast:
  1647       if (src != T_OBJECT || dest != T_OBJECT) {
  1648         err = "adapter requires object src/dest conversion subfields";
  1650       break;
  1651     case _adapter_prim_to_prim:
  1652       if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
  1653         err = "adapter requires primitive src/dest conversion subfields"; break;
  1655       if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
  1656           !(src == T_FLOAT || src == T_DOUBLE) &&  (dest == T_FLOAT || dest == T_DOUBLE)) {
  1657         err = "adapter cannot convert beween floating and fixed-point"; break;
  1659       break;
  1660     case _adapter_ref_to_prim:
  1661       if (src != T_OBJECT || !is_java_primitive(dest)
  1662           || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
  1663         err = "adapter requires primitive dest conversion subfield"; break;
  1665       break;
  1666     case _adapter_prim_to_ref:
  1667       if (!is_java_primitive(src) || dest != T_OBJECT
  1668           || argument() != Klass::cast(SystemDictionary::box_klass(src))->java_mirror()) {
  1669         err = "adapter requires primitive src conversion subfield"; break;
  1671       break;
  1672     case _adapter_swap_args:
  1673     case _adapter_rot_args:
  1675         if (!src || src != dest) {
  1676           err = "adapter requires src/dest conversion subfields for swap"; break;
  1678         int swap_size = type2size[src];
  1679         oop src_mtype  = sun_dyn_AdapterMethodHandle::type(mh());
  1680         oop dest_mtype = sun_dyn_AdapterMethodHandle::type(target());
  1681         int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(target());
  1682         int src_slot   = argslot;
  1683         int dest_slot  = vminfo;
  1684         bool rotate_up = (src_slot > dest_slot); // upward rotation
  1685         int src_arg    = argnum;
  1686         int dest_arg   = argument_slot_to_argnum(dest_mtype, dest_slot);
  1687         verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
  1688         if (!(dest_slot >= src_slot + swap_size) &&
  1689             !(src_slot >= dest_slot + swap_size)) {
  1690           err = "source, destination slots must be distinct";
  1691         } else if (ek == _adapter_swap_args && !(src_slot > dest_slot)) {
  1692           err = "source of swap must be deeper in stack";
  1693         } else if (ek == _adapter_swap_args) {
  1694           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, dest_arg),
  1695                                            java_dyn_MethodType::ptype(dest_mtype, src_arg),
  1696                                            dest_arg);
  1697         } else if (ek == _adapter_rot_args) {
  1698           if (rotate_up) {
  1699             assert((src_slot > dest_slot) && (src_arg < dest_arg), "");
  1700             // rotate up: [dest_slot..src_slot-ss] --> [dest_slot+ss..src_slot]
  1701             // that is:   [src_arg+1..dest_arg] --> [src_arg..dest_arg-1]
  1702             for (int i = src_arg+1; i <= dest_arg && err == NULL; i++) {
  1703               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1704                                                java_dyn_MethodType::ptype(dest_mtype, i-1),
  1705                                                i);
  1707           } else { // rotate down
  1708             assert((src_slot < dest_slot) && (src_arg > dest_arg), "");
  1709             // rotate down: [src_slot+ss..dest_slot] --> [src_slot..dest_slot-ss]
  1710             // that is:     [dest_arg..src_arg-1] --> [dst_arg+1..src_arg]
  1711             for (int i = dest_arg; i <= src_arg-1 && err == NULL; i++) {
  1712               err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, i),
  1713                                                java_dyn_MethodType::ptype(dest_mtype, i+1),
  1714                                                i);
  1718         if (err == NULL)
  1719           err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype, src_arg),
  1720                                            java_dyn_MethodType::ptype(dest_mtype, dest_arg),
  1721                                            src_arg);
  1723       break;
  1724     case _adapter_collect_args:
  1725     case _adapter_spread_args:
  1727         BasicType coll_type = (ek == _adapter_collect_args) ? dest : src;
  1728         BasicType elem_type = (ek == _adapter_collect_args) ? src : dest;
  1729         if (coll_type != T_OBJECT || elem_type != T_OBJECT) {
  1730           err = "adapter requires src/dest subfields"; break;
  1731           // later:
  1732           // - consider making coll be a primitive array
  1733           // - consider making coll be a heterogeneous collection
  1736       break;
  1737     default:
  1738       if (src != 0 || dest != 0) {
  1739         err = "adapter has spurious src/dest conversion subfields"; break;
  1741       break;
  1745   if (err == NULL) {
  1746     // Check the stack_move subfield.
  1747     // It must always report the net change in stack size, positive or negative.
  1748     int slots_pushed = stack_move / stack_move_unit();
  1749     switch (ek) {
  1750     case _adapter_prim_to_prim:
  1751     case _adapter_ref_to_prim:
  1752     case _adapter_prim_to_ref:
  1753       if (slots_pushed != type2size[dest] - type2size[src]) {
  1754         err = "wrong stack motion for primitive conversion";
  1756       break;
  1757     case _adapter_dup_args:
  1758       if (slots_pushed <= 0) {
  1759         err = "adapter requires conversion subfield slots_pushed > 0";
  1761       break;
  1762     case _adapter_drop_args:
  1763       if (slots_pushed >= 0) {
  1764         err = "adapter requires conversion subfield slots_pushed < 0";
  1766       break;
  1767     case _adapter_collect_args:
  1768       if (slots_pushed > 1) {
  1769         err = "adapter requires conversion subfield slots_pushed <= 1";
  1771       break;
  1772     case _adapter_spread_args:
  1773       if (slots_pushed < -1) {
  1774         err = "adapter requires conversion subfield slots_pushed >= -1";
  1776       break;
  1777     default:
  1778       if (stack_move != 0) {
  1779         err = "adapter has spurious stack_move conversion subfield";
  1781       break;
  1783     if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
  1784       err = "stack_move conversion subfield must be multiple of stack_move_unit";
  1788   if (err == NULL) {
  1789     // Make sure this adapter does not push too deeply.
  1790     int slots_pushed = stack_move / stack_move_unit();
  1791     int this_vmslots = java_dyn_MethodHandle::vmslots(mh());
  1792     int target_vmslots = java_dyn_MethodHandle::vmslots(target());
  1793     if (slots_pushed != (target_vmslots - this_vmslots)) {
  1794       err = "stack_move inconsistent with previous and current MethodType vmslots";
  1795     } else if (slots_pushed > 0)  {
  1796       // verify stack_move against MethodHandlePushLimit
  1797       int target_pushes = decode_MethodHandle_stack_pushes(target());
  1798       // do not blow the stack; use a Java-based adapter if this limit is exceeded
  1799       if (slots_pushed + target_pushes > MethodHandlePushLimit) {
  1800         err = "adapter pushes too many parameters";
  1804     // While we're at it, check that the stack motion decoder works:
  1805     DEBUG_ONLY(int target_pushes = decode_MethodHandle_stack_pushes(target()));
  1806     DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
  1807     assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
  1810   if (err == NULL && vminfo != 0) {
  1811     switch (ek) {
  1812       case _adapter_swap_args:
  1813       case _adapter_rot_args:
  1814         break;                // OK
  1815     default:
  1816       err = "vminfo subfield is reserved to the JVM";
  1820   // Do additional ad hoc checks.
  1821   if (err == NULL) {
  1822     switch (ek) {
  1823     case _adapter_retype_only:
  1824       err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
  1825       break;
  1827     case _adapter_retype_raw:
  1828       err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
  1829       break;
  1831     case _adapter_check_cast:
  1833         // The actual value being checked must be a reference:
  1834         err = check_argument_type_change(java_dyn_MethodType::ptype(src_mtype(), argnum),
  1835                                          object_java_mirror(), argnum);
  1836         if (err != NULL)  break;
  1838         // The output of the cast must fit with the destination argument:
  1839         Handle cast_class = argument;
  1840         err = check_method_type_conversion(src_mtype(),
  1841                                            argnum, cast_class(),
  1842                                            dst_mtype());
  1844       break;
  1846       // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
  1850   if (err != NULL) {
  1851     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  1852     return;
  1857 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
  1858   oop  argument   = sun_dyn_AdapterMethodHandle::argument(mh());
  1859   int  argslot    = sun_dyn_AdapterMethodHandle::vmargslot(mh());
  1860   jint conversion = sun_dyn_AdapterMethodHandle::conversion(mh());
  1861   jint conv_op    = adapter_conversion_op(conversion);
  1863   // adjust the adapter code to the internal EntryKind enumeration:
  1864   EntryKind ek_orig = adapter_entry_kind(conv_op);
  1865   EntryKind ek_opt  = ek_orig;  // may be optimized
  1867   // Finalize the vmtarget field (Java initialized it to null).
  1868   if (!java_dyn_MethodHandle::is_instance(target())) {
  1869     throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
  1870     return;
  1872   sun_dyn_AdapterMethodHandle::set_vmtarget(mh(), target());
  1874   if (VerifyMethodHandles) {
  1875     verify_AdapterMethodHandle(mh, argnum, CHECK);
  1878   int stack_move = adapter_conversion_stack_move(conversion);
  1879   BasicType src  = adapter_conversion_src_type(conversion);
  1880   BasicType dest = adapter_conversion_dest_type(conversion);
  1881   int vminfo     = adapter_conversion_vminfo(conversion); // should be zero
  1883   const char* err = NULL;
  1885   // Now it's time to finish the case analysis and pick a MethodHandleEntry.
  1886   switch (ek_orig) {
  1887   case _adapter_retype_only:
  1888   case _adapter_retype_raw:
  1889   case _adapter_check_cast:
  1890   case _adapter_dup_args:
  1891   case _adapter_drop_args:
  1892     // these work fine via general case code
  1893     break;
  1895   case _adapter_prim_to_prim:
  1897       // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
  1898       // And, the {float,double} -> {int,long} cases must be handled by Java.
  1899       switch (type2size[src] *4+ type2size[dest]) {
  1900       case 1 *4+ 1:
  1901         assert(src == T_INT || is_subword_type(src), "source is not float");
  1902         // Subword-related cases are int -> {boolean,byte,char,short}.
  1903         ek_opt = _adapter_opt_i2i;
  1904         vminfo = adapter_subword_vminfo(dest);
  1905         break;
  1906       case 2 *4+ 1:
  1907         if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
  1908           ek_opt = _adapter_opt_l2i;
  1909           vminfo = adapter_subword_vminfo(dest);
  1910         } else if (src == T_DOUBLE && dest == T_FLOAT) {
  1911           ek_opt = _adapter_opt_d2f;
  1912         } else {
  1913           assert(false, "");
  1915         break;
  1916       case 1 *4+ 2:
  1917         if (src == T_INT && dest == T_LONG) {
  1918           ek_opt = _adapter_opt_i2l;
  1919         } else if (src == T_FLOAT && dest == T_DOUBLE) {
  1920           ek_opt = _adapter_opt_f2d;
  1921         } else {
  1922           assert(false, "");
  1924         break;
  1925       default:
  1926         assert(false, "");
  1927         break;
  1930     break;
  1932   case _adapter_ref_to_prim:
  1934       switch (type2size[dest]) {
  1935       case 1:
  1936         ek_opt = _adapter_opt_unboxi;
  1937         vminfo = adapter_subword_vminfo(dest);
  1938         break;
  1939       case 2:
  1940         ek_opt = _adapter_opt_unboxl;
  1941         break;
  1942       default:
  1943         assert(false, "");
  1944         break;
  1947     break;
  1949   case _adapter_prim_to_ref:
  1950     goto throw_not_impl;        // allocates, hence could block
  1952   case _adapter_swap_args:
  1953   case _adapter_rot_args:
  1955       int swap_slots = type2size[src];
  1956       int slot_limit = sun_dyn_AdapterMethodHandle::vmslots(mh());
  1957       int src_slot   = argslot;
  1958       int dest_slot  = vminfo;
  1959       int rotate     = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
  1960       switch (swap_slots) {
  1961       case 1:
  1962         ek_opt = (!rotate    ? _adapter_opt_swap_1 :
  1963                   rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
  1964         break;
  1965       case 2:
  1966         ek_opt = (!rotate    ? _adapter_opt_swap_2 :
  1967                   rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
  1968         break;
  1969       default:
  1970         assert(false, "");
  1971         break;
  1974     break;
  1976   case _adapter_collect_args:
  1977     goto throw_not_impl;        // allocates, hence could block
  1979   case _adapter_spread_args:
  1981       // vminfo will be the required length of the array
  1982       int slots_pushed = stack_move / stack_move_unit();
  1983       int array_size   = slots_pushed + 1;
  1984       assert(array_size >= 0, "");
  1985       vminfo = array_size;
  1986       switch (array_size) {
  1987       case 0:   ek_opt = _adapter_opt_spread_0;       break;
  1988       case 1:   ek_opt = _adapter_opt_spread_1;       break;
  1989       default:  ek_opt = _adapter_opt_spread_more;    break;
  1991       if ((vminfo & CONV_VMINFO_MASK) != vminfo)
  1992         goto throw_not_impl;    // overflow
  1994     break;
  1996   case _adapter_flyby:
  1997   case _adapter_ricochet:
  1998     goto throw_not_impl;        // runs Java code, hence could block
  2000   default:
  2001     // should have failed much earlier; must be a missing case here
  2002     assert(false, "incomplete switch");
  2003     // and fall through:
  2005   throw_not_impl:
  2006     // FIXME: these adapters are NYI
  2007     err = "adapter not yet implemented in the JVM";
  2008     break;
  2011   if (err != NULL) {
  2012     throw_InternalError_for_bad_conversion(conversion, err, THREAD);
  2013     return;
  2016   // Rebuild the conversion value; maybe parts of it were changed.
  2017   jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
  2019   // Finalize the conversion field.  (Note that it is final to Java code.)
  2020   sun_dyn_AdapterMethodHandle::set_conversion(mh(), new_conversion);
  2022   // Done!
  2023   java_dyn_MethodHandle::set_vmentry(mh(), entry(ek_opt));
  2025   // There should be enough memory barriers on exit from native methods
  2026   // to ensure that the MH is fully initialized to all threads before
  2027   // Java code can publish it in global data structures.
  2030 //
  2031 // Here are the native methods on sun.dyn.MethodHandleImpl.
  2032 // They are the private interface between this JVM and the HotSpot-specific
  2033 // Java code that implements JSR 292 method handles.
  2034 //
  2035 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
  2036 // that intrinsic (non-JNI) native methods are defined in HotSpot.
  2037 //
  2039 // direct method handles for invokestatic or invokespecial
  2040 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
  2041 JVM_ENTRY(void, MHI_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2042                              jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
  2043   ResourceMark rm;              // for error messages
  2045   // This is the guy we are initializing:
  2046   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2047   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2049   // Early returns out of this method leave the DMH in an unfinished state.
  2050   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2052   // which method are we really talking about?
  2053   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2054   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2055   if (sun_dyn_MemberName::is_instance(target_oop) &&
  2056       sun_dyn_MemberName::vmindex(target_oop) == VM_INDEX_UNINITIALIZED) {
  2057     Handle mname(THREAD, target_oop);
  2058     MethodHandles::resolve_MemberName(mname, CHECK);
  2059     target_oop = mname(); // in case of GC
  2062   int decode_flags = 0; klassOop receiver_limit = NULL;
  2063   methodHandle m(THREAD,
  2064                  MethodHandles::decode_method(target_oop,
  2065                                               receiver_limit, decode_flags));
  2066   if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
  2068   // The trusted Java code that calls this method should already have performed
  2069   // access checks on behalf of the given caller.  But, we can verify this.
  2070   if (VerifyMethodHandles && caller_jh != NULL) {
  2071     KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
  2072     // If this were a bytecode, the first access check would be against
  2073     // the "reference class" mentioned in the CONSTANT_Methodref.
  2074     // For that class, we use the defining class of m,
  2075     // or a more specific receiver limit if available.
  2076     klassOop reference_klass = m->method_holder();  // OK approximation
  2077     if (receiver_limit != NULL && receiver_limit != reference_klass) {
  2078       if (!Klass::cast(receiver_limit)->is_subtype_of(reference_klass))
  2079         THROW_MSG(vmSymbols::java_lang_InternalError(), "receiver limit out of bounds");  // Java code bug
  2080       reference_klass = receiver_limit;
  2082     // Emulate LinkResolver::check_klass_accessability.
  2083     if (!Reflection::verify_class_access(caller->as_klassOop(),
  2084                                          reference_klass,
  2085                                          true)) {
  2086       THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(m->method_holder())->external_name());
  2088     // If there were a bytecode, the next step would be to lookup the method
  2089     // in the reference class, then then check the method's access bits.
  2090     // Emulate LinkResolver::check_method_accessability.
  2091     klassOop resolved_klass = m->method_holder();
  2092     if (!Reflection::verify_field_access(caller->as_klassOop(),
  2093                                          resolved_klass, reference_klass,
  2094                                          m->access_flags(),
  2095                                          true)) {
  2096       // %%% following cutout belongs in Reflection::verify_field_access?
  2097       bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
  2098                                                         reference_klass, THREAD);
  2099       if (!same_pm) {
  2100         THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
  2105   MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
  2107 JVM_END
  2109 // bound method handles
  2110 JVM_ENTRY(void, MHI_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2111                              jobject target_jh, int argnum)) {
  2112   ResourceMark rm;              // for error messages
  2114   // This is the guy we are initializing:
  2115   if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2116   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2118   // Early returns out of this method leave the BMH in an unfinished state.
  2119   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2121   if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2122   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2124   if (!java_dyn_MethodHandle::is_instance(target())) {
  2125     // Target object is a reflective method.  (%%% Do we need this alternate path?)
  2126     Untested("init_BMH of non-MH");
  2127     if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
  2128     int decode_flags = 0; klassOop receiver_limit_oop = NULL;
  2129     methodHandle m(THREAD,
  2130                    MethodHandles::decode_method(target(),
  2131                                                 receiver_limit_oop,
  2132                                                 decode_flags));
  2133     KlassHandle receiver_limit(THREAD, receiver_limit_oop);
  2134     MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
  2135                                                        receiver_limit,
  2136                                                        decode_flags,
  2137                                                        CHECK);
  2138     return;
  2141   // Build a BMH on top of a DMH or another BMH:
  2142   MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
  2144 JVM_END
  2146 // adapter method handles
  2147 JVM_ENTRY(void, MHI_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
  2148                              jobject target_jh, int argnum)) {
  2149   // This is the guy we are initializing:
  2150   if (mh_jh == NULL || target_jh == NULL) {
  2151     THROW(vmSymbols::java_lang_InternalError());
  2153   Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
  2154   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  2156   // Early returns out of this method leave the AMH in an unfinished state.
  2157   assert(java_dyn_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
  2159   MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
  2161 JVM_END
  2163 // method type forms
  2164 JVM_ENTRY(void, MHI_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
  2165   if (erased_jh == NULL)  return;
  2166   if (TraceMethodHandles) {
  2167     tty->print("creating MethodType form ");
  2168     if (WizardMode || Verbose) {   // Warning: this calls Java code on the MH!
  2169       // call Object.toString()
  2170       symbolOop name = vmSymbols::toString_name(), sig = vmSymbols::void_string_signature();
  2171       JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
  2172       JavaValue result(T_OBJECT);
  2173       JavaCalls::call_virtual(&result, SystemDictionary::object_klass(), name, sig,
  2174                               &args, CHECK);
  2175       Handle str(THREAD, (oop)result.get_jobject());
  2176       java_lang_String::print(str, tty);
  2178     tty->cr();
  2181 JVM_END
  2183 // debugging and reflection
  2184 JVM_ENTRY(jobject, MHI_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
  2185   Handle mh(THREAD, JNIHandles::resolve(mh_jh));
  2186   if (!java_dyn_MethodHandle::is_instance(mh())) {
  2187     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
  2189   oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
  2190   return JNIHandles::make_local(THREAD, target);
  2192 JVM_END
  2194 JVM_ENTRY(jint, MHI_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  2195   switch (which) {
  2196   case MethodHandles::GC_JVM_PUSH_LIMIT:
  2197     guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
  2198               "MethodHandlePushLimit parameter must be in valid range");
  2199     return MethodHandlePushLimit;
  2200   case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
  2201     // return number of words per slot, signed according to stack direction
  2202     return MethodHandles::stack_move_unit();
  2204   return 0;
  2206 JVM_END
  2208 #ifndef PRODUCT
  2209 #define EACH_NAMED_CON(template) \
  2210     template(MethodHandles,GC_JVM_PUSH_LIMIT) \
  2211     template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) \
  2212     template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
  2213     template(MethodHandles,ETF_DIRECT_HANDLE) \
  2214     template(MethodHandles,ETF_METHOD_NAME) \
  2215     template(MethodHandles,ETF_REFLECT_METHOD) \
  2216     template(sun_dyn_MemberName,MN_IS_METHOD) \
  2217     template(sun_dyn_MemberName,MN_IS_CONSTRUCTOR) \
  2218     template(sun_dyn_MemberName,MN_IS_FIELD) \
  2219     template(sun_dyn_MemberName,MN_IS_TYPE) \
  2220     template(sun_dyn_MemberName,MN_SEARCH_SUPERCLASSES) \
  2221     template(sun_dyn_MemberName,MN_SEARCH_INTERFACES) \
  2222     template(sun_dyn_MemberName,VM_INDEX_UNINITIALIZED) \
  2223     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_ONLY) \
  2224     template(sun_dyn_AdapterMethodHandle,OP_RETYPE_RAW) \
  2225     template(sun_dyn_AdapterMethodHandle,OP_CHECK_CAST) \
  2226     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
  2227     template(sun_dyn_AdapterMethodHandle,OP_REF_TO_PRIM) \
  2228     template(sun_dyn_AdapterMethodHandle,OP_PRIM_TO_REF) \
  2229     template(sun_dyn_AdapterMethodHandle,OP_SWAP_ARGS) \
  2230     template(sun_dyn_AdapterMethodHandle,OP_ROT_ARGS) \
  2231     template(sun_dyn_AdapterMethodHandle,OP_DUP_ARGS) \
  2232     template(sun_dyn_AdapterMethodHandle,OP_DROP_ARGS) \
  2233     template(sun_dyn_AdapterMethodHandle,OP_COLLECT_ARGS) \
  2234     template(sun_dyn_AdapterMethodHandle,OP_SPREAD_ARGS) \
  2235     template(sun_dyn_AdapterMethodHandle,OP_FLYBY) \
  2236     template(sun_dyn_AdapterMethodHandle,OP_RICOCHET) \
  2237     template(sun_dyn_AdapterMethodHandle,CONV_OP_LIMIT) \
  2238     template(sun_dyn_AdapterMethodHandle,CONV_OP_MASK) \
  2239     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_MASK) \
  2240     template(sun_dyn_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
  2241     template(sun_dyn_AdapterMethodHandle,CONV_OP_SHIFT) \
  2242     template(sun_dyn_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
  2243     template(sun_dyn_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
  2244     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
  2245     template(sun_dyn_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
  2246     /*end*/
  2248 #define ONE_PLUS(scope,value) 1+
  2249 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
  2250 #define VALUE_COMMA(scope,value) scope::value,
  2251 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
  2252 #define STRING_NULL(scope,value) #value "\0"
  2253 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
  2255 #undef ONE_PLUS
  2256 #undef VALUE_COMMA
  2257 #undef STRING_NULL
  2258 #undef EACH_NAMED_CON
  2259 #endif
  2261 JVM_ENTRY(jint, MHI_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
  2262 #ifndef PRODUCT
  2263   if (which >= 0 && which < con_value_count) {
  2264     int con = con_values[which];
  2265     objArrayOop box = (objArrayOop) JNIHandles::resolve(box_jh);
  2266     if (box != NULL && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
  2267       const char* str = &con_names[0];
  2268       for (int i = 0; i < which; i++)
  2269         str += strlen(str) + 1;   // skip name and null
  2270       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);
  2271       box->obj_at_put(0, name);
  2273     return con;
  2275 #endif
  2276   return 0;
  2278 JVM_END
  2280 // void init(MemberName self, AccessibleObject ref)
  2281 JVM_ENTRY(void, MHI_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
  2282   if (mname_jh == NULL || target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2283   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2284   oop target_oop = JNIHandles::resolve_non_null(target_jh);
  2285   MethodHandles::init_MemberName(mname(), target_oop);
  2287 JVM_END
  2289 // void expand(MemberName self)
  2290 JVM_ENTRY(void, MHI_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  2291   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2292   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2293   MethodHandles::expand_MemberName(mname, 0, CHECK);
  2295 JVM_END
  2297 // void resolve(MemberName self, Class<?> caller)
  2298 JVM_ENTRY(void, MHI_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  2299   if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
  2300   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  2301   // %%% take caller into account!
  2302   MethodHandles::resolve_MemberName(mname, CHECK);
  2304 JVM_END
  2306 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2307 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2308 JVM_ENTRY(jint, MHI_getMembers(JNIEnv *env, jobject igcls,
  2309                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
  2310                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  2311   if (clazz_jh == NULL || results_jh == NULL)  return -1;
  2312   klassOop k_oop = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh));
  2314   objArrayOop results = (objArrayOop) JNIHandles::resolve(results_jh);
  2315   if (results == NULL || !results->is_objArray())       return -1;
  2317   symbolOop name = NULL, sig = NULL;
  2318   if (name_jh != NULL) {
  2319     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
  2320     if (name == NULL)  return 0; // a match is not possible
  2322   if (sig_jh != NULL) {
  2323     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
  2324     if (sig == NULL)  return 0; // a match is not possible
  2327   klassOop caller = NULL;
  2328   if (caller_jh != NULL) {
  2329     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
  2330     if (!java_lang_Class::is_instance(caller_oop))  return -1;
  2331     caller = java_lang_Class::as_klassOop(caller_oop);
  2334   if (name != NULL && sig != NULL && results != NULL) {
  2335     // try a direct resolve
  2336     // %%% TO DO
  2339   int res = MethodHandles::find_MemberNames(k_oop, name, sig, mflags,
  2340                                             caller, skip, results);
  2341   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  2342   return res;
  2344 JVM_END
  2347 JVM_ENTRY(void, MH_linkCallSite(JNIEnv *env, jobject igcls, jobject site_jh, jobject target_jh)) {
  2348   // No special action required, yet.
  2349   oop site_oop = JNIHandles::resolve(site_jh);
  2350   if (site_oop == NULL || site_oop->klass() != SystemDictionary::CallSite_klass())
  2351     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "call site");
  2352   java_dyn_CallSite::set_target(site_oop, JNIHandles::resolve(target_jh));
  2354 JVM_END
  2357 /// JVM_RegisterMethodHandleMethods
  2359 #define ADR "J"
  2361 #define LANG "Ljava/lang/"
  2362 #define JDYN "Ljava/dyn/"
  2363 #define IDYN "Lsun/dyn/"
  2365 #define OBJ   LANG"Object;"
  2366 #define CLS   LANG"Class;"
  2367 #define STRG  LANG"String;"
  2368 #define CST   JDYN"CallSite;"
  2369 #define MT    JDYN"MethodType;"
  2370 #define MH    JDYN"MethodHandle;"
  2371 #define MHI   IDYN"MethodHandleImpl;"
  2372 #define MEM   IDYN"MemberName;"
  2373 #define AMH   IDYN"AdapterMethodHandle;"
  2374 #define BMH   IDYN"BoundMethodHandle;"
  2375 #define DMH   IDYN"DirectMethodHandle;"
  2377 #define CC (char*)  /*cast a literal from (const char*)*/
  2378 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
  2380 // These are the native methods on sun.dyn.MethodHandleNatives.
  2381 static JNINativeMethod methods[] = {
  2382   // void init(MemberName self, AccessibleObject ref)
  2383   {CC"init",                    CC"("AMH""MH"I)V",              FN_PTR(MHI_init_AMH)},
  2384   {CC"init",                    CC"("BMH""OBJ"I)V",             FN_PTR(MHI_init_BMH)},
  2385   {CC"init",                    CC"("DMH""OBJ"Z"CLS")V",        FN_PTR(MHI_init_DMH)},
  2386   {CC"init",                    CC"("MT")V",                    FN_PTR(MHI_init_MT)},
  2387   {CC"init",                    CC"("MEM""OBJ")V",              FN_PTR(MHI_init_Mem)},
  2388   {CC"expand",                  CC"("MEM")V",                   FN_PTR(MHI_expand_Mem)},
  2389   {CC"resolve",                 CC"("MEM""CLS")V",              FN_PTR(MHI_resolve_Mem)},
  2390   {CC"getTarget",               CC"("MH"I)"OBJ,                 FN_PTR(MHI_getTarget)},
  2391   {CC"getConstant",             CC"(I)I",                       FN_PTR(MHI_getConstant)},
  2392   //  static native int getNamedCon(int which, Object[] name)
  2393   {CC"getNamedCon",             CC"(I["OBJ")I",                 FN_PTR(MHI_getNamedCon)},
  2394   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  2395   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
  2396   {CC"getMembers",              CC"("CLS""STRG""STRG"I"CLS"I["MEM")I",  FN_PTR(MHI_getMembers)}
  2397 };
  2399 // More entry points specifically for EnableInvokeDynamic.
  2400 static JNINativeMethod methods2[] = {
  2401   {CC"linkCallSite",            CC"("CST MH")V",                FN_PTR(MH_linkCallSite)}
  2402 };
  2405 // This one function is exported, used by NativeLookup.
  2407 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
  2408   assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
  2410   // note: this explicit warning-producing stuff will be replaced by auto-detection of the JSR 292 classes
  2412   if (!EnableMethodHandles) {
  2413     warning("JSR 292 method handles are disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles to enable.");
  2414     return;  // bind nothing
  2417   bool enable_MH = true;
  2420     ThreadToNativeFromVM ttnfv(thread);
  2422     int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
  2423     if (env->ExceptionOccurred()) {
  2424       MethodHandles::set_enabled(false);
  2425       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2426       enable_MH = false;
  2427       env->ExceptionClear();
  2431   if (enable_MH) {
  2432     KlassHandle MHI_klass = SystemDictionaryHandles::MethodHandleImpl_klass();
  2433     if (MHI_klass.not_null()) {
  2434       symbolHandle raiseException_name = oopFactory::new_symbol_handle("raiseException", CHECK);
  2435       symbolHandle raiseException_sig  = oopFactory::new_symbol_handle("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK);
  2436       methodOop raiseException_method  = instanceKlass::cast(MHI_klass->as_klassOop())
  2437                     ->find_method(raiseException_name(), raiseException_sig());
  2438       if (raiseException_method != NULL && raiseException_method->is_static()) {
  2439         MethodHandles::set_raise_exception_method(raiseException_method);
  2440       } else {
  2441         warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2442         enable_MH = false;
  2447   if (enable_MH) {
  2448     MethodHandles::set_enabled(true);
  2451   if (!EnableInvokeDynamic) {
  2452     warning("JSR 292 invokedynamic is disabled in this JVM.  Use -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic to enable.");
  2453     return;  // bind nothing
  2457     ThreadToNativeFromVM ttnfv(thread);
  2459     int status = env->RegisterNatives(MHN_class, methods2, sizeof(methods2)/sizeof(JNINativeMethod));
  2460     if (env->ExceptionOccurred()) {
  2461       MethodHandles::set_enabled(false);
  2462       warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
  2463       env->ExceptionClear();
  2464     } else {
  2465       MethodHandles::set_enabled(true);
  2469 JVM_END

mercurial