src/share/vm/prims/methodHandles.cpp

Tue, 16 Mar 2010 11:52:17 +0100

author
twisti
date
Tue, 16 Mar 2010 11:52:17 +0100
changeset 1734
9eba43136cb5
parent 1577
4ce7240d622c
child 1862
cd5dbf694d45
permissions
-rw-r--r--

6934494: JSR 292 MethodHandles adapters should be generated into their own CodeBlob
Summary: Passing a null pointer to an InvokeDynamic function call should lead to a NullPointerException.
Reviewed-by: kvn, never

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

mercurial