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