Tue, 17 May 2011 15:43:46 -0700
7044892: JSR 292: API entry points sometimes throw the wrong exceptions or doesn't throw the expected one
Summary: Fix to 7042656: JSR292: invokeExact/Generic doesn't throw UnsupportedOperationException if invoked via Method.invoke
Reviewed-by: never
1 /*
2 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "precompiled.hpp"
26 #include "classfile/symbolTable.hpp"
27 #include "interpreter/interpreter.hpp"
28 #include "memory/allocation.inline.hpp"
29 #include "memory/oopFactory.hpp"
30 #include "prims/methodHandles.hpp"
31 #include "runtime/javaCalls.hpp"
32 #include "runtime/reflection.hpp"
33 #include "runtime/signature.hpp"
34 #include "runtime/stubRoutines.hpp"
36 /*
37 * JSR 292 reference implementation: method handles
38 */
40 bool MethodHandles::_enabled = false; // set true after successful native linkage
42 MethodHandleEntry* MethodHandles::_entries[MethodHandles::_EK_LIMIT] = {NULL};
43 const char* MethodHandles::_entry_names[_EK_LIMIT+1] = {
44 "raise_exception",
45 "invokestatic", // how a MH emulates invokestatic
46 "invokespecial", // ditto for the other invokes...
47 "invokevirtual",
48 "invokeinterface",
49 "bound_ref", // these are for BMH...
50 "bound_int",
51 "bound_long",
52 "bound_ref_direct", // (direct versions have a direct methodOop)
53 "bound_int_direct",
54 "bound_long_direct",
56 // starting at _adapter_mh_first:
57 "adapter_retype_only", // these are for AMH...
58 "adapter_retype_raw",
59 "adapter_check_cast",
60 "adapter_prim_to_prim",
61 "adapter_ref_to_prim",
62 "adapter_prim_to_ref",
63 "adapter_swap_args",
64 "adapter_rot_args",
65 "adapter_dup_args",
66 "adapter_drop_args",
67 "adapter_collect_args",
68 "adapter_spread_args",
69 "adapter_fold_args",
70 "adapter_unused_13",
72 // optimized adapter types:
73 "adapter_swap_args/1",
74 "adapter_swap_args/2",
75 "adapter_rot_args/1,up",
76 "adapter_rot_args/1,down",
77 "adapter_rot_args/2,up",
78 "adapter_rot_args/2,down",
79 "adapter_prim_to_prim/i2i",
80 "adapter_prim_to_prim/l2i",
81 "adapter_prim_to_prim/d2f",
82 "adapter_prim_to_prim/i2l",
83 "adapter_prim_to_prim/f2d",
84 "adapter_ref_to_prim/unboxi",
85 "adapter_ref_to_prim/unboxl",
87 // return value handlers for collect/filter/fold adapters:
88 "return/ref",
89 "return/int",
90 "return/long",
91 "return/float",
92 "return/double",
93 "return/void",
94 "return/S0/ref",
95 "return/S1/ref",
96 "return/S2/ref",
97 "return/S3/ref",
98 "return/S4/ref",
99 "return/S5/ref",
100 "return/any",
102 // spreading (array length cases 0, 1, ...)
103 "adapter_spread/0",
104 "adapter_spread/1/ref",
105 "adapter_spread/2/ref",
106 "adapter_spread/3/ref",
107 "adapter_spread/4/ref",
108 "adapter_spread/5/ref",
109 "adapter_spread/ref",
110 "adapter_spread/byte",
111 "adapter_spread/char",
112 "adapter_spread/short",
113 "adapter_spread/int",
114 "adapter_spread/long",
115 "adapter_spread/float",
116 "adapter_spread/double",
118 // blocking filter/collect conversions:
119 "adapter_collect/ref",
120 "adapter_collect/int",
121 "adapter_collect/long",
122 "adapter_collect/float",
123 "adapter_collect/double",
124 "adapter_collect/void",
125 "adapter_collect/0/ref",
126 "adapter_collect/1/ref",
127 "adapter_collect/2/ref",
128 "adapter_collect/3/ref",
129 "adapter_collect/4/ref",
130 "adapter_collect/5/ref",
131 "adapter_filter/S0/ref",
132 "adapter_filter/S1/ref",
133 "adapter_filter/S2/ref",
134 "adapter_filter/S3/ref",
135 "adapter_filter/S4/ref",
136 "adapter_filter/S5/ref",
137 "adapter_collect/2/S0/ref",
138 "adapter_collect/2/S1/ref",
139 "adapter_collect/2/S2/ref",
140 "adapter_collect/2/S3/ref",
141 "adapter_collect/2/S4/ref",
142 "adapter_collect/2/S5/ref",
144 // blocking fold conversions:
145 "adapter_fold/ref",
146 "adapter_fold/int",
147 "adapter_fold/long",
148 "adapter_fold/float",
149 "adapter_fold/double",
150 "adapter_fold/void",
151 "adapter_fold/1/ref",
152 "adapter_fold/2/ref",
153 "adapter_fold/3/ref",
154 "adapter_fold/4/ref",
155 "adapter_fold/5/ref",
157 NULL
158 };
160 // Adapters.
161 MethodHandlesAdapterBlob* MethodHandles::_adapter_code = NULL;
162 int MethodHandles::_adapter_code_size = StubRoutines::method_handles_adapters_code_size;
164 jobject MethodHandles::_raise_exception_method;
166 address MethodHandles::_adapter_return_handlers[CONV_TYPE_MASK+1];
168 #ifdef ASSERT
169 bool MethodHandles::spot_check_entry_names() {
170 assert(!strcmp(entry_name(_invokestatic_mh), "invokestatic"), "");
171 assert(!strcmp(entry_name(_bound_ref_mh), "bound_ref"), "");
172 assert(!strcmp(entry_name(_adapter_retype_only), "adapter_retype_only"), "");
173 assert(!strcmp(entry_name(_adapter_fold_args), "adapter_fold_args"), "");
174 assert(!strcmp(entry_name(_adapter_opt_unboxi), "adapter_ref_to_prim/unboxi"), "");
175 assert(!strcmp(entry_name(_adapter_opt_spread_char), "adapter_spread/char"), "");
176 assert(!strcmp(entry_name(_adapter_opt_spread_double), "adapter_spread/double"), "");
177 assert(!strcmp(entry_name(_adapter_opt_collect_int), "adapter_collect/int"), "");
178 assert(!strcmp(entry_name(_adapter_opt_collect_0_ref), "adapter_collect/0/ref"), "");
179 assert(!strcmp(entry_name(_adapter_opt_collect_2_S3_ref), "adapter_collect/2/S3/ref"), "");
180 assert(!strcmp(entry_name(_adapter_opt_filter_S5_ref), "adapter_filter/S5/ref"), "");
181 assert(!strcmp(entry_name(_adapter_opt_fold_3_ref), "adapter_fold/3/ref"), "");
182 assert(!strcmp(entry_name(_adapter_opt_fold_void), "adapter_fold/void"), "");
183 return true;
184 }
185 #endif
188 //------------------------------------------------------------------------------
189 // MethodHandles::generate_adapters
190 //
191 void MethodHandles::generate_adapters() {
192 #ifdef TARGET_ARCH_NYI_6939861
193 if (FLAG_IS_DEFAULT(UseRicochetFrames)) UseRicochetFrames = false;
194 #endif
195 if (!EnableInvokeDynamic || SystemDictionary::MethodHandle_klass() == NULL) return;
197 assert(_adapter_code == NULL, "generate only once");
199 ResourceMark rm;
200 TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
201 _adapter_code = MethodHandlesAdapterBlob::create(_adapter_code_size);
202 if (_adapter_code == NULL)
203 vm_exit_out_of_memory(_adapter_code_size, "CodeCache: no room for MethodHandles adapters");
204 CodeBuffer code(_adapter_code);
205 MethodHandlesAdapterGenerator g(&code);
206 g.generate();
207 }
209 //------------------------------------------------------------------------------
210 // MethodHandlesAdapterGenerator::generate
211 //
212 void MethodHandlesAdapterGenerator::generate() {
213 // Generate generic method handle adapters.
214 for (MethodHandles::EntryKind ek = MethodHandles::_EK_FIRST;
215 ek < MethodHandles::_EK_LIMIT;
216 ek = MethodHandles::EntryKind(1 + (int)ek)) {
217 if (MethodHandles::ek_supported(ek)) {
218 StubCodeMark mark(this, "MethodHandle", MethodHandles::entry_name(ek));
219 MethodHandles::generate_method_handle_stub(_masm, ek);
220 }
221 }
222 }
225 #ifdef TARGET_ARCH_NYI_6939861
226 // these defs belong in methodHandles_<arch>.cpp
227 frame MethodHandles::ricochet_frame_sender(const frame& fr, RegisterMap *map) {
228 ShouldNotCallThis();
229 return fr;
230 }
231 void MethodHandles::ricochet_frame_oops_do(const frame& fr, OopClosure* f, const RegisterMap* reg_map) {
232 ShouldNotCallThis();
233 }
234 #endif //TARGET_ARCH_NYI_6939861
237 //------------------------------------------------------------------------------
238 // MethodHandles::ek_supported
239 //
240 bool MethodHandles::ek_supported(MethodHandles::EntryKind ek) {
241 MethodHandles::EntryKind ek_orig = MethodHandles::ek_original_kind(ek);
242 switch (ek_orig) {
243 case _adapter_unused_13:
244 return false; // not defined yet
245 case _adapter_prim_to_ref:
246 return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_PRIM_TO_REF);
247 case _adapter_collect_args:
248 return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_COLLECT_ARGS);
249 case _adapter_fold_args:
250 return UseRicochetFrames && conv_op_supported(java_lang_invoke_AdapterMethodHandle::OP_FOLD_ARGS);
251 case _adapter_opt_return_any:
252 return UseRicochetFrames;
253 #ifdef TARGET_ARCH_NYI_6939861
254 // ports before 6939861 supported only three kinds of spread ops
255 case _adapter_spread_args:
256 // restrict spreads to three kinds:
257 switch (ek) {
258 case _adapter_opt_spread_0:
259 case _adapter_opt_spread_1:
260 case _adapter_opt_spread_more:
261 break;
262 default:
263 return false;
264 break;
265 }
266 break;
267 #endif //TARGET_ARCH_NYI_6939861
268 }
269 return true;
270 }
273 void MethodHandles::set_enabled(bool z) {
274 if (_enabled != z) {
275 guarantee(z && EnableInvokeDynamic, "can only enable once, and only if -XX:+EnableInvokeDynamic");
276 _enabled = z;
277 }
278 }
280 // Note: A method which does not have a TRAPS argument cannot block in the GC
281 // or throw exceptions. Such methods are used in this file to do something quick
282 // and local, like parse a data structure. For speed, such methods work on plain
283 // oops, not handles. Trapping methods uniformly operate on handles.
285 methodHandle MethodHandles::decode_vmtarget(oop vmtarget, int vmindex, oop mtype,
286 KlassHandle& receiver_limit_result, int& decode_flags_result) {
287 if (vmtarget == NULL) return methodHandle();
288 assert(methodOopDesc::nonvirtual_vtable_index < 0, "encoding");
289 if (vmindex < 0) {
290 // this DMH performs no dispatch; it is directly bound to a methodOop
291 // A MemberName may either be directly bound to a methodOop,
292 // or it may use the klass/index form; both forms mean the same thing.
293 methodOop m = decode_methodOop(methodOop(vmtarget), decode_flags_result);
294 if ((decode_flags_result & _dmf_has_receiver) != 0
295 && java_lang_invoke_MethodType::is_instance(mtype)) {
296 // Extract receiver type restriction from mtype.ptypes[0].
297 objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(mtype);
298 oop ptype0 = (ptypes == NULL || ptypes->length() < 1) ? oop(NULL) : ptypes->obj_at(0);
299 if (java_lang_Class::is_instance(ptype0))
300 receiver_limit_result = java_lang_Class::as_klassOop(ptype0);
301 }
302 if (vmindex == methodOopDesc::nonvirtual_vtable_index) {
303 // this DMH can be an "invokespecial" version
304 decode_flags_result &= ~_dmf_does_dispatch;
305 } else {
306 assert(vmindex == methodOopDesc::invalid_vtable_index, "random vmindex?");
307 }
308 return m;
309 } else {
310 assert(vmtarget->is_klass(), "must be class or interface");
311 decode_flags_result |= MethodHandles::_dmf_does_dispatch;
312 decode_flags_result |= MethodHandles::_dmf_has_receiver;
313 receiver_limit_result = (klassOop)vmtarget;
314 Klass* tk = Klass::cast((klassOop)vmtarget);
315 if (tk->is_interface()) {
316 // an itable linkage is <interface, itable index>
317 decode_flags_result |= MethodHandles::_dmf_from_interface;
318 return klassItable::method_for_itable_index((klassOop)vmtarget, vmindex);
319 } else {
320 if (!tk->oop_is_instance())
321 tk = instanceKlass::cast(SystemDictionary::Object_klass());
322 return ((instanceKlass*)tk)->method_at_vtable(vmindex);
323 }
324 }
325 }
327 // MemberName and DirectMethodHandle have the same linkage to the JVM internals.
328 // (MemberName is the non-operational name used for queries and setup.)
330 methodHandle MethodHandles::decode_DirectMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
331 oop vmtarget = java_lang_invoke_DirectMethodHandle::vmtarget(mh);
332 int vmindex = java_lang_invoke_DirectMethodHandle::vmindex(mh);
333 oop mtype = java_lang_invoke_DirectMethodHandle::type(mh);
334 return decode_vmtarget(vmtarget, vmindex, mtype, receiver_limit_result, decode_flags_result);
335 }
337 methodHandle MethodHandles::decode_BoundMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
338 assert(java_lang_invoke_BoundMethodHandle::is_instance(mh), "");
339 assert(mh->klass() != SystemDictionary::AdapterMethodHandle_klass(), "");
340 for (oop bmh = mh;;) {
341 // Bound MHs can be stacked to bind several arguments.
342 oop target = java_lang_invoke_MethodHandle::vmtarget(bmh);
343 if (target == NULL) return methodHandle();
344 decode_flags_result |= MethodHandles::_dmf_binds_argument;
345 klassOop tk = target->klass();
346 if (tk == SystemDictionary::BoundMethodHandle_klass()) {
347 bmh = target;
348 continue;
349 } else {
350 if (java_lang_invoke_MethodHandle::is_subclass(tk)) {
351 //assert(tk == SystemDictionary::DirectMethodHandle_klass(), "end of BMH chain must be DMH");
352 return decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
353 } else {
354 // Optimized case: binding a receiver to a non-dispatched DMH
355 // short-circuits directly to the methodOop.
356 // (It might be another argument besides a receiver also.)
357 assert(target->is_method(), "must be a simple method");
358 decode_flags_result |= MethodHandles::_dmf_binds_method;
359 methodOop m = (methodOop) target;
360 if (!m->is_static())
361 decode_flags_result |= MethodHandles::_dmf_has_receiver;
362 return m;
363 }
364 }
365 }
366 }
368 methodHandle MethodHandles::decode_AdapterMethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
369 assert(mh->klass() == SystemDictionary::AdapterMethodHandle_klass(), "");
370 for (oop amh = mh;;) {
371 // Adapter MHs can be stacked to convert several arguments.
372 int conv_op = adapter_conversion_op(java_lang_invoke_AdapterMethodHandle::conversion(amh));
373 decode_flags_result |= (_dmf_adapter_lsb << conv_op) & _DMF_ADAPTER_MASK;
374 oop target = java_lang_invoke_MethodHandle::vmtarget(amh);
375 if (target == NULL) return methodHandle();
376 klassOop tk = target->klass();
377 if (tk == SystemDictionary::AdapterMethodHandle_klass()) {
378 amh = target;
379 continue;
380 } else {
381 // must be a BMH (which will bind some more arguments) or a DMH (for the final call)
382 return MethodHandles::decode_MethodHandle(target, receiver_limit_result, decode_flags_result);
383 }
384 }
385 }
387 methodHandle MethodHandles::decode_MethodHandle(oop mh, KlassHandle& receiver_limit_result, int& decode_flags_result) {
388 if (mh == NULL) return methodHandle();
389 klassOop mhk = mh->klass();
390 assert(java_lang_invoke_MethodHandle::is_subclass(mhk), "must be a MethodHandle");
391 if (mhk == SystemDictionary::DirectMethodHandle_klass()) {
392 return decode_DirectMethodHandle(mh, receiver_limit_result, decode_flags_result);
393 } else if (mhk == SystemDictionary::BoundMethodHandle_klass()) {
394 return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
395 } else if (mhk == SystemDictionary::AdapterMethodHandle_klass()) {
396 return decode_AdapterMethodHandle(mh, receiver_limit_result, decode_flags_result);
397 } else if (java_lang_invoke_BoundMethodHandle::is_subclass(mhk)) {
398 // could be a JavaMethodHandle (but not an adapter MH)
399 return decode_BoundMethodHandle(mh, receiver_limit_result, decode_flags_result);
400 } else {
401 assert(false, "cannot parse this MH");
402 return methodHandle(); // random MH?
403 }
404 }
406 methodOop MethodHandles::decode_methodOop(methodOop m, int& decode_flags_result) {
407 assert(m->is_method(), "");
408 if (m->is_static()) {
409 // check that signature begins '(L' or '([' (not '(I', '()', etc.)
410 Symbol* sig = m->signature();
411 BasicType recv_bt = char2type(sig->byte_at(1));
412 // Note: recv_bt might be T_ILLEGAL if byte_at(2) is ')'
413 assert(sig->byte_at(0) == '(', "must be method sig");
414 // if (recv_bt == T_OBJECT || recv_bt == T_ARRAY)
415 // decode_flags_result |= _dmf_has_receiver;
416 } else {
417 // non-static method
418 decode_flags_result |= _dmf_has_receiver;
419 if (!m->can_be_statically_bound() && !m->is_initializer()) {
420 decode_flags_result |= _dmf_does_dispatch;
421 if (Klass::cast(m->method_holder())->is_interface())
422 decode_flags_result |= _dmf_from_interface;
423 }
424 }
425 return m;
426 }
429 // A trusted party is handing us a cookie to determine a method.
430 // Let's boil it down to the method oop they really want.
431 methodHandle MethodHandles::decode_method(oop x, KlassHandle& receiver_limit_result, int& decode_flags_result) {
432 decode_flags_result = 0;
433 receiver_limit_result = KlassHandle();
434 klassOop xk = x->klass();
435 if (xk == Universe::methodKlassObj()) {
436 return decode_methodOop((methodOop) x, decode_flags_result);
437 } else if (xk == SystemDictionary::MemberName_klass()) {
438 // Note: This only works if the MemberName has already been resolved.
439 return decode_MemberName(x, receiver_limit_result, decode_flags_result);
440 } else if (java_lang_invoke_MethodHandle::is_subclass(xk)) {
441 return decode_MethodHandle(x, receiver_limit_result, decode_flags_result);
442 } else if (xk == SystemDictionary::reflect_Method_klass()) {
443 oop clazz = java_lang_reflect_Method::clazz(x);
444 int slot = java_lang_reflect_Method::slot(x);
445 klassOop k = java_lang_Class::as_klassOop(clazz);
446 if (k != NULL && Klass::cast(k)->oop_is_instance())
447 return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
448 decode_flags_result);
449 } else if (xk == SystemDictionary::reflect_Constructor_klass()) {
450 oop clazz = java_lang_reflect_Constructor::clazz(x);
451 int slot = java_lang_reflect_Constructor::slot(x);
452 klassOop k = java_lang_Class::as_klassOop(clazz);
453 if (k != NULL && Klass::cast(k)->oop_is_instance())
454 return decode_methodOop(instanceKlass::cast(k)->method_with_idnum(slot),
455 decode_flags_result);
456 } else {
457 // unrecognized object
458 assert(!x->is_method(), "already checked");
459 assert(!java_lang_invoke_MemberName::is_instance(x), "already checked");
460 }
461 return methodHandle();
462 }
465 int MethodHandles::decode_MethodHandle_stack_pushes(oop mh) {
466 if (mh->klass() == SystemDictionary::DirectMethodHandle_klass())
467 return 0; // no push/pop
468 int this_vmslots = java_lang_invoke_MethodHandle::vmslots(mh);
469 int last_vmslots = 0;
470 oop last_mh = mh;
471 for (;;) {
472 oop target = java_lang_invoke_MethodHandle::vmtarget(last_mh);
473 if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
474 last_vmslots = java_lang_invoke_MethodHandle::vmslots(target);
475 break;
476 } else if (!java_lang_invoke_MethodHandle::is_instance(target)) {
477 // might be klass or method
478 assert(target->is_method(), "must get here with a direct ref to method");
479 last_vmslots = methodOop(target)->size_of_parameters();
480 break;
481 }
482 last_mh = target;
483 }
484 // If I am called with fewer VM slots than my ultimate callee,
485 // it must be that I push the additionally needed slots.
486 // Likewise if am called with more VM slots, I will pop them.
487 return (last_vmslots - this_vmslots);
488 }
491 // MemberName support
493 // import java_lang_invoke_MemberName.*
494 enum {
495 IS_METHOD = java_lang_invoke_MemberName::MN_IS_METHOD,
496 IS_CONSTRUCTOR = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
497 IS_FIELD = java_lang_invoke_MemberName::MN_IS_FIELD,
498 IS_TYPE = java_lang_invoke_MemberName::MN_IS_TYPE,
499 SEARCH_SUPERCLASSES = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
500 SEARCH_INTERFACES = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
501 ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE,
502 VM_INDEX_UNINITIALIZED = java_lang_invoke_MemberName::VM_INDEX_UNINITIALIZED
503 };
505 Handle MethodHandles::new_MemberName(TRAPS) {
506 Handle empty;
507 instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
508 if (!k->is_initialized()) k->initialize(CHECK_(empty));
509 return Handle(THREAD, k->allocate_instance(THREAD));
510 }
512 void MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
513 if (target_oop->klass() == SystemDictionary::reflect_Field_klass()) {
514 oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
515 int slot = java_lang_reflect_Field::slot(target_oop); // fd.index()
516 int mods = java_lang_reflect_Field::modifiers(target_oop);
517 klassOop k = java_lang_Class::as_klassOop(clazz);
518 int offset = instanceKlass::cast(k)->offset_from_fields(slot);
519 init_MemberName(mname_oop, k, accessFlags_from(mods), offset);
520 } else {
521 KlassHandle receiver_limit; int decode_flags = 0;
522 methodHandle m = MethodHandles::decode_method(target_oop, receiver_limit, decode_flags);
523 bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
524 init_MemberName(mname_oop, m(), do_dispatch);
525 }
526 }
528 void MethodHandles::init_MemberName(oop mname_oop, methodOop m, bool do_dispatch) {
529 int flags = ((m->is_initializer() ? IS_CONSTRUCTOR : IS_METHOD)
530 | (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS ));
531 oop vmtarget = m;
532 int vmindex = methodOopDesc::invalid_vtable_index; // implies no info yet
533 if (!do_dispatch || (flags & IS_CONSTRUCTOR) || m->can_be_statically_bound())
534 vmindex = methodOopDesc::nonvirtual_vtable_index; // implies never any dispatch
535 assert(vmindex != VM_INDEX_UNINITIALIZED, "Java sentinel value");
536 java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
537 java_lang_invoke_MemberName::set_vmindex(mname_oop, vmindex);
538 java_lang_invoke_MemberName::set_flags(mname_oop, flags);
539 java_lang_invoke_MemberName::set_clazz(mname_oop, Klass::cast(m->method_holder())->java_mirror());
540 }
542 void MethodHandles::init_MemberName(oop mname_oop, klassOop field_holder, AccessFlags mods, int offset) {
543 int flags = (IS_FIELD | (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS ));
544 oop vmtarget = field_holder;
545 int vmindex = offset; // determines the field uniquely when combined with static bit
546 assert(vmindex != VM_INDEX_UNINITIALIZED, "bad alias on vmindex");
547 java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
548 java_lang_invoke_MemberName::set_vmindex(mname_oop, vmindex);
549 java_lang_invoke_MemberName::set_flags(mname_oop, flags);
550 java_lang_invoke_MemberName::set_clazz(mname_oop, Klass::cast(field_holder)->java_mirror());
551 }
554 methodHandle MethodHandles::decode_MemberName(oop mname, KlassHandle& receiver_limit_result, int& decode_flags_result) {
555 methodHandle empty;
556 int flags = java_lang_invoke_MemberName::flags(mname);
557 if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) == 0) return empty; // not invocable
558 oop vmtarget = java_lang_invoke_MemberName::vmtarget(mname);
559 int vmindex = java_lang_invoke_MemberName::vmindex(mname);
560 if (vmindex == VM_INDEX_UNINITIALIZED) return empty; // not resolved
561 methodHandle m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit_result, decode_flags_result);
562 oop clazz = java_lang_invoke_MemberName::clazz(mname);
563 if (clazz != NULL && java_lang_Class::is_instance(clazz)) {
564 klassOop klass = java_lang_Class::as_klassOop(clazz);
565 if (klass != NULL) receiver_limit_result = klass;
566 }
567 return m;
568 }
570 // convert the external string or reflective type to an internal signature
571 Symbol* MethodHandles::convert_to_signature(oop type_str, bool polymorphic, TRAPS) {
572 if (java_lang_invoke_MethodType::is_instance(type_str)) {
573 return java_lang_invoke_MethodType::as_signature(type_str, polymorphic, CHECK_NULL);
574 } else if (java_lang_Class::is_instance(type_str)) {
575 return java_lang_Class::as_signature(type_str, false, CHECK_NULL);
576 } else if (java_lang_String::is_instance(type_str)) {
577 if (polymorphic) {
578 return java_lang_String::as_symbol(type_str, CHECK_NULL);
579 } else {
580 return java_lang_String::as_symbol_or_null(type_str);
581 }
582 } else {
583 THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", NULL);
584 }
585 }
587 // An unresolved member name is a mere symbolic reference.
588 // Resolving it plants a vmtarget/vmindex in it,
589 // which refers dirctly to JVM internals.
590 void MethodHandles::resolve_MemberName(Handle mname, TRAPS) {
591 assert(java_lang_invoke_MemberName::is_instance(mname()), "");
592 #ifdef ASSERT
593 // If this assert throws, renegotiate the sentinel value used by the Java code,
594 // so that it is distinct from any valid vtable index value, and any special
595 // values defined in methodOopDesc::VtableIndexFlag.
596 // The point of the slop is to give the Java code and the JVM some room
597 // to independently specify sentinel values.
598 const int sentinel_slop = 10;
599 const int sentinel_limit = methodOopDesc::highest_unused_vtable_index_value - sentinel_slop;
600 assert(VM_INDEX_UNINITIALIZED < sentinel_limit, "Java sentinel != JVM sentinels");
601 #endif
602 if (java_lang_invoke_MemberName::vmindex(mname()) != VM_INDEX_UNINITIALIZED)
603 return; // already resolved
604 Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
605 Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
606 Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
607 int flags = java_lang_invoke_MemberName::flags(mname());
609 if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
610 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve");
611 }
613 instanceKlassHandle defc;
614 {
615 klassOop defc_klassOop = java_lang_Class::as_klassOop(defc_oop());
616 if (defc_klassOop == NULL) return; // a primitive; no resolution possible
617 if (!Klass::cast(defc_klassOop)->oop_is_instance()) {
618 if (!Klass::cast(defc_klassOop)->oop_is_array()) return;
619 defc_klassOop = SystemDictionary::Object_klass();
620 }
621 defc = instanceKlassHandle(THREAD, defc_klassOop);
622 }
623 if (defc.is_null()) {
624 THROW_MSG(vmSymbols::java_lang_InternalError(), "primitive class");
625 }
626 defc->link_class(CHECK); // possible safepoint
628 // convert the external string name to an internal symbol
629 TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
630 if (name == NULL) return; // no such name
632 Handle polymorphic_method_type;
633 bool polymorphic_signature = false;
634 if ((flags & ALL_KINDS) == IS_METHOD &&
635 (defc() == SystemDictionary::MethodHandle_klass() &&
636 methodOopDesc::is_method_handle_invoke_name(name))) {
637 polymorphic_signature = true;
638 }
640 // convert the external string or reflective type to an internal signature
641 TempNewSymbol type = convert_to_signature(type_str(), polymorphic_signature, CHECK);
642 if (java_lang_invoke_MethodType::is_instance(type_str()) && polymorphic_signature) {
643 polymorphic_method_type = type_str; // preserve exactly
644 }
645 if (type == NULL) return; // no such signature exists in the VM
647 // Time to do the lookup.
648 switch (flags & ALL_KINDS) {
649 case IS_METHOD:
650 {
651 CallInfo result;
652 {
653 EXCEPTION_MARK;
654 if ((flags & JVM_ACC_STATIC) != 0) {
655 LinkResolver::resolve_static_call(result,
656 defc, name, type, KlassHandle(), false, false, THREAD);
657 } else if (defc->is_interface()) {
658 LinkResolver::resolve_interface_call(result, Handle(), defc,
659 defc, name, type, KlassHandle(), false, false, THREAD);
660 } else {
661 LinkResolver::resolve_virtual_call(result, Handle(), defc,
662 defc, name, type, KlassHandle(), false, false, THREAD);
663 }
664 if (HAS_PENDING_EXCEPTION) {
665 CLEAR_PENDING_EXCEPTION;
666 break; // go to second chance
667 }
668 }
669 methodHandle m = result.resolved_method();
670 oop vmtarget = NULL;
671 int vmindex = methodOopDesc::nonvirtual_vtable_index;
672 if (defc->is_interface()) {
673 vmindex = klassItable::compute_itable_index(m());
674 assert(vmindex >= 0, "");
675 } else if (result.has_vtable_index()) {
676 vmindex = result.vtable_index();
677 assert(vmindex >= 0, "");
678 }
679 assert(vmindex != VM_INDEX_UNINITIALIZED, "");
680 if (vmindex < 0) {
681 assert(result.is_statically_bound(), "");
682 vmtarget = m();
683 } else {
684 vmtarget = result.resolved_klass()->as_klassOop();
685 }
686 int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
687 java_lang_invoke_MemberName::set_vmtarget(mname(), vmtarget);
688 java_lang_invoke_MemberName::set_vmindex(mname(), vmindex);
689 java_lang_invoke_MemberName::set_modifiers(mname(), mods);
690 DEBUG_ONLY(KlassHandle junk1; int junk2);
691 assert(decode_MemberName(mname(), junk1, junk2) == result.resolved_method(),
692 "properly stored for later decoding");
693 return;
694 }
695 case IS_CONSTRUCTOR:
696 {
697 CallInfo result;
698 {
699 EXCEPTION_MARK;
700 if (name == vmSymbols::object_initializer_name()) {
701 LinkResolver::resolve_special_call(result,
702 defc, name, type, KlassHandle(), false, THREAD);
703 } else {
704 break; // will throw after end of switch
705 }
706 if (HAS_PENDING_EXCEPTION) {
707 CLEAR_PENDING_EXCEPTION;
708 return;
709 }
710 }
711 assert(result.is_statically_bound(), "");
712 methodHandle m = result.resolved_method();
713 oop vmtarget = m();
714 int vmindex = methodOopDesc::nonvirtual_vtable_index;
715 int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
716 java_lang_invoke_MemberName::set_vmtarget(mname(), vmtarget);
717 java_lang_invoke_MemberName::set_vmindex(mname(), vmindex);
718 java_lang_invoke_MemberName::set_modifiers(mname(), mods);
719 DEBUG_ONLY(KlassHandle junk1; int junk2);
720 assert(decode_MemberName(mname(), junk1, junk2) == result.resolved_method(),
721 "properly stored for later decoding");
722 return;
723 }
724 case IS_FIELD:
725 {
726 // This is taken from LinkResolver::resolve_field, sans access checks.
727 fieldDescriptor fd; // find_field initializes fd if found
728 KlassHandle sel_klass(THREAD, instanceKlass::cast(defc())->find_field(name, type, &fd));
729 // check if field exists; i.e., if a klass containing the field def has been selected
730 if (sel_klass.is_null()) return;
731 oop vmtarget = sel_klass->as_klassOop();
732 int vmindex = fd.offset();
733 int mods = (fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS);
734 if (vmindex == VM_INDEX_UNINITIALIZED) break; // should not happen
735 java_lang_invoke_MemberName::set_vmtarget(mname(), vmtarget);
736 java_lang_invoke_MemberName::set_vmindex(mname(), vmindex);
737 java_lang_invoke_MemberName::set_modifiers(mname(), mods);
738 return;
739 }
740 default:
741 THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
742 }
744 // Second chance.
745 if (polymorphic_method_type.not_null()) {
746 // Look on a non-null class loader.
747 Handle cur_class_loader;
748 const int nptypes = java_lang_invoke_MethodType::ptype_count(polymorphic_method_type());
749 for (int i = 0; i <= nptypes; i++) {
750 oop type_mirror;
751 if (i < nptypes) type_mirror = java_lang_invoke_MethodType::ptype(polymorphic_method_type(), i);
752 else type_mirror = java_lang_invoke_MethodType::rtype(polymorphic_method_type());
753 klassOop example_type = java_lang_Class::as_klassOop(type_mirror);
754 if (example_type == NULL) continue;
755 oop class_loader = Klass::cast(example_type)->class_loader();
756 if (class_loader == NULL || class_loader == cur_class_loader()) continue;
757 cur_class_loader = Handle(THREAD, class_loader);
758 methodOop m = SystemDictionary::find_method_handle_invoke(name,
759 type,
760 KlassHandle(THREAD, example_type),
761 THREAD);
762 if (HAS_PENDING_EXCEPTION) {
763 CLEAR_PENDING_EXCEPTION;
764 m = NULL;
765 // try again with a different class loader...
766 }
767 if (m != NULL) {
768 int mods = (m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS);
769 java_lang_invoke_MemberName::set_vmtarget(mname(), m);
770 java_lang_invoke_MemberName::set_vmindex(mname(), m->vtable_index());
771 java_lang_invoke_MemberName::set_modifiers(mname(), mods);
772 return;
773 }
774 }
775 }
776 }
778 // Conversely, a member name which is only initialized from JVM internals
779 // may have null defc, name, and type fields.
780 // Resolving it plants a vmtarget/vmindex in it,
781 // which refers directly to JVM internals.
782 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
783 assert(java_lang_invoke_MemberName::is_instance(mname()), "");
784 oop vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
785 int vmindex = java_lang_invoke_MemberName::vmindex(mname());
786 if (vmtarget == NULL || vmindex == VM_INDEX_UNINITIALIZED) {
787 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
788 }
790 bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != NULL);
791 bool have_name = (java_lang_invoke_MemberName::name(mname()) != NULL);
792 bool have_type = (java_lang_invoke_MemberName::type(mname()) != NULL);
793 int flags = java_lang_invoke_MemberName::flags(mname());
795 if (suppress != 0) {
796 if (suppress & _suppress_defc) have_defc = true;
797 if (suppress & _suppress_name) have_name = true;
798 if (suppress & _suppress_type) have_type = true;
799 }
801 if (have_defc && have_name && have_type) return; // nothing needed
803 switch (flags & ALL_KINDS) {
804 case IS_METHOD:
805 case IS_CONSTRUCTOR:
806 {
807 KlassHandle receiver_limit; int decode_flags = 0;
808 methodHandle m = decode_vmtarget(vmtarget, vmindex, NULL, receiver_limit, decode_flags);
809 if (m.is_null()) break;
810 if (!have_defc) {
811 klassOop defc = m->method_holder();
812 if (receiver_limit.not_null() && receiver_limit() != defc
813 && Klass::cast(receiver_limit())->is_subtype_of(defc))
814 defc = receiver_limit();
815 java_lang_invoke_MemberName::set_clazz(mname(), Klass::cast(defc)->java_mirror());
816 }
817 if (!have_name) {
818 //not java_lang_String::create_from_symbol; let's intern member names
819 Handle name = StringTable::intern(m->name(), CHECK);
820 java_lang_invoke_MemberName::set_name(mname(), name());
821 }
822 if (!have_type) {
823 Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
824 java_lang_invoke_MemberName::set_type(mname(), type());
825 }
826 return;
827 }
828 case IS_FIELD:
829 {
830 // This is taken from LinkResolver::resolve_field, sans access checks.
831 if (!vmtarget->is_klass()) break;
832 if (!Klass::cast((klassOop) vmtarget)->oop_is_instance()) break;
833 instanceKlassHandle defc(THREAD, (klassOop) vmtarget);
834 bool is_static = ((flags & JVM_ACC_STATIC) != 0);
835 fieldDescriptor fd; // find_field initializes fd if found
836 if (!defc->find_field_from_offset(vmindex, is_static, &fd))
837 break; // cannot expand
838 if (!have_defc) {
839 java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
840 }
841 if (!have_name) {
842 //not java_lang_String::create_from_symbol; let's intern member names
843 Handle name = StringTable::intern(fd.name(), CHECK);
844 java_lang_invoke_MemberName::set_name(mname(), name());
845 }
846 if (!have_type) {
847 Handle type = java_lang_String::create_from_symbol(fd.signature(), CHECK);
848 java_lang_invoke_MemberName::set_type(mname(), type());
849 }
850 return;
851 }
852 }
853 THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
854 }
856 int MethodHandles::find_MemberNames(klassOop k,
857 Symbol* name, Symbol* sig,
858 int mflags, klassOop caller,
859 int skip, objArrayOop results) {
860 DEBUG_ONLY(No_Safepoint_Verifier nsv);
861 // this code contains no safepoints!
863 // %%% take caller into account!
865 if (k == NULL || !Klass::cast(k)->oop_is_instance()) return -1;
867 int rfill = 0, rlimit = results->length(), rskip = skip;
868 // overflow measurement:
869 int overflow = 0, overflow_limit = MAX2(1000, rlimit);
871 int match_flags = mflags;
872 bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
873 bool search_intfc = ((match_flags & SEARCH_INTERFACES) != 0);
874 bool local_only = !(search_superc | search_intfc);
875 bool classes_only = false;
877 if (name != NULL) {
878 if (name->utf8_length() == 0) return 0; // a match is not possible
879 }
880 if (sig != NULL) {
881 if (sig->utf8_length() == 0) return 0; // a match is not possible
882 if (sig->byte_at(0) == '(')
883 match_flags &= ~(IS_FIELD | IS_TYPE);
884 else
885 match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
886 }
888 if ((match_flags & IS_TYPE) != 0) {
889 // NYI, and Core Reflection works quite well for this query
890 }
892 if ((match_flags & IS_FIELD) != 0) {
893 for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
894 if (name != NULL && st.name() != name)
895 continue;
896 if (sig != NULL && st.signature() != sig)
897 continue;
898 // passed the filters
899 if (rskip > 0) {
900 --rskip;
901 } else if (rfill < rlimit) {
902 oop result = results->obj_at(rfill++);
903 if (!java_lang_invoke_MemberName::is_instance(result))
904 return -99; // caller bug!
905 MethodHandles::init_MemberName(result, st.klass()->as_klassOop(), st.access_flags(), st.offset());
906 } else if (++overflow >= overflow_limit) {
907 match_flags = 0; break; // got tired of looking at overflow
908 }
909 }
910 }
912 if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
913 // watch out for these guys:
914 Symbol* init_name = vmSymbols::object_initializer_name();
915 Symbol* clinit_name = vmSymbols::class_initializer_name();
916 if (name == clinit_name) clinit_name = NULL; // hack for exposing <clinit>
917 bool negate_name_test = false;
918 // fix name so that it captures the intention of IS_CONSTRUCTOR
919 if (!(match_flags & IS_METHOD)) {
920 // constructors only
921 if (name == NULL) {
922 name = init_name;
923 } else if (name != init_name) {
924 return 0; // no constructors of this method name
925 }
926 } else if (!(match_flags & IS_CONSTRUCTOR)) {
927 // methods only
928 if (name == NULL) {
929 name = init_name;
930 negate_name_test = true; // if we see the name, we *omit* the entry
931 } else if (name == init_name) {
932 return 0; // no methods of this constructor name
933 }
934 } else {
935 // caller will accept either sort; no need to adjust name
936 }
937 for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
938 methodOop m = st.method();
939 Symbol* m_name = m->name();
940 if (m_name == clinit_name)
941 continue;
942 if (name != NULL && ((m_name != name) ^ negate_name_test))
943 continue;
944 if (sig != NULL && m->signature() != sig)
945 continue;
946 // passed the filters
947 if (rskip > 0) {
948 --rskip;
949 } else if (rfill < rlimit) {
950 oop result = results->obj_at(rfill++);
951 if (!java_lang_invoke_MemberName::is_instance(result))
952 return -99; // caller bug!
953 MethodHandles::init_MemberName(result, m, true);
954 } else if (++overflow >= overflow_limit) {
955 match_flags = 0; break; // got tired of looking at overflow
956 }
957 }
958 }
960 // return number of elements we at leasted wanted to initialize
961 return rfill + overflow;
962 }
965 // Decode this java.lang.Class object into an instanceKlass, if possible.
966 // Throw IAE if not
967 instanceKlassHandle MethodHandles::resolve_instance_klass(oop java_mirror_oop, TRAPS) {
968 instanceKlassHandle empty;
969 klassOop caller = NULL;
970 if (java_lang_Class::is_instance(java_mirror_oop)) {
971 caller = java_lang_Class::as_klassOop(java_mirror_oop);
972 }
973 if (caller == NULL || !Klass::cast(caller)->oop_is_instance()) {
974 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not a class", empty);
975 }
976 return instanceKlassHandle(THREAD, caller);
977 }
981 // Decode the vmtarget field of a method handle.
982 // Sanitize out methodOops, klassOops, and any other non-Java data.
983 // This is for debugging and reflection.
984 oop MethodHandles::encode_target(Handle mh, int format, TRAPS) {
985 assert(java_lang_invoke_MethodHandle::is_instance(mh()), "must be a MH");
986 if (format == ETF_HANDLE_OR_METHOD_NAME) {
987 oop target = java_lang_invoke_MethodHandle::vmtarget(mh());
988 if (target == NULL) {
989 return NULL; // unformed MH
990 }
991 klassOop tklass = target->klass();
992 if (Klass::cast(tklass)->is_subclass_of(SystemDictionary::Object_klass())) {
993 return target; // target is another MH (or something else?)
994 }
995 }
996 if (format == ETF_DIRECT_HANDLE) {
997 oop target = mh();
998 for (;;) {
999 if (target->klass() == SystemDictionary::DirectMethodHandle_klass()) {
1000 return target;
1001 }
1002 if (!java_lang_invoke_MethodHandle::is_instance(target)){
1003 return NULL; // unformed MH
1004 }
1005 target = java_lang_invoke_MethodHandle::vmtarget(target);
1006 }
1007 }
1008 // cases of metadata in MH.vmtarget:
1009 // - AMH can have methodOop for static invoke with bound receiver
1010 // - DMH can have methodOop for static invoke (on variable receiver)
1011 // - DMH can have klassOop for dispatched (non-static) invoke
1012 KlassHandle receiver_limit; int decode_flags = 0;
1013 methodHandle m = decode_MethodHandle(mh(), receiver_limit, decode_flags);
1014 if (m.is_null()) return NULL;
1015 switch (format) {
1016 case ETF_REFLECT_METHOD:
1017 // same as jni_ToReflectedMethod:
1018 if (m->is_initializer()) {
1019 return Reflection::new_constructor(m, THREAD);
1020 } else {
1021 return Reflection::new_method(m, UseNewReflection, false, THREAD);
1022 }
1024 case ETF_HANDLE_OR_METHOD_NAME: // method, not handle
1025 case ETF_METHOD_NAME:
1026 {
1027 if (SystemDictionary::MemberName_klass() == NULL) break;
1028 instanceKlassHandle mname_klass(THREAD, SystemDictionary::MemberName_klass());
1029 mname_klass->initialize(CHECK_NULL);
1030 Handle mname = mname_klass->allocate_instance_handle(CHECK_NULL); // possible safepoint
1031 java_lang_invoke_MemberName::set_vmindex(mname(), VM_INDEX_UNINITIALIZED);
1032 bool do_dispatch = ((decode_flags & MethodHandles::_dmf_does_dispatch) != 0);
1033 init_MemberName(mname(), m(), do_dispatch);
1034 expand_MemberName(mname, 0, CHECK_NULL);
1035 return mname();
1036 }
1037 }
1039 // Unknown format code.
1040 char msg[50];
1041 jio_snprintf(msg, sizeof(msg), "unknown getTarget format=%d", format);
1042 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), msg);
1043 }
1045 static const char* always_null_names[] = {
1046 "java/lang/Void",
1047 "java/lang/Null",
1048 //"java/lang/Nothing",
1049 "sun/dyn/empty/Empty",
1050 "sun/invoke/empty/Empty",
1051 NULL
1052 };
1054 static bool is_always_null_type(klassOop klass) {
1055 if (klass == NULL) return false; // safety
1056 if (!Klass::cast(klass)->oop_is_instance()) return false;
1057 instanceKlass* ik = instanceKlass::cast(klass);
1058 // Must be on the boot class path:
1059 if (ik->class_loader() != NULL) return false;
1060 // Check the name.
1061 Symbol* name = ik->name();
1062 for (int i = 0; ; i++) {
1063 const char* test_name = always_null_names[i];
1064 if (test_name == NULL) break;
1065 if (name->equals(test_name))
1066 return true;
1067 }
1068 return false;
1069 }
1071 bool MethodHandles::class_cast_needed(klassOop src, klassOop dst) {
1072 if (dst == NULL) return true;
1073 if (src == NULL) return (dst != SystemDictionary::Object_klass());
1074 if (src == dst || dst == SystemDictionary::Object_klass())
1075 return false; // quickest checks
1076 Klass* srck = Klass::cast(src);
1077 Klass* dstk = Klass::cast(dst);
1078 if (dstk->is_interface()) {
1079 // interface receivers can safely be viewed as untyped,
1080 // because interface calls always include a dynamic check
1081 //dstk = Klass::cast(SystemDictionary::Object_klass());
1082 return false;
1083 }
1084 if (srck->is_interface()) {
1085 // interface arguments must be viewed as untyped
1086 //srck = Klass::cast(SystemDictionary::Object_klass());
1087 return true;
1088 }
1089 if (is_always_null_type(src)) {
1090 // some source types are known to be never instantiated;
1091 // they represent references which are always null
1092 // such null references never fail to convert safely
1093 return false;
1094 }
1095 return !srck->is_subclass_of(dstk->as_klassOop());
1096 }
1098 static oop object_java_mirror() {
1099 return Klass::cast(SystemDictionary::Object_klass())->java_mirror();
1100 }
1102 bool MethodHandles::is_float_fixed_reinterpretation_cast(BasicType src, BasicType dst) {
1103 if (src == T_FLOAT) return dst == T_INT;
1104 if (src == T_INT) return dst == T_FLOAT;
1105 if (src == T_DOUBLE) return dst == T_LONG;
1106 if (src == T_LONG) return dst == T_DOUBLE;
1107 return false;
1108 }
1110 bool MethodHandles::same_basic_type_for_arguments(BasicType src,
1111 BasicType dst,
1112 bool raw,
1113 bool for_return) {
1114 if (for_return) {
1115 // return values can always be forgotten:
1116 if (dst == T_VOID) return true;
1117 if (src == T_VOID) return raw && (dst == T_INT);
1118 // We allow caller to receive a garbage int, which is harmless.
1119 // This trick is pulled by trusted code (see VerifyType.canPassRaw).
1120 }
1121 assert(src != T_VOID && dst != T_VOID, "should not be here");
1122 if (src == dst) return true;
1123 if (type2size[src] != type2size[dst]) return false;
1124 if (src == T_OBJECT || dst == T_OBJECT) return false;
1125 if (raw) return true; // bitwise reinterpretation; caller guarantees safety
1126 // allow reinterpretation casts for integral widening
1127 if (is_subword_type(src)) { // subwords can fit in int or other subwords
1128 if (dst == T_INT) // any subword fits in an int
1129 return true;
1130 if (src == T_BOOLEAN) // boolean fits in any subword
1131 return is_subword_type(dst);
1132 if (src == T_BYTE && dst == T_SHORT)
1133 return true; // remaining case: byte fits in short
1134 }
1135 // allow float/fixed reinterpretation casts
1136 if (is_float_fixed_reinterpretation_cast(src, dst))
1137 return true;
1138 return false;
1139 }
1141 const char* MethodHandles::check_method_receiver(methodOop m,
1142 klassOop passed_recv_type) {
1143 assert(!m->is_static(), "caller resp.");
1144 if (passed_recv_type == NULL)
1145 return "receiver type is primitive";
1146 if (class_cast_needed(passed_recv_type, m->method_holder())) {
1147 Klass* formal = Klass::cast(m->method_holder());
1148 return SharedRuntime::generate_class_cast_message("receiver type",
1149 formal->external_name());
1150 }
1151 return NULL; // checks passed
1152 }
1154 // Verify that m's signature can be called type-safely by a method handle
1155 // of the given method type 'mtype'.
1156 // It takes a TRAPS argument because it must perform symbol lookups.
1157 void MethodHandles::verify_method_signature(methodHandle m,
1158 Handle mtype,
1159 int first_ptype_pos,
1160 KlassHandle insert_ptype,
1161 TRAPS) {
1162 Handle mhi_type;
1163 if (m->is_method_handle_invoke()) {
1164 // use this more exact typing instead of the symbolic signature:
1165 mhi_type = Handle(THREAD, m->method_handle_type());
1166 }
1167 objArrayHandle ptypes(THREAD, java_lang_invoke_MethodType::ptypes(mtype()));
1168 int pnum = first_ptype_pos;
1169 int pmax = ptypes->length();
1170 int anum = 0; // method argument
1171 const char* err = NULL;
1172 ResourceMark rm(THREAD);
1173 for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
1174 oop ptype_oop = NULL;
1175 if (ss.at_return_type()) {
1176 if (pnum != pmax)
1177 { err = "too many arguments"; break; }
1178 ptype_oop = java_lang_invoke_MethodType::rtype(mtype());
1179 } else {
1180 if (pnum >= pmax)
1181 { err = "not enough arguments"; break; }
1182 if (pnum >= 0)
1183 ptype_oop = ptypes->obj_at(pnum);
1184 else if (insert_ptype.is_null())
1185 ptype_oop = NULL;
1186 else
1187 ptype_oop = insert_ptype->java_mirror();
1188 pnum += 1;
1189 anum += 1;
1190 }
1191 KlassHandle pklass;
1192 BasicType ptype = T_OBJECT;
1193 bool have_ptype = false;
1194 // missing ptype_oop does not match any non-reference; use Object to report the error
1195 pklass = SystemDictionaryHandles::Object_klass();
1196 if (ptype_oop != NULL) {
1197 have_ptype = true;
1198 klassOop pklass_oop = NULL;
1199 ptype = java_lang_Class::as_BasicType(ptype_oop, &pklass_oop);
1200 pklass = KlassHandle(THREAD, pklass_oop);
1201 }
1202 ptype_oop = NULL; //done with this
1203 KlassHandle aklass;
1204 BasicType atype = ss.type();
1205 if (atype == T_ARRAY) atype = T_OBJECT; // fold all refs to T_OBJECT
1206 if (atype == T_OBJECT) {
1207 if (!have_ptype) {
1208 // null matches any reference
1209 continue;
1210 }
1211 if (mhi_type.is_null()) {
1212 // If we fail to resolve types at this point, we will usually throw an error.
1213 TempNewSymbol name = ss.as_symbol_or_null();
1214 if (name != NULL) {
1215 instanceKlass* mk = instanceKlass::cast(m->method_holder());
1216 Handle loader(THREAD, mk->class_loader());
1217 Handle domain(THREAD, mk->protection_domain());
1218 klassOop aklass_oop = SystemDictionary::resolve_or_null(name, loader, domain, CHECK);
1219 if (aklass_oop != NULL)
1220 aklass = KlassHandle(THREAD, aklass_oop);
1221 }
1222 } else {
1223 // for method handle invokers we don't look at the name in the signature
1224 oop atype_oop;
1225 if (ss.at_return_type())
1226 atype_oop = java_lang_invoke_MethodType::rtype(mhi_type());
1227 else
1228 atype_oop = java_lang_invoke_MethodType::ptype(mhi_type(), anum-1);
1229 klassOop aklass_oop = NULL;
1230 atype = java_lang_Class::as_BasicType(atype_oop, &aklass_oop);
1231 aklass = KlassHandle(THREAD, aklass_oop);
1232 }
1233 }
1234 if (!ss.at_return_type()) {
1235 err = check_argument_type_change(ptype, pklass(), atype, aklass(), anum);
1236 } else {
1237 err = check_return_type_change(atype, aklass(), ptype, pklass()); // note reversal!
1238 }
1239 if (err != NULL) break;
1240 }
1242 if (err != NULL) {
1243 #ifndef PRODUCT
1244 if (PrintMiscellaneous && (Verbose || WizardMode)) {
1245 tty->print("*** verify_method_signature failed: ");
1246 java_lang_invoke_MethodType::print_signature(mtype(), tty);
1247 tty->cr();
1248 tty->print_cr(" first_ptype_pos = %d, insert_ptype = "UINTX_FORMAT, first_ptype_pos, insert_ptype());
1249 tty->print(" Failing method: ");
1250 m->print();
1251 }
1252 #endif //PRODUCT
1253 THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1254 }
1255 }
1257 // Main routine for verifying the MethodHandle.type of a proposed
1258 // direct or bound-direct method handle.
1259 void MethodHandles::verify_method_type(methodHandle m,
1260 Handle mtype,
1261 bool has_bound_recv,
1262 KlassHandle bound_recv_type,
1263 TRAPS) {
1264 bool m_needs_receiver = !m->is_static();
1266 const char* err = NULL;
1268 int first_ptype_pos = m_needs_receiver ? 1 : 0;
1269 if (has_bound_recv) {
1270 first_ptype_pos -= 1; // ptypes do not include the bound argument; start earlier in them
1271 if (m_needs_receiver && bound_recv_type.is_null())
1272 { err = "bound receiver is not an object"; goto die; }
1273 }
1275 if (m_needs_receiver && err == NULL) {
1276 objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(mtype());
1277 if (ptypes->length() < first_ptype_pos)
1278 { err = "receiver argument is missing"; goto die; }
1279 if (has_bound_recv)
1280 err = check_method_receiver(m(), bound_recv_type->as_klassOop());
1281 else
1282 err = check_method_receiver(m(), java_lang_Class::as_klassOop(ptypes->obj_at(first_ptype_pos-1)));
1283 if (err != NULL) goto die;
1284 }
1286 // Check the other arguments for mistypes.
1287 verify_method_signature(m, mtype, first_ptype_pos, bound_recv_type, CHECK);
1288 return;
1290 die:
1291 THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1292 }
1294 void MethodHandles::verify_vmslots(Handle mh, TRAPS) {
1295 // Verify vmslots.
1296 int check_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(mh()));
1297 if (java_lang_invoke_MethodHandle::vmslots(mh()) != check_slots) {
1298 THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH");
1299 }
1300 }
1302 void MethodHandles::verify_vmargslot(Handle mh, int argnum, int argslot, TRAPS) {
1303 // Verify that argslot points at the given argnum.
1304 int check_slot = argument_slot(java_lang_invoke_MethodHandle::type(mh()), argnum);
1305 if (argslot != check_slot || argslot < 0) {
1306 const char* fmt = "for argnum of %d, vmargslot is %d, should be %d";
1307 size_t msglen = strlen(fmt) + 3*11 + 1;
1308 char* msg = NEW_RESOURCE_ARRAY(char, msglen);
1309 jio_snprintf(msg, msglen, fmt, argnum, argslot, check_slot);
1310 THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
1311 }
1312 }
1314 // Verify the correspondence between two method types.
1315 // Apart from the advertised changes, caller method type X must
1316 // be able to invoke the callee method Y type with no violations
1317 // of type integrity.
1318 // Return NULL if all is well, else a short error message.
1319 const char* MethodHandles::check_method_type_change(oop src_mtype, int src_beg, int src_end,
1320 int insert_argnum, oop insert_type,
1321 int change_argnum, oop change_type,
1322 int delete_argnum,
1323 oop dst_mtype, int dst_beg, int dst_end,
1324 bool raw) {
1325 objArrayOop src_ptypes = java_lang_invoke_MethodType::ptypes(src_mtype);
1326 objArrayOop dst_ptypes = java_lang_invoke_MethodType::ptypes(dst_mtype);
1328 int src_max = src_ptypes->length();
1329 int dst_max = dst_ptypes->length();
1331 if (src_end == -1) src_end = src_max;
1332 if (dst_end == -1) dst_end = dst_max;
1334 assert(0 <= src_beg && src_beg <= src_end && src_end <= src_max, "oob");
1335 assert(0 <= dst_beg && dst_beg <= dst_end && dst_end <= dst_max, "oob");
1337 // pending actions; set to -1 when done:
1338 int ins_idx = insert_argnum, chg_idx = change_argnum, del_idx = delete_argnum;
1340 const char* err = NULL;
1342 // Walk along each array of parameter types, including a virtual
1343 // NULL end marker at the end of each.
1344 for (int src_idx = src_beg, dst_idx = dst_beg;
1345 (src_idx <= src_end && dst_idx <= dst_end);
1346 src_idx++, dst_idx++) {
1347 oop src_type = (src_idx == src_end) ? oop(NULL) : src_ptypes->obj_at(src_idx);
1348 oop dst_type = (dst_idx == dst_end) ? oop(NULL) : dst_ptypes->obj_at(dst_idx);
1349 bool fix_null_src_type = false;
1351 // Perform requested edits.
1352 if (ins_idx == src_idx) {
1353 // note that the inserted guy is never affected by a change or deletion
1354 ins_idx = -1;
1355 src_type = insert_type;
1356 fix_null_src_type = true;
1357 --src_idx; // back up to process src type on next loop
1358 src_idx = src_end;
1359 } else {
1360 // note that the changed guy can be immediately deleted
1361 if (chg_idx == src_idx) {
1362 chg_idx = -1;
1363 assert(src_idx < src_end, "oob");
1364 src_type = change_type;
1365 fix_null_src_type = true;
1366 }
1367 if (del_idx == src_idx) {
1368 del_idx = -1;
1369 assert(src_idx < src_end, "oob");
1370 --dst_idx;
1371 continue; // rerun loop after skipping this position
1372 }
1373 }
1375 if (src_type == NULL && fix_null_src_type)
1376 // explicit null in this case matches any dest reference
1377 src_type = (java_lang_Class::is_primitive(dst_type) ? object_java_mirror() : dst_type);
1379 // Compare the two argument types.
1380 if (src_type != dst_type) {
1381 if (src_type == NULL) return "not enough arguments";
1382 if (dst_type == NULL) return "too many arguments";
1383 err = check_argument_type_change(src_type, dst_type, dst_idx, raw);
1384 if (err != NULL) return err;
1385 }
1386 }
1388 // Now compare return types also.
1389 oop src_rtype = java_lang_invoke_MethodType::rtype(src_mtype);
1390 oop dst_rtype = java_lang_invoke_MethodType::rtype(dst_mtype);
1391 if (src_rtype != dst_rtype) {
1392 err = check_return_type_change(dst_rtype, src_rtype, raw); // note reversal!
1393 if (err != NULL) return err;
1394 }
1396 assert(err == NULL, "");
1397 return NULL; // all is well
1398 }
1401 const char* MethodHandles::check_argument_type_change(BasicType src_type,
1402 klassOop src_klass,
1403 BasicType dst_type,
1404 klassOop dst_klass,
1405 int argnum,
1406 bool raw) {
1407 const char* err = NULL;
1408 const bool for_return = (argnum < 0);
1410 // just in case:
1411 if (src_type == T_ARRAY) src_type = T_OBJECT;
1412 if (dst_type == T_ARRAY) dst_type = T_OBJECT;
1414 // Produce some nice messages if VerifyMethodHandles is turned on:
1415 if (!same_basic_type_for_arguments(src_type, dst_type, raw, for_return)) {
1416 if (src_type == T_OBJECT) {
1417 if (raw && is_java_primitive(dst_type))
1418 return NULL; // ref-to-prim discards ref and returns zero
1419 err = (!for_return
1420 ? "type mismatch: passing a %s for method argument #%d, which expects primitive %s"
1421 : "type mismatch: returning a %s, but caller expects primitive %s");
1422 } else if (dst_type == T_OBJECT) {
1423 err = (!for_return
1424 ? "type mismatch: passing a primitive %s for method argument #%d, which expects %s"
1425 : "type mismatch: returning a primitive %s, but caller expects %s");
1426 } else {
1427 err = (!for_return
1428 ? "type mismatch: passing a %s for method argument #%d, which expects %s"
1429 : "type mismatch: returning a %s, but caller expects %s");
1430 }
1431 } else if (src_type == T_OBJECT && dst_type == T_OBJECT &&
1432 class_cast_needed(src_klass, dst_klass)) {
1433 if (!class_cast_needed(dst_klass, src_klass)) {
1434 if (raw)
1435 return NULL; // reverse cast is OK; the MH target is trusted to enforce it
1436 err = (!for_return
1437 ? "cast required: passing a %s for method argument #%d, which expects %s"
1438 : "cast required: returning a %s, but caller expects %s");
1439 } else {
1440 err = (!for_return
1441 ? "reference mismatch: passing a %s for method argument #%d, which expects %s"
1442 : "reference mismatch: returning a %s, but caller expects %s");
1443 }
1444 } else {
1445 // passed the obstacle course
1446 return NULL;
1447 }
1449 // format, format, format
1450 const char* src_name = type2name(src_type);
1451 const char* dst_name = type2name(dst_type);
1452 if (src_name == NULL) src_name = "unknown type";
1453 if (dst_name == NULL) dst_name = "unknown type";
1454 if (src_type == T_OBJECT)
1455 src_name = (src_klass != NULL) ? Klass::cast(src_klass)->external_name() : "an unresolved class";
1456 if (dst_type == T_OBJECT)
1457 dst_name = (dst_klass != NULL) ? Klass::cast(dst_klass)->external_name() : "an unresolved class";
1459 size_t msglen = strlen(err) + strlen(src_name) + strlen(dst_name) + (argnum < 10 ? 1 : 11);
1460 char* msg = NEW_RESOURCE_ARRAY(char, msglen + 1);
1461 if (!for_return) {
1462 assert(strstr(err, "%d") != NULL, "");
1463 jio_snprintf(msg, msglen, err, src_name, argnum, dst_name);
1464 } else {
1465 assert(strstr(err, "%d") == NULL, "");
1466 jio_snprintf(msg, msglen, err, src_name, dst_name);
1467 }
1468 return msg;
1469 }
1471 // Compute the depth within the stack of the given argument, i.e.,
1472 // the combined size of arguments to the right of the given argument.
1473 // For the last argument (ptypes.length-1) this will be zero.
1474 // For the first argument (0) this will be the size of all
1475 // arguments but that one. For the special number -1, this
1476 // will be the size of all arguments, including the first.
1477 // If the argument is neither -1 nor a valid argument index,
1478 // then return a negative number. Otherwise, the result
1479 // is in the range [0..vmslots] inclusive.
1480 int MethodHandles::argument_slot(oop method_type, int arg) {
1481 objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(method_type);
1482 int argslot = 0;
1483 int len = ptypes->length();
1484 if (arg < -1 || arg >= len) return -99;
1485 for (int i = len-1; i > arg; i--) {
1486 BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
1487 argslot += type2size[bt];
1488 }
1489 assert(argument_slot_to_argnum(method_type, argslot) == arg, "inverse works");
1490 return argslot;
1491 }
1493 // Given a slot number, return the argument number.
1494 int MethodHandles::argument_slot_to_argnum(oop method_type, int query_argslot) {
1495 objArrayOop ptypes = java_lang_invoke_MethodType::ptypes(method_type);
1496 int argslot = 0;
1497 int len = ptypes->length();
1498 for (int i = len-1; i >= 0; i--) {
1499 if (query_argslot == argslot) return i;
1500 BasicType bt = java_lang_Class::as_BasicType(ptypes->obj_at(i));
1501 argslot += type2size[bt];
1502 }
1503 // return pseudo-arg deepest in stack:
1504 if (query_argslot == argslot) return -1;
1505 return -99; // oob slot, or splitting a double-slot arg
1506 }
1508 methodHandle MethodHandles::dispatch_decoded_method(methodHandle m,
1509 KlassHandle receiver_limit,
1510 int decode_flags,
1511 KlassHandle receiver_klass,
1512 TRAPS) {
1513 assert((decode_flags & ~_DMF_DIRECT_MASK) == 0, "must be direct method reference");
1514 assert((decode_flags & _dmf_has_receiver) != 0, "must have a receiver or first reference argument");
1516 if (!m->is_static() &&
1517 (receiver_klass.is_null() || !receiver_klass->is_subtype_of(m->method_holder())))
1518 // given type does not match class of method, or receiver is null!
1519 // caller should have checked this, but let's be extra careful...
1520 return methodHandle();
1522 if (receiver_limit.not_null() &&
1523 (receiver_klass.not_null() && !receiver_klass->is_subtype_of(receiver_limit())))
1524 // given type is not limited to the receiver type
1525 // note that a null receiver can match any reference value, for a static method
1526 return methodHandle();
1528 if (!(decode_flags & MethodHandles::_dmf_does_dispatch)) {
1529 // pre-dispatched or static method (null receiver is OK for static)
1530 return m;
1532 } else if (receiver_klass.is_null()) {
1533 // null receiver value; cannot dispatch
1534 return methodHandle();
1536 } else if (!(decode_flags & MethodHandles::_dmf_from_interface)) {
1537 // perform virtual dispatch
1538 int vtable_index = m->vtable_index();
1539 guarantee(vtable_index >= 0, "valid vtable index");
1541 // receiver_klass might be an arrayKlassOop but all vtables start at
1542 // the same place. The cast is to avoid virtual call and assertion.
1543 // See also LinkResolver::runtime_resolve_virtual_method.
1544 instanceKlass* inst = (instanceKlass*)Klass::cast(receiver_klass());
1545 DEBUG_ONLY(inst->verify_vtable_index(vtable_index));
1546 methodOop m_oop = inst->method_at_vtable(vtable_index);
1547 return methodHandle(THREAD, m_oop);
1549 } else {
1550 // perform interface dispatch
1551 int itable_index = klassItable::compute_itable_index(m());
1552 guarantee(itable_index >= 0, "valid itable index");
1553 instanceKlass* inst = instanceKlass::cast(receiver_klass());
1554 methodOop m_oop = inst->method_at_itable(m->method_holder(), itable_index, THREAD);
1555 return methodHandle(THREAD, m_oop);
1556 }
1557 }
1559 void MethodHandles::verify_DirectMethodHandle(Handle mh, methodHandle m, TRAPS) {
1560 // Verify type.
1561 Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1562 verify_method_type(m, mtype, false, KlassHandle(), CHECK);
1564 // Verify vmslots.
1565 if (java_lang_invoke_MethodHandle::vmslots(mh()) != m->size_of_parameters()) {
1566 THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in DMH");
1567 }
1568 }
1570 void MethodHandles::init_DirectMethodHandle(Handle mh, methodHandle m, bool do_dispatch, TRAPS) {
1571 // Check arguments.
1572 if (mh.is_null() || m.is_null() ||
1573 (!do_dispatch && m->is_abstract())) {
1574 THROW(vmSymbols::java_lang_InternalError());
1575 }
1577 java_lang_invoke_MethodHandle::init_vmslots(mh());
1579 if (VerifyMethodHandles) {
1580 // The privileged code which invokes this routine should not make
1581 // a mistake about types, but it's better to verify.
1582 verify_DirectMethodHandle(mh, m, CHECK);
1583 }
1585 // Finally, after safety checks are done, link to the target method.
1586 // We will follow the same path as the latter part of
1587 // InterpreterRuntime::resolve_invoke(), which first finds the method
1588 // and then decides how to populate the constant pool cache entry
1589 // that links the interpreter calls to the method. We need the same
1590 // bits, and will use the same calling sequence code.
1592 int vmindex = methodOopDesc::garbage_vtable_index;
1593 Handle vmtarget;
1595 instanceKlass::cast(m->method_holder())->link_class(CHECK);
1597 MethodHandleEntry* me = NULL;
1598 if (do_dispatch && Klass::cast(m->method_holder())->is_interface()) {
1599 // We are simulating an invokeinterface instruction.
1600 // (We might also be simulating an invokevirtual on a miranda method,
1601 // but it is safe to treat it as an invokeinterface.)
1602 assert(!m->can_be_statically_bound(), "no final methods on interfaces");
1603 vmindex = klassItable::compute_itable_index(m());
1604 assert(vmindex >= 0, "(>=0) == do_dispatch");
1605 // Set up same bits as ConstantPoolCacheEntry::set_interface_call().
1606 vmtarget = m->method_holder(); // the interface
1607 me = MethodHandles::entry(MethodHandles::_invokeinterface_mh);
1608 } else if (!do_dispatch || m->can_be_statically_bound()) {
1609 // We are simulating an invokestatic or invokespecial instruction.
1610 // Set up the method pointer, just like ConstantPoolCacheEntry::set_method().
1611 vmtarget = m;
1612 // this does not help dispatch, but it will make it possible to parse this MH:
1613 vmindex = methodOopDesc::nonvirtual_vtable_index;
1614 assert(vmindex < 0, "(>=0) == do_dispatch");
1615 if (!m->is_static()) {
1616 me = MethodHandles::entry(MethodHandles::_invokespecial_mh);
1617 } else {
1618 me = MethodHandles::entry(MethodHandles::_invokestatic_mh);
1619 // Part of the semantics of a static call is an initialization barrier.
1620 // For a DMH, it is done now, when the handle is created.
1621 Klass* k = Klass::cast(m->method_holder());
1622 if (k->should_be_initialized()) {
1623 k->initialize(CHECK); // possible safepoint
1624 }
1625 }
1626 } else {
1627 // We are simulating an invokevirtual instruction.
1628 // Set up the vtable index, just like ConstantPoolCacheEntry::set_method().
1629 // The key logic is LinkResolver::runtime_resolve_virtual_method.
1630 vmindex = m->vtable_index();
1631 vmtarget = m->method_holder();
1632 me = MethodHandles::entry(MethodHandles::_invokevirtual_mh);
1633 }
1635 if (me == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
1637 java_lang_invoke_DirectMethodHandle::set_vmtarget(mh(), vmtarget());
1638 java_lang_invoke_DirectMethodHandle::set_vmindex( mh(), vmindex);
1639 DEBUG_ONLY(KlassHandle rlimit; int flags);
1640 assert(MethodHandles::decode_method(mh(), rlimit, flags) == m,
1641 "properly stored for later decoding");
1642 DEBUG_ONLY(bool actual_do_dispatch = ((flags & _dmf_does_dispatch) != 0));
1643 assert(!(actual_do_dispatch && !do_dispatch),
1644 "do not perform dispatch if !do_dispatch specified");
1645 assert(actual_do_dispatch == (vmindex >= 0), "proper later decoding of do_dispatch");
1646 assert(decode_MethodHandle_stack_pushes(mh()) == 0, "DMH does not move stack");
1648 // Done!
1649 java_lang_invoke_MethodHandle::set_vmentry(mh(), me);
1650 }
1652 void MethodHandles::verify_BoundMethodHandle_with_receiver(Handle mh,
1653 methodHandle m,
1654 TRAPS) {
1655 // Verify type.
1656 KlassHandle bound_recv_type;
1657 {
1658 oop receiver = java_lang_invoke_BoundMethodHandle::argument(mh());
1659 if (receiver != NULL)
1660 bound_recv_type = KlassHandle(THREAD, receiver->klass());
1661 }
1662 Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1663 verify_method_type(m, mtype, true, bound_recv_type, CHECK);
1665 int receiver_pos = m->size_of_parameters() - 1;
1667 // Verify MH.vmargslot, which should point at the bound receiver.
1668 verify_vmargslot(mh, -1, java_lang_invoke_BoundMethodHandle::vmargslot(mh()), CHECK);
1669 //verify_vmslots(mh, CHECK);
1671 // Verify vmslots.
1672 if (java_lang_invoke_MethodHandle::vmslots(mh()) != receiver_pos) {
1673 THROW_MSG(vmSymbols::java_lang_InternalError(), "bad vmslots in BMH (receiver)");
1674 }
1675 }
1677 // Initialize a BMH with a receiver bound directly to a methodOop.
1678 void MethodHandles::init_BoundMethodHandle_with_receiver(Handle mh,
1679 methodHandle original_m,
1680 KlassHandle receiver_limit,
1681 int decode_flags,
1682 TRAPS) {
1683 // Check arguments.
1684 if (mh.is_null() || original_m.is_null()) {
1685 THROW(vmSymbols::java_lang_InternalError());
1686 }
1688 KlassHandle receiver_klass;
1689 {
1690 oop receiver_oop = java_lang_invoke_BoundMethodHandle::argument(mh());
1691 if (receiver_oop != NULL)
1692 receiver_klass = KlassHandle(THREAD, receiver_oop->klass());
1693 }
1694 methodHandle m = dispatch_decoded_method(original_m,
1695 receiver_limit, decode_flags,
1696 receiver_klass,
1697 CHECK);
1698 if (m.is_null()) { THROW(vmSymbols::java_lang_InternalError()); }
1699 if (m->is_abstract()) { THROW(vmSymbols::java_lang_AbstractMethodError()); }
1701 java_lang_invoke_MethodHandle::init_vmslots(mh());
1702 int vmargslot = m->size_of_parameters() - 1;
1703 assert(java_lang_invoke_BoundMethodHandle::vmargslot(mh()) == vmargslot, "");
1705 if (VerifyMethodHandles) {
1706 verify_BoundMethodHandle_with_receiver(mh, m, CHECK);
1707 }
1709 java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), m());
1711 DEBUG_ONLY(KlassHandle junk1; int junk2);
1712 assert(MethodHandles::decode_method(mh(), junk1, junk2) == m, "properly stored for later decoding");
1713 assert(decode_MethodHandle_stack_pushes(mh()) == 1, "BMH pushes one stack slot");
1715 // Done!
1716 java_lang_invoke_MethodHandle::set_vmentry(mh(), MethodHandles::entry(MethodHandles::_bound_ref_direct_mh));
1717 }
1719 void MethodHandles::verify_BoundMethodHandle(Handle mh, Handle target, int argnum,
1720 bool direct_to_method, TRAPS) {
1721 Handle ptype_handle(THREAD,
1722 java_lang_invoke_MethodType::ptype(java_lang_invoke_MethodHandle::type(target()), argnum));
1723 KlassHandle ptype_klass;
1724 BasicType ptype = java_lang_Class::as_BasicType(ptype_handle(), &ptype_klass);
1725 int slots_pushed = type2size[ptype];
1727 oop argument = java_lang_invoke_BoundMethodHandle::argument(mh());
1729 const char* err = NULL;
1731 switch (ptype) {
1732 case T_OBJECT:
1733 if (argument != NULL)
1734 // we must implicitly convert from the arg type to the outgoing ptype
1735 err = check_argument_type_change(T_OBJECT, argument->klass(), ptype, ptype_klass(), argnum);
1736 break;
1738 case T_ARRAY: case T_VOID:
1739 assert(false, "array, void do not appear here");
1740 default:
1741 if (ptype != T_INT && !is_subword_type(ptype)) {
1742 err = "unexpected parameter type";
1743 break;
1744 }
1745 // check subrange of Integer.value, if necessary
1746 if (argument == NULL || argument->klass() != SystemDictionary::Integer_klass()) {
1747 err = "bound integer argument must be of type java.lang.Integer";
1748 break;
1749 }
1750 if (ptype != T_INT) {
1751 int value_offset = java_lang_boxing_object::value_offset_in_bytes(T_INT);
1752 jint value = argument->int_field(value_offset);
1753 int vminfo = adapter_unbox_subword_vminfo(ptype);
1754 jint subword = truncate_subword_from_vminfo(value, vminfo);
1755 if (value != subword) {
1756 err = "bound subword value does not fit into the subword type";
1757 break;
1758 }
1759 }
1760 break;
1761 case T_FLOAT:
1762 case T_DOUBLE:
1763 case T_LONG:
1764 {
1765 // we must implicitly convert from the unboxed arg type to the outgoing ptype
1766 BasicType argbox = java_lang_boxing_object::basic_type(argument);
1767 if (argbox != ptype) {
1768 err = check_argument_type_change(T_OBJECT, (argument == NULL
1769 ? SystemDictionary::Object_klass()
1770 : argument->klass()),
1771 ptype, ptype_klass(), argnum);
1772 assert(err != NULL, "this must be an error");
1773 }
1774 break;
1775 }
1776 }
1778 if (err == NULL) {
1779 DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
1780 if (direct_to_method) {
1781 assert(this_pushes == slots_pushed, "BMH pushes one or two stack slots");
1782 } else {
1783 int target_pushes = decode_MethodHandle_stack_pushes(target());
1784 assert(this_pushes == slots_pushed + target_pushes, "BMH stack motion must be correct");
1785 }
1786 }
1788 if (err == NULL) {
1789 // Verify the rest of the method type.
1790 err = check_method_type_insertion(java_lang_invoke_MethodHandle::type(mh()),
1791 argnum, ptype_handle(),
1792 java_lang_invoke_MethodHandle::type(target()));
1793 }
1795 if (err != NULL) {
1796 THROW_MSG(vmSymbols::java_lang_InternalError(), err);
1797 }
1798 }
1800 void MethodHandles::init_BoundMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
1801 // Check arguments.
1802 if (mh.is_null() || target.is_null() || !java_lang_invoke_MethodHandle::is_instance(target())) {
1803 THROW(vmSymbols::java_lang_InternalError());
1804 }
1806 java_lang_invoke_MethodHandle::init_vmslots(mh());
1807 int argslot = java_lang_invoke_BoundMethodHandle::vmargslot(mh());
1809 if (VerifyMethodHandles) {
1810 int insert_after = argnum - 1;
1811 verify_vmargslot(mh, insert_after, argslot, CHECK);
1812 verify_vmslots(mh, CHECK);
1813 }
1815 // Get bound type and required slots.
1816 BasicType ptype;
1817 {
1818 oop ptype_oop = java_lang_invoke_MethodType::ptype(java_lang_invoke_MethodHandle::type(target()), argnum);
1819 ptype = java_lang_Class::as_BasicType(ptype_oop);
1820 }
1821 int slots_pushed = type2size[ptype];
1823 // If (a) the target is a direct non-dispatched method handle,
1824 // or (b) the target is a dispatched direct method handle and we
1825 // are binding the receiver, cut out the middle-man.
1826 // Do this by decoding the DMH and using its methodOop directly as vmtarget.
1827 bool direct_to_method = false;
1828 if (OptimizeMethodHandles &&
1829 target->klass() == SystemDictionary::DirectMethodHandle_klass() &&
1830 (argnum == 0 || java_lang_invoke_DirectMethodHandle::vmindex(target()) < 0)) {
1831 KlassHandle receiver_limit; int decode_flags = 0;
1832 methodHandle m = decode_method(target(), receiver_limit, decode_flags);
1833 if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "DMH failed to decode"); }
1834 DEBUG_ONLY(int m_vmslots = m->size_of_parameters() - slots_pushed); // pos. of 1st arg.
1835 assert(java_lang_invoke_BoundMethodHandle::vmslots(mh()) == m_vmslots, "type w/ m sig");
1836 if (argnum == 0 && (decode_flags & _dmf_has_receiver) != 0) {
1837 init_BoundMethodHandle_with_receiver(mh, m,
1838 receiver_limit, decode_flags,
1839 CHECK);
1840 return;
1841 }
1843 // Even if it is not a bound receiver, we still might be able
1844 // to bind another argument and still invoke the methodOop directly.
1845 if (!(decode_flags & _dmf_does_dispatch)) {
1846 direct_to_method = true;
1847 java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), m());
1848 }
1849 }
1850 if (!direct_to_method)
1851 java_lang_invoke_BoundMethodHandle::set_vmtarget(mh(), target());
1853 if (VerifyMethodHandles) {
1854 verify_BoundMethodHandle(mh, target, argnum, direct_to_method, CHECK);
1855 }
1857 // Next question: Is this a ref, int, or long bound value?
1858 MethodHandleEntry* me = NULL;
1859 if (ptype == T_OBJECT) {
1860 if (direct_to_method) me = MethodHandles::entry(_bound_ref_direct_mh);
1861 else me = MethodHandles::entry(_bound_ref_mh);
1862 } else if (slots_pushed == 2) {
1863 if (direct_to_method) me = MethodHandles::entry(_bound_long_direct_mh);
1864 else me = MethodHandles::entry(_bound_long_mh);
1865 } else if (slots_pushed == 1) {
1866 if (direct_to_method) me = MethodHandles::entry(_bound_int_direct_mh);
1867 else me = MethodHandles::entry(_bound_int_mh);
1868 } else {
1869 assert(false, "");
1870 }
1872 // Done!
1873 java_lang_invoke_MethodHandle::set_vmentry(mh(), me);
1874 }
1876 static void throw_InternalError_for_bad_conversion(int conversion, const char* err, TRAPS) {
1877 char msg[200];
1878 jio_snprintf(msg, sizeof(msg), "bad adapter (conversion=0x%08x): %s", conversion, err);
1879 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), msg);
1880 }
1882 void MethodHandles::verify_AdapterMethodHandle(Handle mh, int argnum, TRAPS) {
1883 jint conversion = java_lang_invoke_AdapterMethodHandle::conversion(mh());
1884 int argslot = java_lang_invoke_AdapterMethodHandle::vmargslot(mh());
1886 verify_vmargslot(mh, argnum, argslot, CHECK);
1887 verify_vmslots(mh, CHECK);
1889 jint conv_op = adapter_conversion_op(conversion);
1890 if (!conv_op_valid(conv_op)) {
1891 throw_InternalError_for_bad_conversion(conversion, "unknown conversion op", THREAD);
1892 return;
1893 }
1894 EntryKind ek = adapter_entry_kind(conv_op);
1896 int stack_move = adapter_conversion_stack_move(conversion);
1897 BasicType src = adapter_conversion_src_type(conversion);
1898 BasicType dest = adapter_conversion_dest_type(conversion);
1899 int vminfo = adapter_conversion_vminfo(conversion); // should be zero
1901 Handle argument(THREAD, java_lang_invoke_AdapterMethodHandle::argument(mh()));
1902 Handle target(THREAD, java_lang_invoke_AdapterMethodHandle::vmtarget(mh()));
1903 Handle src_mtype(THREAD, java_lang_invoke_MethodHandle::type(mh()));
1904 Handle dst_mtype(THREAD, java_lang_invoke_MethodHandle::type(target()));
1905 Handle arg_mtype;
1907 const char* err = NULL;
1909 if (err == NULL) {
1910 // Check that the correct argument is supplied, but only if it is required.
1911 switch (ek) {
1912 case _adapter_check_cast: // target type of cast
1913 case _adapter_ref_to_prim: // wrapper type from which to unbox
1914 case _adapter_spread_args: // array type to spread from
1915 if (!java_lang_Class::is_instance(argument())
1916 || java_lang_Class::is_primitive(argument()))
1917 { err = "adapter requires argument of type java.lang.Class"; break; }
1918 if (ek == _adapter_spread_args) {
1919 // Make sure it is a suitable collection type. (Array, for now.)
1920 Klass* ak = Klass::cast(java_lang_Class::as_klassOop(argument()));
1921 if (!ak->oop_is_array())
1922 { err = "spread adapter requires argument representing an array class"; break; }
1923 BasicType et = arrayKlass::cast(ak->as_klassOop())->element_type();
1924 if (et != dest && stack_move <= 0)
1925 { err = "spread adapter requires array class argument of correct type"; break; }
1926 }
1927 break;
1928 case _adapter_prim_to_ref: // boxer MH to use
1929 case _adapter_collect_args: // method handle which collects the args
1930 case _adapter_fold_args: // method handle which collects the args
1931 if (!UseRicochetFrames) {
1932 { err = "box/collect/fold operators are not supported"; break; }
1933 }
1934 if (!java_lang_invoke_MethodHandle::is_instance(argument()))
1935 { err = "MethodHandle adapter argument required"; break; }
1936 arg_mtype = Handle(THREAD, java_lang_invoke_MethodHandle::type(argument()));
1937 break;
1938 default:
1939 if (argument.not_null())
1940 { err = "adapter has spurious argument"; break; }
1941 break;
1942 }
1943 }
1945 if (err == NULL) {
1946 // Check that the src/dest types are supplied if needed.
1947 // Also check relevant parameter or return types.
1948 switch (ek) {
1949 case _adapter_check_cast:
1950 if (src != T_OBJECT || dest != T_OBJECT) {
1951 err = "adapter requires object src/dest conversion subfields";
1952 }
1953 break;
1954 case _adapter_prim_to_prim:
1955 if (!is_java_primitive(src) || !is_java_primitive(dest) || src == dest) {
1956 err = "adapter requires primitive src/dest conversion subfields"; break;
1957 }
1958 if ( (src == T_FLOAT || src == T_DOUBLE) && !(dest == T_FLOAT || dest == T_DOUBLE) ||
1959 !(src == T_FLOAT || src == T_DOUBLE) && (dest == T_FLOAT || dest == T_DOUBLE)) {
1960 err = "adapter cannot convert beween floating and fixed-point"; break;
1961 }
1962 break;
1963 case _adapter_ref_to_prim:
1964 if (src != T_OBJECT || !is_java_primitive(dest)
1965 || argument() != Klass::cast(SystemDictionary::box_klass(dest))->java_mirror()) {
1966 err = "adapter requires primitive dest conversion subfield"; break;
1967 }
1968 break;
1969 case _adapter_prim_to_ref:
1970 if (!is_java_primitive(src) || dest != T_OBJECT) {
1971 err = "adapter requires primitive src conversion subfield"; break;
1972 }
1973 break;
1974 case _adapter_swap_args:
1975 case _adapter_rot_args:
1976 {
1977 if (!src || src != dest) {
1978 err = "adapter requires src/dest conversion subfields for swap"; break;
1979 }
1980 int swap_size = type2size[src];
1981 int slot_limit = java_lang_invoke_MethodHandle::vmslots(target());
1982 int src_slot = argslot;
1983 int dest_slot = vminfo;
1984 bool rotate_up = (src_slot > dest_slot); // upward rotation
1985 int src_arg = argnum;
1986 int dest_arg = argument_slot_to_argnum(dst_mtype(), dest_slot);
1987 verify_vmargslot(mh, dest_arg, dest_slot, CHECK);
1988 if (!(dest_slot >= src_slot + swap_size) &&
1989 !(src_slot >= dest_slot + swap_size)) {
1990 err = "source, destination slots must be distinct";
1991 } else if (ek == _adapter_swap_args && !(src_slot > dest_slot)) {
1992 err = "source of swap must be deeper in stack";
1993 } else if (ek == _adapter_swap_args) {
1994 err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), dest_arg),
1995 java_lang_invoke_MethodType::ptype(dst_mtype(), src_arg),
1996 dest_arg);
1997 } else if (ek == _adapter_rot_args) {
1998 if (rotate_up) {
1999 assert((src_slot > dest_slot) && (src_arg < dest_arg), "");
2000 // rotate up: [dest_slot..src_slot-ss] --> [dest_slot+ss..src_slot]
2001 // that is: [src_arg+1..dest_arg] --> [src_arg..dest_arg-1]
2002 for (int i = src_arg+1; i <= dest_arg && err == NULL; i++) {
2003 err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), i),
2004 java_lang_invoke_MethodType::ptype(dst_mtype(), i-1),
2005 i);
2006 }
2007 } else { // rotate down
2008 assert((src_slot < dest_slot) && (src_arg > dest_arg), "");
2009 // rotate down: [src_slot+ss..dest_slot] --> [src_slot..dest_slot-ss]
2010 // that is: [dest_arg..src_arg-1] --> [dst_arg+1..src_arg]
2011 for (int i = dest_arg; i <= src_arg-1 && err == NULL; i++) {
2012 err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), i),
2013 java_lang_invoke_MethodType::ptype(dst_mtype(), i+1),
2014 i);
2015 }
2016 }
2017 }
2018 if (err == NULL)
2019 err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), src_arg),
2020 java_lang_invoke_MethodType::ptype(dst_mtype(), dest_arg),
2021 src_arg);
2022 }
2023 break;
2024 case _adapter_spread_args:
2025 case _adapter_collect_args:
2026 case _adapter_fold_args:
2027 {
2028 bool is_spread = (ek == _adapter_spread_args);
2029 bool is_fold = (ek == _adapter_fold_args);
2030 BasicType coll_type = is_spread ? src : dest;
2031 BasicType elem_type = is_spread ? dest : src;
2032 // coll_type is type of args in collected form (or T_VOID if none)
2033 // elem_type is common type of args in spread form (or T_VOID if missing or heterogeneous)
2034 if (coll_type == 0 || elem_type == 0) {
2035 err = "adapter requires src/dest subfields for spread or collect"; break;
2036 }
2037 if (is_spread && coll_type != T_OBJECT) {
2038 err = "spread adapter requires object type for argument bundle"; break;
2039 }
2040 Handle spread_mtype = (is_spread ? dst_mtype : src_mtype);
2041 int spread_slot = argslot;
2042 int spread_arg = argnum;
2043 int slots_pushed = stack_move / stack_move_unit();
2044 int coll_slot_count = type2size[coll_type];
2045 int spread_slot_count = (is_spread ? slots_pushed : -slots_pushed) + coll_slot_count;
2046 if (is_fold) spread_slot_count = argument_slot_count(arg_mtype());
2047 if (!is_spread) {
2048 int init_slots = argument_slot_count(src_mtype());
2049 int coll_slots = argument_slot_count(arg_mtype());
2050 if (spread_slot_count > init_slots ||
2051 spread_slot_count != coll_slots) {
2052 err = "collect adapter has inconsistent arg counts"; break;
2053 }
2054 int next_slots = argument_slot_count(dst_mtype());
2055 int unchanged_slots_in = (init_slots - spread_slot_count);
2056 int unchanged_slots_out = (next_slots - coll_slot_count - (is_fold ? spread_slot_count : 0));
2057 if (unchanged_slots_in != unchanged_slots_out) {
2058 err = "collect adapter continuation has inconsistent arg counts"; break;
2059 }
2060 }
2061 }
2062 break;
2063 default:
2064 if (src != 0 || dest != 0) {
2065 err = "adapter has spurious src/dest conversion subfields"; break;
2066 }
2067 break;
2068 }
2069 }
2071 if (err == NULL) {
2072 // Check the stack_move subfield.
2073 // It must always report the net change in stack size, positive or negative.
2074 int slots_pushed = stack_move / stack_move_unit();
2075 switch (ek) {
2076 case _adapter_prim_to_prim:
2077 case _adapter_ref_to_prim:
2078 case _adapter_prim_to_ref:
2079 if (slots_pushed != type2size[dest] - type2size[src]) {
2080 err = "wrong stack motion for primitive conversion";
2081 }
2082 break;
2083 case _adapter_dup_args:
2084 if (slots_pushed <= 0) {
2085 err = "adapter requires conversion subfield slots_pushed > 0";
2086 }
2087 break;
2088 case _adapter_drop_args:
2089 if (slots_pushed >= 0) {
2090 err = "adapter requires conversion subfield slots_pushed < 0";
2091 }
2092 break;
2093 case _adapter_collect_args:
2094 case _adapter_fold_args:
2095 if (slots_pushed > 2) {
2096 err = "adapter requires conversion subfield slots_pushed <= 2";
2097 }
2098 break;
2099 case _adapter_spread_args:
2100 if (slots_pushed < -1) {
2101 err = "adapter requires conversion subfield slots_pushed >= -1";
2102 }
2103 break;
2104 default:
2105 if (stack_move != 0) {
2106 err = "adapter has spurious stack_move conversion subfield";
2107 }
2108 break;
2109 }
2110 if (err == NULL && stack_move != slots_pushed * stack_move_unit()) {
2111 err = "stack_move conversion subfield must be multiple of stack_move_unit";
2112 }
2113 }
2115 if (err == NULL) {
2116 // Make sure this adapter's stack pushing is accurately recorded.
2117 int slots_pushed = stack_move / stack_move_unit();
2118 int this_vmslots = java_lang_invoke_MethodHandle::vmslots(mh());
2119 int target_vmslots = java_lang_invoke_MethodHandle::vmslots(target());
2120 int target_pushes = decode_MethodHandle_stack_pushes(target());
2121 if (slots_pushed != (target_vmslots - this_vmslots)) {
2122 err = "stack_move inconsistent with previous and current MethodType vmslots";
2123 } else {
2124 int this_pushes = decode_MethodHandle_stack_pushes(mh());
2125 if (slots_pushed + target_pushes != this_pushes) {
2126 if (this_pushes == 0)
2127 err = "adapter push count not initialized";
2128 else
2129 err = "adapter push count is wrong";
2130 }
2131 }
2133 // While we're at it, check that the stack motion decoder works:
2134 DEBUG_ONLY(int this_pushes = decode_MethodHandle_stack_pushes(mh()));
2135 assert(this_pushes == slots_pushed + target_pushes, "AMH stack motion must be correct");
2136 }
2138 if (err == NULL && vminfo != 0) {
2139 switch (ek) {
2140 case _adapter_swap_args:
2141 case _adapter_rot_args:
2142 case _adapter_prim_to_ref:
2143 case _adapter_collect_args:
2144 case _adapter_fold_args:
2145 break; // OK
2146 default:
2147 err = "vminfo subfield is reserved to the JVM";
2148 }
2149 }
2151 // Do additional ad hoc checks.
2152 if (err == NULL) {
2153 switch (ek) {
2154 case _adapter_retype_only:
2155 err = check_method_type_passthrough(src_mtype(), dst_mtype(), false);
2156 break;
2158 case _adapter_retype_raw:
2159 err = check_method_type_passthrough(src_mtype(), dst_mtype(), true);
2160 break;
2162 case _adapter_check_cast:
2163 {
2164 // The actual value being checked must be a reference:
2165 err = check_argument_type_change(java_lang_invoke_MethodType::ptype(src_mtype(), argnum),
2166 object_java_mirror(), argnum);
2167 if (err != NULL) break;
2169 // The output of the cast must fit with the destination argument:
2170 Handle cast_class = argument;
2171 err = check_method_type_conversion(src_mtype(),
2172 argnum, cast_class(),
2173 dst_mtype());
2174 }
2175 break;
2177 // %%% TO DO: continue in remaining cases to verify src/dst_mtype if VerifyMethodHandles
2178 }
2179 }
2181 if (err != NULL) {
2182 throw_InternalError_for_bad_conversion(conversion, err, THREAD);
2183 return;
2184 }
2186 }
2188 void MethodHandles::init_AdapterMethodHandle(Handle mh, Handle target, int argnum, TRAPS) {
2189 Handle argument = java_lang_invoke_AdapterMethodHandle::argument(mh());
2190 int argslot = java_lang_invoke_AdapterMethodHandle::vmargslot(mh());
2191 jint conversion = java_lang_invoke_AdapterMethodHandle::conversion(mh());
2192 jint conv_op = adapter_conversion_op(conversion);
2194 // adjust the adapter code to the internal EntryKind enumeration:
2195 EntryKind ek_orig = adapter_entry_kind(conv_op);
2196 EntryKind ek_opt = ek_orig; // may be optimized
2197 EntryKind ek_try; // temp
2199 // Finalize the vmtarget field (Java initialized it to null).
2200 if (!java_lang_invoke_MethodHandle::is_instance(target())) {
2201 throw_InternalError_for_bad_conversion(conversion, "bad target", THREAD);
2202 return;
2203 }
2204 java_lang_invoke_AdapterMethodHandle::set_vmtarget(mh(), target());
2206 int stack_move = adapter_conversion_stack_move(conversion);
2207 BasicType src = adapter_conversion_src_type(conversion);
2208 BasicType dest = adapter_conversion_dest_type(conversion);
2209 int vminfo = adapter_conversion_vminfo(conversion); // should be zero
2211 int slots_pushed = stack_move / stack_move_unit();
2213 if (VerifyMethodHandles) {
2214 verify_AdapterMethodHandle(mh, argnum, CHECK);
2215 }
2217 const char* err = NULL;
2219 if (!conv_op_supported(conv_op)) {
2220 err = "adapter not yet implemented in the JVM";
2221 }
2223 // Now it's time to finish the case analysis and pick a MethodHandleEntry.
2224 switch (ek_orig) {
2225 case _adapter_retype_only:
2226 case _adapter_retype_raw:
2227 case _adapter_check_cast:
2228 case _adapter_dup_args:
2229 case _adapter_drop_args:
2230 // these work fine via general case code
2231 break;
2233 case _adapter_prim_to_prim:
2234 {
2235 // Non-subword cases are {int,float,long,double} -> {int,float,long,double}.
2236 // And, the {float,double} -> {int,long} cases must be handled by Java.
2237 switch (type2size[src] *4+ type2size[dest]) {
2238 case 1 *4+ 1:
2239 assert(src == T_INT || is_subword_type(src), "source is not float");
2240 // Subword-related cases are int -> {boolean,byte,char,short}.
2241 ek_opt = _adapter_opt_i2i;
2242 vminfo = adapter_prim_to_prim_subword_vminfo(dest);
2243 break;
2244 case 2 *4+ 1:
2245 if (src == T_LONG && (dest == T_INT || is_subword_type(dest))) {
2246 ek_opt = _adapter_opt_l2i;
2247 vminfo = adapter_prim_to_prim_subword_vminfo(dest);
2248 } else if (src == T_DOUBLE && dest == T_FLOAT) {
2249 ek_opt = _adapter_opt_d2f;
2250 } else {
2251 goto throw_not_impl; // runs user code, hence could block
2252 }
2253 break;
2254 case 1 *4+ 2:
2255 if ((src == T_INT || is_subword_type(src)) && dest == T_LONG) {
2256 ek_opt = _adapter_opt_i2l;
2257 } else if (src == T_FLOAT && dest == T_DOUBLE) {
2258 ek_opt = _adapter_opt_f2d;
2259 } else {
2260 goto throw_not_impl; // runs user code, hence could block
2261 }
2262 break;
2263 default:
2264 goto throw_not_impl; // runs user code, hence could block
2265 break;
2266 }
2267 }
2268 break;
2270 case _adapter_ref_to_prim:
2271 {
2272 switch (type2size[dest]) {
2273 case 1:
2274 ek_opt = _adapter_opt_unboxi;
2275 vminfo = adapter_unbox_subword_vminfo(dest);
2276 break;
2277 case 2:
2278 ek_opt = _adapter_opt_unboxl;
2279 break;
2280 default:
2281 goto throw_not_impl;
2282 break;
2283 }
2284 }
2285 break;
2287 case _adapter_prim_to_ref:
2288 {
2289 assert(UseRicochetFrames, "else don't come here");
2290 // vminfo will be the location to insert the return value
2291 vminfo = argslot;
2292 ek_opt = _adapter_opt_collect_ref;
2293 ensure_vmlayout_field(target, CHECK);
2294 // for MethodHandleWalk:
2295 if (java_lang_invoke_AdapterMethodHandle::is_instance(argument()))
2296 ensure_vmlayout_field(argument, CHECK);
2297 if (!OptimizeMethodHandles) break;
2298 switch (type2size[src]) {
2299 case 1:
2300 ek_try = EntryKind(_adapter_opt_filter_S0_ref + argslot);
2301 if (ek_try < _adapter_opt_collect_LAST &&
2302 ek_adapter_opt_collect_slot(ek_try) == argslot) {
2303 assert(ek_adapter_opt_collect_count(ek_try) == 1 &&
2304 ek_adapter_opt_collect_type(ek_try) == T_OBJECT, "");
2305 ek_opt = ek_try;
2306 break;
2307 }
2308 // else downgrade to variable slot:
2309 ek_opt = _adapter_opt_collect_1_ref;
2310 break;
2311 case 2:
2312 ek_try = EntryKind(_adapter_opt_collect_2_S0_ref + argslot);
2313 if (ek_try < _adapter_opt_collect_LAST &&
2314 ek_adapter_opt_collect_slot(ek_try) == argslot) {
2315 assert(ek_adapter_opt_collect_count(ek_try) == 2 &&
2316 ek_adapter_opt_collect_type(ek_try) == T_OBJECT, "");
2317 ek_opt = ek_try;
2318 break;
2319 }
2320 // else downgrade to variable slot:
2321 ek_opt = _adapter_opt_collect_2_ref;
2322 break;
2323 default:
2324 goto throw_not_impl;
2325 break;
2326 }
2327 }
2328 break;
2330 case _adapter_swap_args:
2331 case _adapter_rot_args:
2332 {
2333 int swap_slots = type2size[src];
2334 int slot_limit = java_lang_invoke_AdapterMethodHandle::vmslots(mh());
2335 int src_slot = argslot;
2336 int dest_slot = vminfo;
2337 int rotate = (ek_orig == _adapter_swap_args) ? 0 : (src_slot > dest_slot) ? 1 : -1;
2338 switch (swap_slots) {
2339 case 1:
2340 ek_opt = (!rotate ? _adapter_opt_swap_1 :
2341 rotate > 0 ? _adapter_opt_rot_1_up : _adapter_opt_rot_1_down);
2342 break;
2343 case 2:
2344 ek_opt = (!rotate ? _adapter_opt_swap_2 :
2345 rotate > 0 ? _adapter_opt_rot_2_up : _adapter_opt_rot_2_down);
2346 break;
2347 default:
2348 goto throw_not_impl;
2349 break;
2350 }
2351 }
2352 break;
2354 case _adapter_spread_args:
2355 {
2356 #ifdef TARGET_ARCH_NYI_6939861
2357 // ports before 6939861 supported only three kinds of spread ops
2358 if (!UseRicochetFrames) {
2359 int array_size = slots_pushed + 1;
2360 assert(array_size >= 0, "");
2361 vminfo = array_size;
2362 switch (array_size) {
2363 case 0: ek_opt = _adapter_opt_spread_0; break;
2364 case 1: ek_opt = _adapter_opt_spread_1; break;
2365 default: ek_opt = _adapter_opt_spread_more; break;
2366 }
2367 break;
2368 }
2369 #endif //TARGET_ARCH_NYI_6939861
2370 // vminfo will be the required length of the array
2371 int array_size = (slots_pushed + 1) / (type2size[dest] == 2 ? 2 : 1);
2372 vminfo = array_size;
2373 // general case
2374 switch (dest) {
2375 case T_BOOLEAN : // fall through to T_BYTE:
2376 case T_BYTE : ek_opt = _adapter_opt_spread_byte; break;
2377 case T_CHAR : ek_opt = _adapter_opt_spread_char; break;
2378 case T_SHORT : ek_opt = _adapter_opt_spread_short; break;
2379 case T_INT : ek_opt = _adapter_opt_spread_int; break;
2380 case T_LONG : ek_opt = _adapter_opt_spread_long; break;
2381 case T_FLOAT : ek_opt = _adapter_opt_spread_float; break;
2382 case T_DOUBLE : ek_opt = _adapter_opt_spread_double; break;
2383 case T_OBJECT : ek_opt = _adapter_opt_spread_ref; break;
2384 case T_VOID : if (array_size != 0) goto throw_not_impl;
2385 ek_opt = _adapter_opt_spread_ref; break;
2386 default : goto throw_not_impl;
2387 }
2388 assert(array_size == 0 || // it doesn't matter what the spreader is
2389 (ek_adapter_opt_spread_count(ek_opt) == -1 &&
2390 (ek_adapter_opt_spread_type(ek_opt) == dest ||
2391 (ek_adapter_opt_spread_type(ek_opt) == T_BYTE && dest == T_BOOLEAN))),
2392 err_msg("dest=%d ek_opt=%d", dest, ek_opt));
2394 if (array_size <= 0) {
2395 // since the general case does not handle length 0, this case is required:
2396 ek_opt = _adapter_opt_spread_0;
2397 break;
2398 }
2399 if (dest == T_OBJECT) {
2400 ek_try = EntryKind(_adapter_opt_spread_1_ref - 1 + array_size);
2401 if (ek_try < _adapter_opt_spread_LAST &&
2402 ek_adapter_opt_spread_count(ek_try) == array_size) {
2403 assert(ek_adapter_opt_spread_type(ek_try) == dest, "");
2404 ek_opt = ek_try;
2405 break;
2406 }
2407 }
2408 break;
2409 }
2410 break;
2412 case _adapter_collect_args:
2413 {
2414 assert(UseRicochetFrames, "else don't come here");
2415 int elem_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(argument()));
2416 // vminfo will be the location to insert the return value
2417 vminfo = argslot;
2418 ensure_vmlayout_field(target, CHECK);
2419 ensure_vmlayout_field(argument, CHECK);
2421 // general case:
2422 switch (dest) {
2423 default : if (!is_subword_type(dest)) goto throw_not_impl;
2424 // else fall through:
2425 case T_INT : ek_opt = _adapter_opt_collect_int; break;
2426 case T_LONG : ek_opt = _adapter_opt_collect_long; break;
2427 case T_FLOAT : ek_opt = _adapter_opt_collect_float; break;
2428 case T_DOUBLE : ek_opt = _adapter_opt_collect_double; break;
2429 case T_OBJECT : ek_opt = _adapter_opt_collect_ref; break;
2430 case T_VOID : ek_opt = _adapter_opt_collect_void; break;
2431 }
2432 assert(ek_adapter_opt_collect_slot(ek_opt) == -1 &&
2433 ek_adapter_opt_collect_count(ek_opt) == -1 &&
2434 (ek_adapter_opt_collect_type(ek_opt) == dest ||
2435 ek_adapter_opt_collect_type(ek_opt) == T_INT && is_subword_type(dest)),
2436 "");
2438 if (dest == T_OBJECT && elem_slots == 1 && OptimizeMethodHandles) {
2439 // filter operation on a ref
2440 ek_try = EntryKind(_adapter_opt_filter_S0_ref + argslot);
2441 if (ek_try < _adapter_opt_collect_LAST &&
2442 ek_adapter_opt_collect_slot(ek_try) == argslot) {
2443 assert(ek_adapter_opt_collect_count(ek_try) == elem_slots &&
2444 ek_adapter_opt_collect_type(ek_try) == dest, "");
2445 ek_opt = ek_try;
2446 break;
2447 }
2448 ek_opt = _adapter_opt_collect_1_ref;
2449 break;
2450 }
2452 if (dest == T_OBJECT && elem_slots == 2 && OptimizeMethodHandles) {
2453 // filter of two arguments
2454 ek_try = EntryKind(_adapter_opt_collect_2_S0_ref + argslot);
2455 if (ek_try < _adapter_opt_collect_LAST &&
2456 ek_adapter_opt_collect_slot(ek_try) == argslot) {
2457 assert(ek_adapter_opt_collect_count(ek_try) == elem_slots &&
2458 ek_adapter_opt_collect_type(ek_try) == dest, "");
2459 ek_opt = ek_try;
2460 break;
2461 }
2462 ek_opt = _adapter_opt_collect_2_ref;
2463 break;
2464 }
2466 if (dest == T_OBJECT && OptimizeMethodHandles) {
2467 // try to use a fixed length adapter
2468 ek_try = EntryKind(_adapter_opt_collect_0_ref + elem_slots);
2469 if (ek_try < _adapter_opt_collect_LAST &&
2470 ek_adapter_opt_collect_count(ek_try) == elem_slots) {
2471 assert(ek_adapter_opt_collect_slot(ek_try) == -1 &&
2472 ek_adapter_opt_collect_type(ek_try) == dest, "");
2473 ek_opt = ek_try;
2474 break;
2475 }
2476 }
2478 break;
2479 }
2481 case _adapter_fold_args:
2482 {
2483 assert(UseRicochetFrames, "else don't come here");
2484 int elem_slots = argument_slot_count(java_lang_invoke_MethodHandle::type(argument()));
2485 // vminfo will be the location to insert the return value
2486 vminfo = argslot + elem_slots;
2487 ensure_vmlayout_field(target, CHECK);
2488 ensure_vmlayout_field(argument, CHECK);
2490 switch (dest) {
2491 default : if (!is_subword_type(dest)) goto throw_not_impl;
2492 // else fall through:
2493 case T_INT : ek_opt = _adapter_opt_fold_int; break;
2494 case T_LONG : ek_opt = _adapter_opt_fold_long; break;
2495 case T_FLOAT : ek_opt = _adapter_opt_fold_float; break;
2496 case T_DOUBLE : ek_opt = _adapter_opt_fold_double; break;
2497 case T_OBJECT : ek_opt = _adapter_opt_fold_ref; break;
2498 case T_VOID : ek_opt = _adapter_opt_fold_void; break;
2499 }
2500 assert(ek_adapter_opt_collect_slot(ek_opt) == -1 &&
2501 ek_adapter_opt_collect_count(ek_opt) == -1 &&
2502 (ek_adapter_opt_collect_type(ek_opt) == dest ||
2503 ek_adapter_opt_collect_type(ek_opt) == T_INT && is_subword_type(dest)),
2504 "");
2506 if (dest == T_OBJECT && elem_slots == 0 && OptimizeMethodHandles) {
2507 // if there are no args, just pretend it's a collect
2508 ek_opt = _adapter_opt_collect_0_ref;
2509 break;
2510 }
2512 if (dest == T_OBJECT && OptimizeMethodHandles) {
2513 // try to use a fixed length adapter
2514 ek_try = EntryKind(_adapter_opt_fold_1_ref - 1 + elem_slots);
2515 if (ek_try < _adapter_opt_fold_LAST &&
2516 ek_adapter_opt_collect_count(ek_try) == elem_slots) {
2517 assert(ek_adapter_opt_collect_slot(ek_try) == -1 &&
2518 ek_adapter_opt_collect_type(ek_try) == dest, "");
2519 ek_opt = ek_try;
2520 break;
2521 }
2522 }
2524 break;
2525 }
2527 default:
2528 // should have failed much earlier; must be a missing case here
2529 assert(false, "incomplete switch");
2530 // and fall through:
2532 throw_not_impl:
2533 if (err == NULL)
2534 err = "unknown adapter type";
2535 break;
2536 }
2538 if (err == NULL && (vminfo & CONV_VMINFO_MASK) != vminfo) {
2539 // should not happen, since vminfo is used to encode arg/slot indexes < 255
2540 err = "vminfo overflow";
2541 }
2543 if (err == NULL && !have_entry(ek_opt)) {
2544 err = "adapter stub for this kind of method handle is missing";
2545 }
2547 if (err == NULL && ek_opt == ek_orig) {
2548 switch (ek_opt) {
2549 case _adapter_prim_to_prim:
2550 case _adapter_ref_to_prim:
2551 case _adapter_prim_to_ref:
2552 case _adapter_swap_args:
2553 case _adapter_rot_args:
2554 case _adapter_collect_args:
2555 case _adapter_fold_args:
2556 case _adapter_spread_args:
2557 // should be handled completely by optimized cases; see above
2558 err = "init_AdapterMethodHandle should not issue this";
2559 break;
2560 }
2561 }
2563 if (err != NULL) {
2564 throw_InternalError_for_bad_conversion(conversion, err, THREAD);
2565 return;
2566 }
2568 // Rebuild the conversion value; maybe parts of it were changed.
2569 jint new_conversion = adapter_conversion(conv_op, src, dest, stack_move, vminfo);
2571 // Finalize the conversion field. (Note that it is final to Java code.)
2572 java_lang_invoke_AdapterMethodHandle::set_conversion(mh(), new_conversion);
2574 // Done!
2575 java_lang_invoke_MethodHandle::set_vmentry(mh(), entry(ek_opt));
2577 // There should be enough memory barriers on exit from native methods
2578 // to ensure that the MH is fully initialized to all threads before
2579 // Java code can publish it in global data structures.
2580 }
2582 void MethodHandles::ensure_vmlayout_field(Handle target, TRAPS) {
2583 Handle mtype(THREAD, java_lang_invoke_MethodHandle::type(target()));
2584 Handle mtform(THREAD, java_lang_invoke_MethodType::form(mtype()));
2585 if (mtform.is_null()) { THROW(vmSymbols::java_lang_InternalError()); }
2586 if (java_lang_invoke_MethodTypeForm::vmlayout_offset_in_bytes() > 0) {
2587 if (java_lang_invoke_MethodTypeForm::vmlayout(mtform()) == NULL) {
2588 // fill it in
2589 Handle erased_mtype(THREAD, java_lang_invoke_MethodTypeForm::erasedType(mtform()));
2590 TempNewSymbol erased_signature
2591 = java_lang_invoke_MethodType::as_signature(erased_mtype(), /*intern:*/true, CHECK);
2592 methodOop cookie
2593 = SystemDictionary::find_method_handle_invoke(vmSymbols::invokeExact_name(),
2594 erased_signature,
2595 SystemDictionaryHandles::Object_klass(),
2596 THREAD);
2597 java_lang_invoke_MethodTypeForm::init_vmlayout(mtform(), cookie);
2598 }
2599 }
2600 }
2602 //
2603 // Here are the native methods on sun.invoke.MethodHandleImpl.
2604 // They are the private interface between this JVM and the HotSpot-specific
2605 // Java code that implements JSR 292 method handles.
2606 //
2607 // Note: We use a JVM_ENTRY macro to define each of these, for this is the way
2608 // that intrinsic (non-JNI) native methods are defined in HotSpot.
2609 //
2611 // direct method handles for invokestatic or invokespecial
2612 // void init(DirectMethodHandle self, MemberName ref, boolean doDispatch, Class<?> caller);
2613 JVM_ENTRY(void, MHN_init_DMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2614 jobject target_jh, jboolean do_dispatch, jobject caller_jh)) {
2615 ResourceMark rm; // for error messages
2617 // This is the guy we are initializing:
2618 if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2619 Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2621 // Early returns out of this method leave the DMH in an unfinished state.
2622 assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2624 // which method are we really talking about?
2625 if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2626 Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2627 if (java_lang_invoke_MemberName::is_instance(target()) &&
2628 java_lang_invoke_MemberName::vmindex(target()) == VM_INDEX_UNINITIALIZED) {
2629 MethodHandles::resolve_MemberName(target, CHECK);
2630 }
2632 KlassHandle receiver_limit; int decode_flags = 0;
2633 methodHandle m = MethodHandles::decode_method(target(), receiver_limit, decode_flags);
2634 if (m.is_null()) { THROW_MSG(vmSymbols::java_lang_InternalError(), "no such method"); }
2636 // The trusted Java code that calls this method should already have performed
2637 // access checks on behalf of the given caller. But, we can verify this.
2638 if (VerifyMethodHandles && caller_jh != NULL) {
2639 KlassHandle caller(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh)));
2640 // If this were a bytecode, the first access check would be against
2641 // the "reference class" mentioned in the CONSTANT_Methodref.
2642 // We don't know at this point which class that was, and if we
2643 // check against m.method_holder we might get the wrong answer.
2644 // So we just make sure to handle this check when the resolution
2645 // happens, when we call resolve_MemberName.
2646 //
2647 // (A public class can inherit public members from private supers,
2648 // and it would be wrong to check access against the private super
2649 // if the original symbolic reference was against the public class.)
2650 //
2651 // If there were a bytecode, the next step would be to lookup the method
2652 // in the reference class, then then check the method's access bits.
2653 // Emulate LinkResolver::check_method_accessability.
2654 klassOop resolved_klass = m->method_holder();
2655 if (!Reflection::verify_field_access(caller->as_klassOop(),
2656 resolved_klass, resolved_klass,
2657 m->access_flags(),
2658 true)) {
2659 // %%% following cutout belongs in Reflection::verify_field_access?
2660 bool same_pm = Reflection::is_same_package_member(caller->as_klassOop(),
2661 resolved_klass, THREAD);
2662 if (!same_pm) {
2663 THROW_MSG(vmSymbols::java_lang_InternalError(), m->name_and_sig_as_C_string());
2664 }
2665 }
2666 }
2668 MethodHandles::init_DirectMethodHandle(mh, m, (do_dispatch != JNI_FALSE), CHECK);
2669 }
2670 JVM_END
2672 // bound method handles
2673 JVM_ENTRY(void, MHN_init_BMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2674 jobject target_jh, int argnum)) {
2675 ResourceMark rm; // for error messages
2677 // This is the guy we are initializing:
2678 if (mh_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2679 Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2681 // Early returns out of this method leave the BMH in an unfinished state.
2682 assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2684 if (target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2685 Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2687 if (!java_lang_invoke_MethodHandle::is_instance(target())) {
2688 // Target object is a reflective method. (%%% Do we need this alternate path?)
2689 Untested("init_BMH of non-MH");
2690 if (argnum != 0) { THROW(vmSymbols::java_lang_InternalError()); }
2691 KlassHandle receiver_limit; int decode_flags = 0;
2692 methodHandle m = MethodHandles::decode_method(target(), receiver_limit, decode_flags);
2693 MethodHandles::init_BoundMethodHandle_with_receiver(mh, m,
2694 receiver_limit,
2695 decode_flags,
2696 CHECK);
2697 return;
2698 }
2700 // Build a BMH on top of a DMH or another BMH:
2701 MethodHandles::init_BoundMethodHandle(mh, target, argnum, CHECK);
2702 }
2703 JVM_END
2705 // adapter method handles
2706 JVM_ENTRY(void, MHN_init_AMH(JNIEnv *env, jobject igcls, jobject mh_jh,
2707 jobject target_jh, int argnum)) {
2708 // This is the guy we are initializing:
2709 if (mh_jh == NULL || target_jh == NULL) {
2710 THROW(vmSymbols::java_lang_InternalError());
2711 }
2712 Handle mh(THREAD, JNIHandles::resolve_non_null(mh_jh));
2713 Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
2715 // Early returns out of this method leave the AMH in an unfinished state.
2716 assert(java_lang_invoke_MethodHandle::vmentry(mh()) == NULL, "must be safely null");
2718 MethodHandles::init_AdapterMethodHandle(mh, target, argnum, CHECK);
2719 }
2720 JVM_END
2722 // method type forms
2723 JVM_ENTRY(void, MHN_init_MT(JNIEnv *env, jobject igcls, jobject erased_jh)) {
2724 if (erased_jh == NULL) return;
2725 if (TraceMethodHandles) {
2726 tty->print("creating MethodType form ");
2727 if (WizardMode || Verbose) { // Warning: this calls Java code on the MH!
2728 // call Object.toString()
2729 Symbol* name = vmSymbols::toString_name();
2730 Symbol* sig = vmSymbols::void_string_signature();
2731 JavaCallArguments args(Handle(THREAD, JNIHandles::resolve_non_null(erased_jh)));
2732 JavaValue result(T_OBJECT);
2733 JavaCalls::call_virtual(&result, SystemDictionary::Object_klass(), name, sig,
2734 &args, CHECK);
2735 Handle str(THREAD, (oop)result.get_jobject());
2736 java_lang_String::print(str, tty);
2737 }
2738 tty->cr();
2739 }
2740 }
2741 JVM_END
2743 // debugging and reflection
2744 JVM_ENTRY(jobject, MHN_getTarget(JNIEnv *env, jobject igcls, jobject mh_jh, jint format)) {
2745 Handle mh(THREAD, JNIHandles::resolve(mh_jh));
2746 if (!java_lang_invoke_MethodHandle::is_instance(mh())) {
2747 THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
2748 }
2749 oop target = MethodHandles::encode_target(mh, format, CHECK_NULL);
2750 return JNIHandles::make_local(THREAD, target);
2751 }
2752 JVM_END
2754 JVM_ENTRY(jint, MHN_getConstant(JNIEnv *env, jobject igcls, jint which)) {
2755 switch (which) {
2756 case MethodHandles::GC_JVM_PUSH_LIMIT:
2757 guarantee(MethodHandlePushLimit >= 2 && MethodHandlePushLimit <= 0xFF,
2758 "MethodHandlePushLimit parameter must be in valid range");
2759 return MethodHandlePushLimit;
2760 case MethodHandles::GC_JVM_STACK_MOVE_UNIT:
2761 // return number of words per slot, signed according to stack direction
2762 return MethodHandles::stack_move_unit();
2763 case MethodHandles::GC_CONV_OP_IMPLEMENTED_MASK:
2764 return MethodHandles::adapter_conversion_ops_supported_mask();
2765 }
2766 return 0;
2767 }
2768 JVM_END
2770 #ifndef PRODUCT
2771 #define EACH_NAMED_CON(template) \
2772 /* hold back this one until JDK stabilizes */ \
2773 /* template(MethodHandles,GC_JVM_PUSH_LIMIT) */ \
2774 /* hold back this one until JDK stabilizes */ \
2775 /* template(MethodHandles,GC_JVM_STACK_MOVE_UNIT) */ \
2776 template(MethodHandles,ETF_HANDLE_OR_METHOD_NAME) \
2777 template(MethodHandles,ETF_DIRECT_HANDLE) \
2778 template(MethodHandles,ETF_METHOD_NAME) \
2779 template(MethodHandles,ETF_REFLECT_METHOD) \
2780 template(java_lang_invoke_MemberName,MN_IS_METHOD) \
2781 template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
2782 template(java_lang_invoke_MemberName,MN_IS_FIELD) \
2783 template(java_lang_invoke_MemberName,MN_IS_TYPE) \
2784 template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
2785 template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
2786 template(java_lang_invoke_MemberName,VM_INDEX_UNINITIALIZED) \
2787 template(java_lang_invoke_AdapterMethodHandle,OP_RETYPE_ONLY) \
2788 template(java_lang_invoke_AdapterMethodHandle,OP_RETYPE_RAW) \
2789 template(java_lang_invoke_AdapterMethodHandle,OP_CHECK_CAST) \
2790 template(java_lang_invoke_AdapterMethodHandle,OP_PRIM_TO_PRIM) \
2791 template(java_lang_invoke_AdapterMethodHandle,OP_REF_TO_PRIM) \
2792 template(java_lang_invoke_AdapterMethodHandle,OP_PRIM_TO_REF) \
2793 template(java_lang_invoke_AdapterMethodHandle,OP_SWAP_ARGS) \
2794 template(java_lang_invoke_AdapterMethodHandle,OP_ROT_ARGS) \
2795 template(java_lang_invoke_AdapterMethodHandle,OP_DUP_ARGS) \
2796 template(java_lang_invoke_AdapterMethodHandle,OP_DROP_ARGS) \
2797 template(java_lang_invoke_AdapterMethodHandle,OP_COLLECT_ARGS) \
2798 template(java_lang_invoke_AdapterMethodHandle,OP_SPREAD_ARGS) \
2799 /* hold back this one until JDK stabilizes */ \
2800 /*template(java_lang_invoke_AdapterMethodHandle,CONV_OP_LIMIT)*/ \
2801 template(java_lang_invoke_AdapterMethodHandle,CONV_OP_MASK) \
2802 template(java_lang_invoke_AdapterMethodHandle,CONV_VMINFO_MASK) \
2803 template(java_lang_invoke_AdapterMethodHandle,CONV_VMINFO_SHIFT) \
2804 template(java_lang_invoke_AdapterMethodHandle,CONV_OP_SHIFT) \
2805 template(java_lang_invoke_AdapterMethodHandle,CONV_DEST_TYPE_SHIFT) \
2806 template(java_lang_invoke_AdapterMethodHandle,CONV_SRC_TYPE_SHIFT) \
2807 template(java_lang_invoke_AdapterMethodHandle,CONV_STACK_MOVE_SHIFT) \
2808 template(java_lang_invoke_AdapterMethodHandle,CONV_STACK_MOVE_MASK) \
2809 /*end*/
2811 #define ONE_PLUS(scope,value) 1+
2812 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS) 0;
2813 #define VALUE_COMMA(scope,value) scope::value,
2814 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA) 0 };
2815 #define STRING_NULL(scope,value) #value "\0"
2816 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL) };
2818 #undef ONE_PLUS
2819 #undef VALUE_COMMA
2820 #undef STRING_NULL
2821 #undef EACH_NAMED_CON
2822 #endif
2824 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
2825 #ifndef PRODUCT
2826 if (which >= 0 && which < con_value_count) {
2827 int con = con_values[which];
2828 objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
2829 if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
2830 const char* str = &con_names[0];
2831 for (int i = 0; i < which; i++)
2832 str += strlen(str) + 1; // skip name and null
2833 oop name = java_lang_String::create_oop_from_str(str, CHECK_0); // possible safepoint
2834 box->obj_at_put(0, name);
2835 }
2836 return con;
2837 }
2838 #endif
2839 return 0;
2840 }
2841 JVM_END
2843 // void init(MemberName self, AccessibleObject ref)
2844 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
2845 if (mname_jh == NULL || target_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2846 Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
2847 oop target_oop = JNIHandles::resolve_non_null(target_jh);
2848 MethodHandles::init_MemberName(mname(), target_oop);
2849 }
2850 JVM_END
2852 // void expand(MemberName self)
2853 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
2854 if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2855 Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
2856 MethodHandles::expand_MemberName(mname, 0, CHECK);
2857 }
2858 JVM_END
2860 // void resolve(MemberName self, Class<?> caller)
2861 JVM_ENTRY(void, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
2862 if (mname_jh == NULL) { THROW(vmSymbols::java_lang_InternalError()); }
2863 Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
2865 // The trusted Java code that calls this method should already have performed
2866 // access checks on behalf of the given caller. But, we can verify this.
2867 if (VerifyMethodHandles && caller_jh != NULL) {
2868 klassOop reference_klass = java_lang_Class::as_klassOop(java_lang_invoke_MemberName::clazz(mname()));
2869 if (reference_klass != NULL) {
2870 // Emulate LinkResolver::check_klass_accessability.
2871 klassOop caller = java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(caller_jh));
2872 if (!Reflection::verify_class_access(caller,
2873 reference_klass,
2874 true)) {
2875 THROW_MSG(vmSymbols::java_lang_InternalError(), Klass::cast(reference_klass)->external_name());
2876 }
2877 }
2878 }
2880 MethodHandles::resolve_MemberName(mname, CHECK);
2881 }
2882 JVM_END
2884 // static native int getMembers(Class<?> defc, String matchName, String matchSig,
2885 // int matchFlags, Class<?> caller, int skip, MemberName[] results);
2886 JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
2887 jclass clazz_jh, jstring name_jh, jstring sig_jh,
2888 int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
2889 if (clazz_jh == NULL || results_jh == NULL) return -1;
2890 KlassHandle k(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz_jh)));
2892 objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
2893 if (results.is_null() || !results->is_objArray()) return -1;
2895 TempNewSymbol name = NULL;
2896 TempNewSymbol sig = NULL;
2897 if (name_jh != NULL) {
2898 name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
2899 if (name == NULL) return 0; // a match is not possible
2900 }
2901 if (sig_jh != NULL) {
2902 sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
2903 if (sig == NULL) return 0; // a match is not possible
2904 }
2906 KlassHandle caller;
2907 if (caller_jh != NULL) {
2908 oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
2909 if (!java_lang_Class::is_instance(caller_oop)) return -1;
2910 caller = KlassHandle(THREAD, java_lang_Class::as_klassOop(caller_oop));
2911 }
2913 if (name != NULL && sig != NULL && results.not_null()) {
2914 // try a direct resolve
2915 // %%% TO DO
2916 }
2918 int res = MethodHandles::find_MemberNames(k(), name, sig, mflags,
2919 caller(), skip, results());
2920 // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
2921 return res;
2922 }
2923 JVM_END
2925 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv *env, jobject igmh, jobjectArray igargs)) {
2926 TempNewSymbol UOE_name = SymbolTable::new_symbol("java/lang/UnsupportedOperationException", CHECK_NULL);
2927 THROW_MSG_NULL(UOE_name, "MethodHandle.invoke cannot be invoked reflectively");
2928 return NULL;
2929 }
2930 JVM_END
2932 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv *env, jobject igmh, jobjectArray igargs)) {
2933 TempNewSymbol UOE_name = SymbolTable::new_symbol("java/lang/UnsupportedOperationException", CHECK_NULL);
2934 THROW_MSG_NULL(UOE_name, "MethodHandle.invokeExact cannot be invoked reflectively");
2935 return NULL;
2936 }
2937 JVM_END
2940 /// JVM_RegisterMethodHandleMethods
2942 #define LANG "Ljava/lang/"
2943 #define JLINV "Ljava/lang/invoke/"
2945 #define OBJ LANG"Object;"
2946 #define CLS LANG"Class;"
2947 #define STRG LANG"String;"
2948 #define MT JLINV"MethodType;"
2949 #define MH JLINV"MethodHandle;"
2950 #define MEM JLINV"MemberName;"
2951 #define AMH JLINV"AdapterMethodHandle;"
2952 #define BMH JLINV"BoundMethodHandle;"
2953 #define DMH JLINV"DirectMethodHandle;"
2955 #define CC (char*) /*cast a literal from (const char*)*/
2956 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
2958 // These are the native methods on sun.invoke.MethodHandleNatives.
2959 static JNINativeMethod methods[] = {
2960 // void init(MemberName self, AccessibleObject ref)
2961 {CC"init", CC"("AMH""MH"I)V", FN_PTR(MHN_init_AMH)},
2962 {CC"init", CC"("BMH""OBJ"I)V", FN_PTR(MHN_init_BMH)},
2963 {CC"init", CC"("DMH""OBJ"Z"CLS")V", FN_PTR(MHN_init_DMH)},
2964 {CC"init", CC"("MT")V", FN_PTR(MHN_init_MT)},
2965 {CC"init", CC"("MEM""OBJ")V", FN_PTR(MHN_init_Mem)},
2966 {CC"expand", CC"("MEM")V", FN_PTR(MHN_expand_Mem)},
2967 {CC"resolve", CC"("MEM""CLS")V", FN_PTR(MHN_resolve_Mem)},
2968 {CC"getTarget", CC"("MH"I)"OBJ, FN_PTR(MHN_getTarget)},
2969 {CC"getConstant", CC"(I)I", FN_PTR(MHN_getConstant)},
2970 // static native int getNamedCon(int which, Object[] name)
2971 {CC"getNamedCon", CC"(I["OBJ")I", FN_PTR(MHN_getNamedCon)},
2972 // static native int getMembers(Class<?> defc, String matchName, String matchSig,
2973 // int matchFlags, Class<?> caller, int skip, MemberName[] results);
2974 {CC"getMembers", CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)}
2975 };
2977 static JNINativeMethod invoke_methods[] = {
2978 // void init(MemberName self, AccessibleObject ref)
2979 {CC"invoke", CC"(["OBJ")"OBJ, FN_PTR(MH_invoke_UOE)},
2980 {CC"invokeExact", CC"(["OBJ")"OBJ, FN_PTR(MH_invokeExact_UOE)}
2981 };
2983 // This one function is exported, used by NativeLookup.
2985 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
2986 assert(MethodHandles::spot_check_entry_names(), "entry enum is OK");
2988 if (!EnableInvokeDynamic) {
2989 warning("JSR 292 is disabled in this JVM. Use -XX:+UnlockDiagnosticVMOptions -XX:+EnableInvokeDynamic to enable.");
2990 return; // bind nothing
2991 }
2993 bool enable_MH = true;
2995 {
2996 ThreadToNativeFromVM ttnfv(thread);
2998 int status = env->RegisterNatives(MHN_class, methods, sizeof(methods)/sizeof(JNINativeMethod));
2999 if (!env->ExceptionOccurred()) {
3000 const char* L_MH_name = (JLINV "MethodHandle");
3001 const char* MH_name = L_MH_name+1;
3002 jclass MH_class = env->FindClass(MH_name);
3003 status = env->RegisterNatives(MH_class, invoke_methods, sizeof(invoke_methods)/sizeof(JNINativeMethod));
3004 }
3005 if (env->ExceptionOccurred()) {
3006 MethodHandles::set_enabled(false);
3007 warning("JSR 292 method handle code is mismatched to this JVM. Disabling support.");
3008 enable_MH = false;
3009 env->ExceptionClear();
3010 }
3011 }
3013 if (enable_MH) {
3014 KlassHandle MHN_klass = SystemDictionaryHandles::MethodHandleNatives_klass();
3015 if (MHN_klass.not_null()) {
3016 TempNewSymbol raiseException_name = SymbolTable::new_symbol("raiseException", CHECK);
3017 TempNewSymbol raiseException_sig = SymbolTable::new_symbol("(ILjava/lang/Object;Ljava/lang/Object;)V", CHECK);
3018 methodOop raiseException_method = instanceKlass::cast(MHN_klass->as_klassOop())
3019 ->find_method(raiseException_name, raiseException_sig);
3020 if (raiseException_method != NULL && raiseException_method->is_static()) {
3021 MethodHandles::set_raise_exception_method(raiseException_method);
3022 } else {
3023 warning("JSR 292 method handle code is mismatched to this JVM. Disabling support.");
3024 enable_MH = false;
3025 }
3026 } else {
3027 enable_MH = false;
3028 }
3029 }
3031 if (enable_MH) {
3032 MethodHandles::generate_adapters();
3033 MethodHandles::set_enabled(true);
3034 }
3035 }
3036 JVM_END