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