1 /*
  2  * Copyright (c) 1997, 2025, 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  */
 24 
 25 #include "asm/macroAssembler.hpp"
 26 #include "classfile/vmClasses.hpp"
 27 #include "compiler/disassembler.hpp"
 28 #include "classfile/javaClasses.inline.hpp"
 29 #include "interpreter/interpreter.hpp"
 30 #include "interpreter/interpreterRuntime.hpp"
 31 #include "jvm.h"
 32 #include "logging/log.hpp"
 33 #include "logging/logStream.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "prims/jvmtiExport.hpp"
 37 #include "prims/methodHandles.hpp"
 38 #include "runtime/flags/flagSetting.hpp"
 39 #include "runtime/frame.inline.hpp"
 40 #include "runtime/stubRoutines.hpp"
 41 #include "utilities/formatBuffer.hpp"
 42 #include "utilities/preserveException.hpp"
 43 
 44 #define __ Disassembler::hook<MacroAssembler>(__FILE__, __LINE__, _masm)->
 45 
 46 #ifdef PRODUCT
 47 #define BLOCK_COMMENT(str) /* nothing */
 48 #define STOP(error) stop(error)
 49 #else
 50 #define BLOCK_COMMENT(str) __ block_comment(str)
 51 #define STOP(error) block_comment(error); __ stop(error)
 52 #endif
 53 
 54 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 55 
 56 void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
 57   if (VerifyMethodHandles)
 58     verify_klass(_masm, klass_reg, VM_CLASS_ID(java_lang_Class),
 59                  "MH argument is a Class");
 60   __ movptr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset()));
 61 }
 62 
 63 #ifdef ASSERT
 64 static int check_nonzero(const char* xname, int x) {
 65   assert(x != 0, "%s should be nonzero", xname);
 66   return x;
 67 }
 68 #define NONZERO(x) check_nonzero(#x, x)
 69 #else //ASSERT
 70 #define NONZERO(x) (x)
 71 #endif //ASSERT
 72 
 73 #ifdef ASSERT
 74 void MethodHandles::verify_klass(MacroAssembler* _masm,
 75                                  Register obj, vmClassID klass_id,
 76                                  const char* error_message) {
 77   InstanceKlass** klass_addr = vmClasses::klass_addr_at(klass_id);
 78   Klass* klass = vmClasses::klass_at(klass_id);
 79   Register temp = rdi;
 80   Label L_ok, L_bad;
 81   BLOCK_COMMENT("verify_klass {");
 82   __ verify_oop(obj);
 83   __ testptr(obj, obj);
 84   __ jcc(Assembler::zero, L_bad);
 85 #define PUSH { __ push(temp); __ push(rscratch1);               }
 86 #define POP  {                __ pop(rscratch1);  __ pop(temp); }
 87   PUSH;
 88   __ load_klass(temp, obj, rscratch1);
 89   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 90   __ jcc(Assembler::equal, L_ok);
 91   intptr_t super_check_offset = klass->super_check_offset();
 92   __ movptr(temp, Address(temp, super_check_offset));
 93   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 94   __ jcc(Assembler::equal, L_ok);
 95   POP;
 96   __ bind(L_bad);
 97   __ STOP(error_message);
 98   __ BIND(L_ok);
 99   POP;
100   BLOCK_COMMENT("} verify_klass");
101 #undef POP
102 #undef PUSH
103 }
104 
105 void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) {
106   Label L;
107   BLOCK_COMMENT("verify_ref_kind {");
108   __ movl(temp, Address(member_reg, NONZERO(java_lang_invoke_MemberName::flags_offset())));
109   __ shrl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT);
110   __ andl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK);
111   __ cmpl(temp, ref_kind);
112   __ jcc(Assembler::equal, L);
113   const char* msg = ref_kind_to_verify_msg(ref_kind);
114   if (ref_kind == JVM_REF_invokeVirtual ||
115       ref_kind == JVM_REF_invokeSpecial) {
116     // could do this for all ref_kinds, but would explode assembly code size
117     trace_method_handle(_masm, msg);
118   }
119   __ STOP(msg);
120   BLOCK_COMMENT("} verify_ref_kind");
121   __ bind(L);
122 }
123 
124 void MethodHandles::verify_method(MacroAssembler* _masm, Register method, Register temp, vmIntrinsics::ID iid) {
125   BLOCK_COMMENT("verify_method {");
126   __ verify_method_ptr(method);
127   if (VerifyMethodHandles) {
128     Label L_ok;
129     assert_different_registers(method, temp);
130 
131     const Register method_holder = temp;
132     __ load_method_holder(method_holder, method);
133     __ push_ppx(method_holder); // keep holder around for diagnostic purposes
134 
135     switch (iid) {
136       case vmIntrinsicID::_invokeBasic:
137         // Require compiled LambdaForm class to be fully initialized.
138         __ cmpb(Address(method_holder, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
139         __ jcc(Assembler::equal, L_ok);
140         break;
141 
142       case vmIntrinsicID::_linkToStatic:
143         __ clinit_barrier(method_holder, &L_ok);
144         break;
145 
146       case vmIntrinsicID::_linkToVirtual:
147       case vmIntrinsicID::_linkToSpecial:
148       case vmIntrinsicID::_linkToInterface:
149         // Class initialization check is too strong here. Just ensure that initialization has been initiated.
150         __ cmpb(Address(method_holder, InstanceKlass::init_state_offset()), InstanceKlass::being_initialized);
151         __ jcc(Assembler::greaterEqual, L_ok);
152 
153         // init_state check failed, but it may be an abstract interface method
154         __ load_unsigned_short(temp, Address(method, Method::access_flags_offset()));
155         __ testl(temp, JVM_ACC_ABSTRACT);
156         __ jcc(Assembler::notZero, L_ok);
157         break;
158 
159       default:
160         fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
161     }
162 
163     // clinit check failed for a concrete method
164     __ STOP("Method holder klass is not initialized");
165 
166     __ BIND(L_ok);
167     __ pop_ppx(method_holder); // restore stack layout
168   }
169   BLOCK_COMMENT("} verify_method");
170 }
171 #endif // ASSERT
172 
173 void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
174                                             bool for_compiler_entry, vmIntrinsics::ID iid) {
175   assert(method == rbx, "interpreter calling convention");
176 
177    Label L_no_such_method;
178    __ testptr(rbx, rbx);
179    __ jcc(Assembler::zero, L_no_such_method);
180 
181   verify_method(_masm, method, temp, iid);
182 
183   if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
184     Label run_compiled_code;
185     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
186     // compiled code in threads for which the event is enabled.  Check here for
187     // interp_only_mode if these events CAN be enabled.
188     // interp_only is an int, on little endian it is sufficient to test the byte only
189     // Is a cmpl faster?
190     __ cmpb(Address(r15_thread, JavaThread::interp_only_mode_offset()), 0);
191     __ jccb(Assembler::zero, run_compiled_code);
192     __ jmp(Address(method, Method::interpreter_entry_offset()));
193     __ BIND(run_compiled_code);
194   }
195 
196   // The following jump might pass an inline type argument that was erased to Object as oop to a
197   // callee that expects inline type arguments to be passed as fields. We need to call the compiled
198   // value entry (_code->inline_entry_point() or _adapter->c2i_inline_entry()) which will take care
199   // of translating between the calling conventions.
200   const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_inline_offset() :
201                                                      Method::from_interpreted_offset();
202   __ jmp(Address(method, entry_offset));
203 
204   __ bind(L_no_such_method);
205   __ jump(RuntimeAddress(SharedRuntime::throw_AbstractMethodError_entry()));
206 }
207 
208 void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
209                                         Register recv, Register method_temp,
210                                         Register temp2,
211                                         bool for_compiler_entry) {
212   BLOCK_COMMENT("jump_to_lambda_form {");
213   // This is the initial entry point of a lazy method handle.
214   // After type checking, it picks up the invoker from the LambdaForm.
215   assert_different_registers(recv, method_temp, temp2);
216   assert(recv != noreg, "required register");
217   assert(method_temp == rbx, "required register for loading method");
218 
219   // Load the invoker, as MH -> MH.form -> LF.vmentry
220   __ verify_oop(recv);
221   __ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset())), temp2);
222   __ verify_oop(method_temp);
223   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset())), temp2);
224   __ verify_oop(method_temp);
225   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset())), temp2);
226   __ verify_oop(method_temp);
227   __ access_load_at(T_ADDRESS, IN_HEAP, method_temp,
228                     Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset())),
229                     noreg);
230 
231   if (VerifyMethodHandles && !for_compiler_entry) {
232     // make sure recv is already on stack
233     __ movptr(temp2, Address(method_temp, Method::const_offset()));
234     __ load_sized_value(temp2,
235                         Address(temp2, ConstMethod::size_of_parameters_offset()),
236                         sizeof(u2), /*is_signed*/ false);
237     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
238     Label L;
239     __ cmpoop(recv, __ argument_address(temp2, -1));
240     __ jcc(Assembler::equal, L);
241     __ movptr(rax, __ argument_address(temp2, -1));
242     __ STOP("receiver not on stack");
243     __ BIND(L);
244   }
245 
246   jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry, vmIntrinsics::_invokeBasic);
247   BLOCK_COMMENT("} jump_to_lambda_form");
248 }
249 
250 void MethodHandles::jump_to_native_invoker(MacroAssembler* _masm, Register nep_reg, Register temp_target) {
251   BLOCK_COMMENT("jump_to_native_invoker {");
252   assert_different_registers(nep_reg, temp_target);
253   assert(nep_reg != noreg, "required register");
254 
255   // Load the invoker, as NEP -> .invoker
256   __ verify_oop(nep_reg);
257   __ access_load_at(T_ADDRESS, IN_HEAP, temp_target,
258                     Address(nep_reg, NONZERO(jdk_internal_foreign_abi_NativeEntryPoint::downcall_stub_address_offset_in_bytes())),
259                     noreg);
260 
261   __ jmp(temp_target);
262   BLOCK_COMMENT("} jump_to_native_invoker");
263 }
264 
265 
266 // Code generation
267 address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
268                                                                 vmIntrinsics::ID iid) {
269   const bool not_for_compiler_entry = false;  // this is the interpreter entry
270   assert(is_signature_polymorphic(iid), "expected invoke iid");
271   if (iid == vmIntrinsics::_invokeGeneric ||
272       iid == vmIntrinsics::_compiledLambdaForm) {
273     // Perhaps surprisingly, the symbolic references visible to Java are not directly used.
274     // They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
275     // They all allow an appendix argument.
276     __ hlt();           // empty stubs make SG sick
277     return nullptr;
278   }
279 
280   // No need in interpreter entry for linkToNative for now.
281   // Interpreter calls compiled entry through i2c.
282   if (iid == vmIntrinsics::_linkToNative) {
283     __ hlt();
284     return nullptr;
285   }
286 
287   // rsi/r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
288   // rbx: Method*
289   // rdx: argument locator (parameter slot count, added to rsp)
290   // rcx: used as temp to hold mh or receiver
291   // rax, rdi: garbage temps, blown away
292   Register rdx_argp   = rdx;   // argument list ptr, live on error paths
293   Register rax_temp   = rax;
294   Register rcx_mh     = rcx;   // MH receiver; dies quickly and is recycled
295   Register rbx_method = rbx;   // eventual target of this invocation
296 
297   // here's where control starts out:
298   __ align(CodeEntryAlignment);
299   address entry_point = __ pc();
300 
301   if (VerifyMethodHandles) {
302     assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
303 
304     Label L;
305     BLOCK_COMMENT("verify_intrinsic_id {");
306     __ cmpw(Address(rbx_method, Method::intrinsic_id_offset()), (int) iid);
307     __ jcc(Assembler::equal, L);
308     if (iid == vmIntrinsics::_linkToVirtual ||
309         iid == vmIntrinsics::_linkToSpecial) {
310       // could do this for all kinds, but would explode assembly code size
311       trace_method_handle(_masm, "bad Method*::intrinsic_id");
312     }
313     __ STOP("bad Method*::intrinsic_id");
314     __ bind(L);
315     BLOCK_COMMENT("} verify_intrinsic_id");
316   }
317 
318   // First task:  Find out how big the argument list is.
319   Address rdx_first_arg_addr;
320   int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
321   assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
322   if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
323     __ movptr(rdx_argp, Address(rbx_method, Method::const_offset()));
324     __ load_sized_value(rdx_argp,
325                         Address(rdx_argp, ConstMethod::size_of_parameters_offset()),
326                         sizeof(u2), /*is_signed*/ false);
327     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
328     rdx_first_arg_addr = __ argument_address(rdx_argp, -1);
329   } else {
330     DEBUG_ONLY(rdx_argp = noreg);
331   }
332 
333   if (!is_signature_polymorphic_static(iid)) {
334     __ movptr(rcx_mh, rdx_first_arg_addr);
335     DEBUG_ONLY(rdx_argp = noreg);
336   }
337 
338   // rdx_first_arg_addr is live!
339 
340   trace_method_handle_interpreter_entry(_masm, iid);
341 
342   if (iid == vmIntrinsics::_invokeBasic) {
343     generate_method_handle_dispatch(_masm, iid, rcx_mh, noreg, not_for_compiler_entry);
344 
345   } else {
346     // Adjust argument list by popping the trailing MemberName argument.
347     Register rcx_recv = noreg;
348     if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
349       // Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
350       __ movptr(rcx_recv = rcx, rdx_first_arg_addr);
351     }
352     DEBUG_ONLY(rdx_argp = noreg);
353     Register rbx_member = rbx_method;  // MemberName ptr; incoming method ptr is dead now
354     __ pop(rax_temp);           // return address
355     __ pop(rbx_member);         // extract last argument
356     __ push(rax_temp);          // re-push return address
357     generate_method_handle_dispatch(_masm, iid, rcx_recv, rbx_member, not_for_compiler_entry);
358   }
359 
360   return entry_point;
361 }
362 
363 void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
364                                                     vmIntrinsics::ID iid,
365                                                     Register receiver_reg,
366                                                     Register member_reg,
367                                                     bool for_compiler_entry) {
368   assert(is_signature_polymorphic(iid), "expected invoke iid");
369   Register rbx_method = rbx;   // eventual target of this invocation
370   // temps used in this code are not used in *either* compiled or interpreted calling sequences
371   Register temp1 = rscratch1;
372   Register temp2 = rscratch2;
373   Register temp3 = rax;
374   if (for_compiler_entry) {
375     assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic || iid == vmIntrinsics::_linkToNative ? noreg : j_rarg0), "only valid assignment");
376     assert_different_registers(temp1,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
377     assert_different_registers(temp2,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
378     assert_different_registers(temp3,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
379   } else {
380     assert_different_registers(temp1, temp2, temp3, saved_last_sp_register());  // don't trash lastSP
381   }
382   assert_different_registers(temp1, temp2, temp3, receiver_reg);
383   assert_different_registers(temp1, temp2, temp3, member_reg);
384 
385   if (iid == vmIntrinsics::_invokeBasic) {
386     // indirect through MH.form.vmentry.vmtarget
387     jump_to_lambda_form(_masm, receiver_reg, rbx_method, temp1, for_compiler_entry);
388   } else if (iid == vmIntrinsics::_linkToNative) {
389     assert(for_compiler_entry, "only compiler entry is supported");
390     jump_to_native_invoker(_masm, member_reg, temp1);
391   } else {
392     // The method is a member invoker used by direct method handles.
393     if (VerifyMethodHandles) {
394       // make sure the trailing argument really is a MemberName (caller responsibility)
395       verify_klass(_masm, member_reg, VM_CLASS_ID(java_lang_invoke_MemberName),
396                    "MemberName required for invokeVirtual etc.");
397     }
398 
399     Address member_clazz(    member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset()));
400     Address member_vmindex(  member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset()));
401     Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset()));
402     Address vmtarget_method( rbx_method, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset()));
403 
404     Register temp1_recv_klass = temp1;
405     if (iid != vmIntrinsics::_linkToStatic) {
406       __ verify_oop(receiver_reg);
407       if (iid == vmIntrinsics::_linkToSpecial) {
408         // Don't actually load the klass; just null-check the receiver.
409         __ null_check(receiver_reg);
410       } else {
411         // load receiver klass itself
412         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
413         __ verify_klass_ptr(temp1_recv_klass);
414       }
415       BLOCK_COMMENT("check_receiver {");
416       // The receiver for the MemberName must be in receiver_reg.
417       // Check the receiver against the MemberName.clazz
418       if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
419         // Did not load it above...
420         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
421         __ verify_klass_ptr(temp1_recv_klass);
422       }
423       if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
424         Label L_ok;
425         Register temp2_defc = temp2;
426         __ load_heap_oop(temp2_defc, member_clazz, temp3);
427         load_klass_from_Class(_masm, temp2_defc);
428         __ verify_klass_ptr(temp2_defc);
429         __ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
430         // If we get here, the type check failed!
431         __ STOP("receiver class disagrees with MemberName.clazz");
432         __ bind(L_ok);
433       }
434       BLOCK_COMMENT("} check_receiver");
435     }
436     if (iid == vmIntrinsics::_linkToSpecial ||
437         iid == vmIntrinsics::_linkToStatic) {
438       DEBUG_ONLY(temp1_recv_klass = noreg);  // these guys didn't load the recv_klass
439     }
440 
441     // Live registers at this point:
442     //  member_reg - MemberName that was the trailing argument
443     //  temp1_recv_klass - klass of stacked receiver, if needed
444     //  rsi/r13 - interpreter linkage (if interpreted)
445     //  rcx, rdx, rsi, rdi, r8 - compiler arguments (if compiled)
446 
447     Label L_incompatible_class_change_error;
448     switch (iid) {
449     case vmIntrinsics::_linkToSpecial:
450       if (VerifyMethodHandles) {
451         verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
452       }
453       __ load_heap_oop(rbx_method, member_vmtarget);
454       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg);
455       break;
456 
457     case vmIntrinsics::_linkToStatic:
458       if (VerifyMethodHandles) {
459         verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
460       }
461       __ load_heap_oop(rbx_method, member_vmtarget);
462       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg);
463       break;
464 
465     case vmIntrinsics::_linkToVirtual:
466     {
467       // same as TemplateTable::invokevirtual,
468       // minus the CP setup and profiling:
469 
470       if (VerifyMethodHandles) {
471         verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
472       }
473 
474       // pick out the vtable index from the MemberName, and then we can discard it:
475       Register temp2_index = temp2;
476       __ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg);
477 
478       if (VerifyMethodHandles) {
479         Label L_index_ok;
480         __ cmpl(temp2_index, 0);
481         __ jcc(Assembler::greaterEqual, L_index_ok);
482         __ STOP("no virtual index");
483         __ BIND(L_index_ok);
484       }
485 
486       // Note:  The verifier invariants allow us to ignore MemberName.clazz and vmtarget
487       // at this point.  And VerifyMethodHandles has already checked clazz, if needed.
488 
489       // get target Method* & entry point
490       __ lookup_virtual_method(temp1_recv_klass, temp2_index, rbx_method);
491       break;
492     }
493 
494     case vmIntrinsics::_linkToInterface:
495     {
496       // same as TemplateTable::invokeinterface
497       // (minus the CP setup and profiling, with different argument motion)
498       if (VerifyMethodHandles) {
499         verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
500       }
501 
502       Register temp3_intf = temp3;
503       __ load_heap_oop(temp3_intf, member_clazz);
504       load_klass_from_Class(_masm, temp3_intf);
505       __ verify_klass_ptr(temp3_intf);
506 
507       Register rbx_index = rbx_method;
508       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_index, member_vmindex, noreg);
509       if (VerifyMethodHandles) {
510         Label L;
511         __ cmpl(rbx_index, 0);
512         __ jcc(Assembler::greaterEqual, L);
513         __ STOP("invalid vtable index for MH.invokeInterface");
514         __ bind(L);
515       }
516 
517       // given intf, index, and recv klass, dispatch to the implementation method
518       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
519                                  // note: next two args must be the same:
520                                  rbx_index, rbx_method,
521                                  temp2,
522                                  L_incompatible_class_change_error);
523       break;
524     }
525 
526     default:
527       fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
528       break;
529     }
530 
531     // Live at this point:
532     //   rbx_method
533     //   rsi/r13 (if interpreted)
534 
535     // After figuring out which concrete method to call, jump into it.
536     // Note that this works in the interpreter with no data motion.
537     // But the compiled version will require that rcx_recv be shifted out.
538     jump_from_method_handle(_masm, rbx_method, temp1, for_compiler_entry, iid);
539 
540     if (iid == vmIntrinsics::_linkToInterface) {
541       __ bind(L_incompatible_class_change_error);
542       __ jump(RuntimeAddress(SharedRuntime::throw_IncompatibleClassChangeError_entry()));
543     }
544   }
545 }
546 
547 #ifndef PRODUCT
548 void trace_method_handle_stub(const char* adaptername,
549                               oopDesc* mh,
550                               intptr_t* saved_regs,
551                               intptr_t* entry_sp) {
552   // called as a leaf from native code: do not block the JVM!
553   bool has_mh = (strstr(adaptername, "/static") == nullptr &&
554                  strstr(adaptername, "linkTo") == nullptr);    // static linkers don't have MH
555   const char* mh_reg_name = has_mh ? "rcx_mh" : "rcx";
556   log_info(methodhandles)("MH %s %s=" PTR_FORMAT " sp=" PTR_FORMAT, adaptername, mh_reg_name, p2i(mh), p2i(entry_sp));
557 
558   LogTarget(Trace, methodhandles) lt;
559   if (lt.is_enabled()) {
560     ResourceMark rm;
561     LogStream ls(lt);
562     ls.print_cr("Registers:");
563     const int saved_regs_count = Register::number_of_registers;
564     for (int i = 0; i < saved_regs_count; i++) {
565       Register r = as_Register(i);
566       // The registers are stored in reverse order on the stack (by pusha).
567       int num_regs = UseAPX ? 32 : 16;
568       assert(Register::available_gp_registers() == num_regs, "sanity");
569       if (r == rsp) {
570         // rsp is actually not stored by pusha(), compute the old rsp from saved_regs (rsp after pusha): saved_regs + 16 = old rsp
571         ls.print("%3s=" PTR_FORMAT, r->name(), (intptr_t)(&saved_regs[num_regs]));
572       } else {
573         ls.print("%3s=" PTR_FORMAT, r->name(), saved_regs[((saved_regs_count - 1) - i)]);
574       }
575       if ((i + 1) % 4 == 0) {
576         ls.cr();
577       } else {
578         ls.print(", ");
579       }
580     }
581     ls.cr();
582 
583     // Note: We want to allow trace_method_handle from any call site.
584     // While trace_method_handle creates a frame, it may be entered
585     // without a PC on the stack top (e.g. not just after a call).
586     // Walking that frame could lead to failures due to that invalid PC.
587     // => carefully detect that frame when doing the stack walking
588 
589     {
590       // dumping last frame with frame::describe
591 
592       JavaThread* p = JavaThread::active();
593 
594       // may not be needed by safer and unexpensive here
595       PreserveExceptionMark pem(Thread::current());
596       FrameValues values;
597 
598       frame cur_frame = os::current_frame();
599 
600       if (cur_frame.fp() != nullptr) { // not walkable
601 
602         // Robust search of trace_calling_frame (independent of inlining).
603         // Assumes saved_regs comes from a pusha in the trace_calling_frame.
604         //
605         // We have to start the search from cur_frame, because trace_calling_frame may be it.
606         // It is guaranteed that trace_calling_frame is different from the top frame.
607         // But os::current_frame() does NOT return the top frame: it returns the next frame under it (caller's frame).
608         // (Due to inlining and tail call optimizations, caller's frame doesn't necessarily correspond to the immediate
609         // caller in the source code.)
610         assert(cur_frame.sp() < saved_regs, "registers not saved on stack ?");
611         frame trace_calling_frame = cur_frame;
612         while (trace_calling_frame.fp() < saved_regs) {
613           assert(trace_calling_frame.cb() == nullptr, "not a C frame");
614           trace_calling_frame = os::get_sender_for_C_frame(&trace_calling_frame);
615         }
616         assert(trace_calling_frame.sp() < saved_regs, "wrong frame");
617 
618         // safely create a frame and call frame::describe
619         intptr_t *dump_sp = trace_calling_frame.sender_sp();
620         intptr_t *dump_fp = trace_calling_frame.link();
621 
622         if (has_mh) {
623           // The previous definition of walkable may have to be refined
624           // if new call sites cause the next frame constructor to start
625           // failing. Alternatively, frame constructors could be
626           // modified to support the current or future non walkable
627           // frames (but this is more intrusive and is not considered as
628           // part of this RFE, which will instead use a simpler output).
629           frame dump_frame = frame(dump_sp, dump_fp);
630           dump_frame.describe(values, 1);
631         } else {
632           // Stack may not be walkable (invalid PC above FP):
633           // Add descriptions without building a Java frame to avoid issues
634           values.describe(-1, dump_fp, "fp for #1 <not parsed, cannot trust pc>");
635           values.describe(-1, dump_sp, "sp for #1");
636         }
637       }
638       values.describe(-1, entry_sp, "raw top of stack");
639 
640       ls.print_cr("Stack layout:");
641       values.print_on(p, &ls);
642     }
643     if (has_mh && oopDesc::is_oop(mh)) {
644       mh->print_on(&ls);
645       if (java_lang_invoke_MethodHandle::is_instance(mh)) {
646         java_lang_invoke_MethodHandle::form(mh)->print_on(&ls);
647       }
648     }
649   }
650 }
651 
652 // The stub wraps the arguments in a struct on the stack to avoid
653 // dealing with the different calling conventions for passing 6
654 // arguments.
655 struct MethodHandleStubArguments {
656   const char* adaptername;
657   oopDesc* mh;
658   intptr_t* saved_regs;
659   intptr_t* entry_sp;
660 };
661 void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {
662   trace_method_handle_stub(args->adaptername,
663                            args->mh,
664                            args->saved_regs,
665                            args->entry_sp);
666 }
667 
668 void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {
669   if (!log_is_enabled(Info, methodhandles))  return;
670   BLOCK_COMMENT(err_msg("trace_method_handle %s {", adaptername));
671   __ enter();
672   __ andptr(rsp, -16); // align stack if needed for FPU state
673   __ pusha();
674   __ mov(rbx, rsp); // for retrieving saved_regs
675   // Note: saved_regs must be in the entered frame for the
676   // robust stack walking implemented in trace_method_handle_stub.
677 
678   // save FP result, valid at some call sites (adapter_opt_return_float, ...)
679   __ decrement(rsp, 2 * wordSize);
680   __ movdbl(Address(rsp, 0), xmm0);
681 
682   // Incoming state:
683   // rcx: method handle
684   //
685   // To avoid calling convention issues, build a record on the stack
686   // and pass the pointer to that instead.
687   __ push(rbp);               // entry_sp (with extra align space)
688   __ push(rbx);               // pusha saved_regs
689   __ push(rcx);               // mh
690   __ push(rcx);               // slot for adaptername
691   __ movptr(Address(rsp, 0), (intptr_t) adaptername, rscratch1);
692   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, trace_method_handle_stub_wrapper), rsp);
693   __ increment(rsp, sizeof(MethodHandleStubArguments));
694 
695   __ movdbl(xmm0, Address(rsp, 0));
696   __ increment(rsp, 2 * wordSize);
697 
698   __ popa();
699   __ leave();
700   BLOCK_COMMENT("} trace_method_handle");
701 }
702 #endif //PRODUCT