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