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