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