1 /*
  2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2014, Red Hat Inc. All rights reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #include "precompiled.hpp"
 27 #include "asm/macroAssembler.hpp"
 28 #include "classfile/javaClasses.inline.hpp"
 29 #include "classfile/vmClasses.hpp"
 30 #include "interpreter/interpreter.hpp"
 31 #include "interpreter/interpreterRuntime.hpp"
 32 #include "memory/allocation.inline.hpp"
 33 #include "prims/jvmtiExport.hpp"
 34 #include "prims/methodHandles.hpp"
 35 #include "runtime/flags/flagSetting.hpp"
 36 #include "runtime/frame.inline.hpp"
 37 #include "runtime/stubRoutines.hpp"
 38 
 39 #define __ _masm->
 40 
 41 #ifdef PRODUCT
 42 #define BLOCK_COMMENT(str) /* nothing */
 43 #else
 44 #define BLOCK_COMMENT(str) __ block_comment(str)
 45 #endif
 46 
 47 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 48 
 49 void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
 50   if (VerifyMethodHandles)
 51     verify_klass(_masm, klass_reg, VM_CLASS_ID(java_lang_Class),
 52                  "MH argument is a Class");
 53   __ ldr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset()));
 54 }
 55 
 56 #ifdef ASSERT
 57 static int check_nonzero(const char* xname, int x) {
 58   assert(x != 0, "%s should be nonzero", xname);
 59   return x;
 60 }
 61 #define NONZERO(x) check_nonzero(#x, x)
 62 #else //ASSERT
 63 #define NONZERO(x) (x)
 64 #endif //PRODUCT
 65 
 66 #ifdef ASSERT
 67 void MethodHandles::verify_klass(MacroAssembler* _masm,
 68                                  Register obj, vmClassID klass_id,
 69                                  const char* error_message) {
 70   InstanceKlass** klass_addr = vmClasses::klass_addr_at(klass_id);
 71   Klass* klass = vmClasses::klass_at(klass_id);
 72   Register temp = rscratch2;
 73   Register temp2 = rscratch1; // used by MacroAssembler::cmpptr
 74   Label L_ok, L_bad;
 75   BLOCK_COMMENT("verify_klass {");
 76   __ verify_oop(obj);
 77   __ cbz(obj, L_bad);
 78   __ push(RegSet::of(temp, temp2), sp);
 79   __ load_klass(temp, obj);
 80   __ cmpptr(temp, ExternalAddress((address) klass_addr));
 81   __ br(Assembler::EQ, L_ok);
 82   intptr_t super_check_offset = klass->super_check_offset();
 83   __ ldr(temp, Address(temp, super_check_offset));
 84   __ cmpptr(temp, ExternalAddress((address) klass_addr));
 85   __ br(Assembler::EQ, L_ok);
 86   __ pop(RegSet::of(temp, temp2), sp);
 87   __ bind(L_bad);
 88   __ stop(error_message);
 89   __ BIND(L_ok);
 90   __ pop(RegSet::of(temp, temp2), sp);
 91   BLOCK_COMMENT("} verify_klass");
 92 }
 93 
 94 void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) {  }
 95 
 96 #endif //ASSERT
 97 
 98 void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
 99                                             bool for_compiler_entry) {
100   assert(method == rmethod, "interpreter calling convention");
101   Label L_no_such_method;
102   __ cbz(rmethod, L_no_such_method);
103   __ verify_method_ptr(method);
104 
105   if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
106     Label run_compiled_code;
107     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
108     // compiled code in threads for which the event is enabled.  Check here for
109     // interp_only_mode if these events CAN be enabled.
110 
111     __ ldrw(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
112     __ cbzw(rscratch1, run_compiled_code);
113     __ ldr(rscratch1, Address(method, Method::interpreter_entry_offset()));
114     __ br(rscratch1);
115     __ BIND(run_compiled_code);
116   }
117 
118   const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_offset() :
119                                                      Method::from_interpreted_offset();
120   __ ldr(rscratch1,Address(method, entry_offset));
121   __ br(rscratch1);
122   __ bind(L_no_such_method);
123   __ far_jump(RuntimeAddress(StubRoutines::throw_AbstractMethodError_entry()));
124 }
125 
126 void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
127                                         Register recv, Register method_temp,
128                                         Register temp2,
129                                         bool for_compiler_entry) {
130   BLOCK_COMMENT("jump_to_lambda_form {");
131   // This is the initial entry point of a lazy method handle.
132   // After type checking, it picks up the invoker from the LambdaForm.
133   assert_different_registers(recv, method_temp, temp2);
134   assert(recv != noreg, "required register");
135   assert(method_temp == rmethod, "required register for loading method");
136 
137   // Load the invoker, as MH -> MH.form -> LF.vmentry
138   __ verify_oop(recv);
139   __ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset())), temp2);
140   __ verify_oop(method_temp);
141   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset())), temp2);
142   __ verify_oop(method_temp);
143   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset())), temp2);
144   __ verify_oop(method_temp);
145   __ access_load_at(T_ADDRESS, IN_HEAP, method_temp, Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset())), noreg, noreg);
146 
147   if (VerifyMethodHandles && !for_compiler_entry) {
148     // make sure recv is already on stack
149     __ ldr(temp2, Address(method_temp, Method::const_offset()));
150     __ load_sized_value(temp2,
151                         Address(temp2, ConstMethod::size_of_parameters_offset()),
152                         sizeof(u2), /*is_signed*/ false);
153     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
154     Label L;
155     __ ldr(rscratch1, __ argument_address(temp2, -1));
156     __ cmpoop(recv, rscratch1);
157     __ br(Assembler::EQ, L);
158     __ ldr(r0, __ argument_address(temp2, -1));
159     __ hlt(0);
160     __ BIND(L);
161   }
162 
163   jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry);
164   BLOCK_COMMENT("} jump_to_lambda_form");
165 }
166 
167 // Code generation
168 address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
169                                                                 vmIntrinsics::ID iid) {
170   const bool not_for_compiler_entry = false;  // this is the interpreter entry
171   assert(is_signature_polymorphic(iid), "expected invoke iid");
172   if (iid == vmIntrinsics::_invokeGeneric ||
173       iid == vmIntrinsics::_compiledLambdaForm) {
174     // Perhaps surprisingly, the symbolic references visible to Java are not directly used.
175     // They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
176     // They all allow an appendix argument.
177     __ hlt(0);           // empty stubs make SG sick
178     return NULL;
179   }
180 
181   // No need in interpreter entry for linkToNative for now.
182   // Interpreter calls compiled entry through i2c.
183   if (iid == vmIntrinsics::_linkToNative) {
184     __ hlt(0);
185     return NULL;
186   }
187 
188   // r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
189   // rmethod: Method*
190   // r3: argument locator (parameter slot count, added to rsp)
191   // r1: used as temp to hold mh or receiver
192   // r0, r11: garbage temps, blown away
193   Register argp   = r3;   // argument list ptr, live on error paths
194   Register temp   = r0;
195   Register mh     = r1;   // MH receiver; dies quickly and is recycled
196 
197   // here's where control starts out:
198   __ align(CodeEntryAlignment);
199   address entry_point = __ pc();
200 
201   if (VerifyMethodHandles) {
202     assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
203 
204     Label L;
205     BLOCK_COMMENT("verify_intrinsic_id {");
206     __ ldrh(rscratch1, Address(rmethod, Method::intrinsic_id_offset_in_bytes()));
207     __ subs(zr, rscratch1, (int) iid);
208     __ br(Assembler::EQ, L);
209     if (iid == vmIntrinsics::_linkToVirtual ||
210         iid == vmIntrinsics::_linkToSpecial) {
211       // could do this for all kinds, but would explode assembly code size
212       trace_method_handle(_masm, "bad Method*::intrinsic_id");
213     }
214     __ hlt(0);
215     __ bind(L);
216     BLOCK_COMMENT("} verify_intrinsic_id");
217   }
218 
219   // First task:  Find out how big the argument list is.
220   Address r3_first_arg_addr;
221   int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
222   assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
223   if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
224     __ ldr(argp, Address(rmethod, Method::const_offset()));
225     __ load_sized_value(argp,
226                         Address(argp, ConstMethod::size_of_parameters_offset()),
227                         sizeof(u2), /*is_signed*/ false);
228     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
229     r3_first_arg_addr = __ argument_address(argp, -1);
230   } else {
231     DEBUG_ONLY(argp = noreg);
232   }
233 
234   if (!is_signature_polymorphic_static(iid)) {
235     __ ldr(mh, r3_first_arg_addr);
236     DEBUG_ONLY(argp = noreg);
237   }
238 
239   // r3_first_arg_addr is live!
240 
241   trace_method_handle_interpreter_entry(_masm, iid);
242   if (iid == vmIntrinsics::_invokeBasic) {
243     generate_method_handle_dispatch(_masm, iid, mh, noreg, not_for_compiler_entry);
244 
245   } else {
246     // Adjust argument list by popping the trailing MemberName argument.
247     Register recv = noreg;
248     if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
249       // Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
250       __ ldr(recv = r2, r3_first_arg_addr);
251     }
252     DEBUG_ONLY(argp = noreg);
253     Register rmember = rmethod;  // MemberName ptr; incoming method ptr is dead now
254     __ pop(rmember);             // extract last argument
255     generate_method_handle_dispatch(_masm, iid, recv, rmember, not_for_compiler_entry);
256   }
257 
258   return entry_point;
259 }
260 
261 
262 void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
263                                                     vmIntrinsics::ID iid,
264                                                     Register receiver_reg,
265                                                     Register member_reg,
266                                                     bool for_compiler_entry) {
267   assert(is_signature_polymorphic(iid), "expected invoke iid");
268   // temps used in this code are not used in *either* compiled or interpreted calling sequences
269   Register temp1 = r10;
270   Register temp2 = r11;
271   Register temp3 = r14;  // r13 is live by this point: it contains the sender SP
272   if (for_compiler_entry) {
273     assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic ? noreg : j_rarg0), "only valid assignment");
274     assert_different_registers(temp1,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
275     assert_different_registers(temp2,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
276     assert_different_registers(temp3,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
277   }
278 
279   assert_different_registers(temp1, temp2, temp3, receiver_reg);
280   assert_different_registers(temp1, temp2, temp3, member_reg);
281 
282   if (iid == vmIntrinsics::_invokeBasic || iid == vmIntrinsics::_linkToNative) {
283     if (iid == vmIntrinsics::_linkToNative) {
284       assert(for_compiler_entry, "only compiler entry is supported");
285     }
286     // indirect through MH.form.vmentry.vmtarget
287     jump_to_lambda_form(_masm, receiver_reg, rmethod, temp1, for_compiler_entry);
288 
289   } else {
290     // The method is a member invoker used by direct method handles.
291     if (VerifyMethodHandles) {
292       // make sure the trailing argument really is a MemberName (caller responsibility)
293       verify_klass(_masm, member_reg, VM_CLASS_ID(java_lang_invoke_MemberName),
294                    "MemberName required for invokeVirtual etc.");
295     }
296 
297     Address member_clazz(    member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset()));
298     Address member_vmindex(  member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset()));
299     Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset()));
300     Address vmtarget_method( rmethod, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset()));
301 
302     Register temp1_recv_klass = temp1;
303     if (iid != vmIntrinsics::_linkToStatic) {
304       __ verify_oop(receiver_reg);
305       if (iid == vmIntrinsics::_linkToSpecial) {
306         // Don't actually load the klass; just null-check the receiver.
307         __ null_check(receiver_reg);
308       } else {
309         // load receiver klass itself
310         __ null_check(receiver_reg, oopDesc::klass_offset_in_bytes());
311         __ load_klass(temp1_recv_klass, receiver_reg);
312         __ verify_klass_ptr(temp1_recv_klass);
313       }
314       BLOCK_COMMENT("check_receiver {");
315       // The receiver for the MemberName must be in receiver_reg.
316       // Check the receiver against the MemberName.clazz
317       if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
318         // Did not load it above...
319         __ load_klass(temp1_recv_klass, receiver_reg);
320         __ verify_klass_ptr(temp1_recv_klass);
321       }
322       if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
323         Label L_ok;
324         Register temp2_defc = temp2;
325         __ load_heap_oop(temp2_defc, member_clazz, temp3);
326         load_klass_from_Class(_masm, temp2_defc);
327         __ verify_klass_ptr(temp2_defc);
328         __ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
329         // If we get here, the type check failed!
330         __ hlt(0);
331         // __ STOP("receiver class disagrees with MemberName.clazz");
332         __ bind(L_ok);
333       }
334       BLOCK_COMMENT("} check_receiver");
335     }
336     if (iid == vmIntrinsics::_linkToSpecial ||
337         iid == vmIntrinsics::_linkToStatic) {
338       DEBUG_ONLY(temp1_recv_klass = noreg);  // these guys didn't load the recv_klass
339     }
340 
341     // Live registers at this point:
342     //  member_reg - MemberName that was the trailing argument
343     //  temp1_recv_klass - klass of stacked receiver, if needed
344     //  r13 - interpreter linkage (if interpreted)  ??? FIXME
345     //  r1 ... r0 - compiler arguments (if compiled)
346 
347     Label L_incompatible_class_change_error;
348     switch (iid) {
349     case vmIntrinsics::_linkToSpecial:
350       if (VerifyMethodHandles) {
351         verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
352       }
353       __ load_heap_oop(rmethod, member_vmtarget);
354       __ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
355       break;
356 
357     case vmIntrinsics::_linkToStatic:
358       if (VerifyMethodHandles) {
359         verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
360       }
361       __ load_heap_oop(rmethod, member_vmtarget);
362       __ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
363       break;
364 
365     case vmIntrinsics::_linkToVirtual:
366     {
367       // same as TemplateTable::invokevirtual,
368       // minus the CP setup and profiling:
369 
370       if (VerifyMethodHandles) {
371         verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
372       }
373 
374       // pick out the vtable index from the MemberName, and then we can discard it:
375       Register temp2_index = temp2;
376       __ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg, noreg);
377 
378       if (VerifyMethodHandles) {
379         Label L_index_ok;
380         __ cmpw(temp2_index, 0U);
381         __ br(Assembler::GE, L_index_ok);
382         __ hlt(0);
383         __ BIND(L_index_ok);
384       }
385 
386       // Note:  The verifier invariants allow us to ignore MemberName.clazz and vmtarget
387       // at this point.  And VerifyMethodHandles has already checked clazz, if needed.
388 
389       // get target Method* & entry point
390       __ lookup_virtual_method(temp1_recv_klass, temp2_index, rmethod);
391       break;
392     }
393 
394     case vmIntrinsics::_linkToInterface:
395     {
396       // same as TemplateTable::invokeinterface
397       // (minus the CP setup and profiling, with different argument motion)
398       if (VerifyMethodHandles) {
399         verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
400       }
401 
402       Register temp3_intf = temp3;
403       __ load_heap_oop(temp3_intf, member_clazz);
404       load_klass_from_Class(_masm, temp3_intf);
405       __ verify_klass_ptr(temp3_intf);
406 
407       Register rindex = rmethod;
408       __ access_load_at(T_ADDRESS, IN_HEAP, rindex, member_vmindex, noreg, noreg);
409       if (VerifyMethodHandles) {
410         Label L;
411         __ cmpw(rindex, 0U);
412         __ br(Assembler::GE, L);
413         __ hlt(0);
414         __ bind(L);
415       }
416 
417       // given intf, index, and recv klass, dispatch to the implementation method
418       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
419                                  // note: next two args must be the same:
420                                  rindex, rmethod,
421                                  temp2,
422                                  L_incompatible_class_change_error);
423       break;
424     }
425 
426     default:
427       fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
428       break;
429     }
430 
431     // live at this point:  rmethod, r13 (if interpreted)
432 
433     // After figuring out which concrete method to call, jump into it.
434     // Note that this works in the interpreter with no data motion.
435     // But the compiled version will require that r2_recv be shifted out.
436     __ verify_method_ptr(rmethod);
437     jump_from_method_handle(_masm, rmethod, temp1, for_compiler_entry);
438     if (iid == vmIntrinsics::_linkToInterface) {
439       __ bind(L_incompatible_class_change_error);
440       __ far_jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
441     }
442   }
443 }
444 
445 #ifndef PRODUCT
446 void trace_method_handle_stub(const char* adaptername,
447                               oopDesc* mh,
448                               intptr_t* saved_regs,
449                               intptr_t* entry_sp) {  }
450 
451 // The stub wraps the arguments in a struct on the stack to avoid
452 // dealing with the different calling conventions for passing 6
453 // arguments.
454 struct MethodHandleStubArguments {
455   const char* adaptername;
456   oopDesc* mh;
457   intptr_t* saved_regs;
458   intptr_t* entry_sp;
459 };
460 void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {  }
461 
462 void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {  }
463 #endif //PRODUCT