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