comparison src/share/vm/prims/methodHandles.cpp @ 710:e5b0439ef4ae

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