1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "jni_compiler.h" 18 19 #include <algorithm> 20 #include <fstream> 21 #include <ios> 22 #include <memory> 23 #include <vector> 24 25 #include "art_method.h" 26 #include "base/arena_allocator.h" 27 #include "base/enums.h" 28 #include "base/logging.h" // For VLOG. 29 #include "base/macros.h" 30 #include "base/malloc_arena_pool.h" 31 #include "base/memory_region.h" 32 #include "base/utils.h" 33 #include "calling_convention.h" 34 #include "class_linker.h" 35 #include "dwarf/debug_frame_opcode_writer.h" 36 #include "dex/dex_file-inl.h" 37 #include "driver/compiler_options.h" 38 #include "entrypoints/quick/quick_entrypoints.h" 39 #include "jni/jni_env_ext.h" 40 #include "thread.h" 41 #include "utils/arm/managed_register_arm.h" 42 #include "utils/arm64/managed_register_arm64.h" 43 #include "utils/assembler.h" 44 #include "utils/jni_macro_assembler.h" 45 #include "utils/managed_register.h" 46 #include "utils/mips/managed_register_mips.h" 47 #include "utils/mips64/managed_register_mips64.h" 48 #include "utils/x86/managed_register_x86.h" 49 50 #define __ jni_asm-> 51 52 namespace art { 53 54 template <PointerSize kPointerSize> 55 static void CopyParameter(JNIMacroAssembler<kPointerSize>* jni_asm, 56 ManagedRuntimeCallingConvention* mr_conv, 57 JniCallingConvention* jni_conv, 58 size_t frame_size, size_t out_arg_size); 59 template <PointerSize kPointerSize> 60 static void SetNativeParameter(JNIMacroAssembler<kPointerSize>* jni_asm, 61 JniCallingConvention* jni_conv, 62 ManagedRegister in_reg); 63 64 template <PointerSize kPointerSize> 65 static std::unique_ptr<JNIMacroAssembler<kPointerSize>> GetMacroAssembler( 66 ArenaAllocator* allocator, InstructionSet isa, const InstructionSetFeatures* features) { 67 return JNIMacroAssembler<kPointerSize>::Create(allocator, isa, features); 68 } 69 70 enum class JniEntrypoint { 71 kStart, 72 kEnd 73 }; 74 75 template <PointerSize kPointerSize> 76 static ThreadOffset<kPointerSize> GetJniEntrypointThreadOffset(JniEntrypoint which, 77 bool reference_return, 78 bool is_synchronized, 79 bool is_fast_native) { 80 if (which == JniEntrypoint::kStart) { // JniMethodStart 81 ThreadOffset<kPointerSize> jni_start = 82 is_synchronized 83 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodStartSynchronized) 84 : (is_fast_native 85 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodFastStart) 86 : QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodStart)); 87 88 return jni_start; 89 } else { // JniMethodEnd 90 ThreadOffset<kPointerSize> jni_end(-1); 91 if (reference_return) { 92 // Pass result. 93 jni_end = is_synchronized 94 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEndWithReferenceSynchronized) 95 : (is_fast_native 96 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodFastEndWithReference) 97 : QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEndWithReference)); 98 } else { 99 jni_end = is_synchronized 100 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEndSynchronized) 101 : (is_fast_native 102 ? QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodFastEnd) 103 : QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEnd)); 104 } 105 106 return jni_end; 107 } 108 } 109 110 111 // Generate the JNI bridge for the given method, general contract: 112 // - Arguments are in the managed runtime format, either on stack or in 113 // registers, a reference to the method object is supplied as part of this 114 // convention. 115 // 116 template <PointerSize kPointerSize> 117 static JniCompiledMethod ArtJniCompileMethodInternal(const CompilerOptions& compiler_options, 118 uint32_t access_flags, 119 uint32_t method_idx, 120 const DexFile& dex_file) { 121 const bool is_native = (access_flags & kAccNative) != 0; 122 CHECK(is_native); 123 const bool is_static = (access_flags & kAccStatic) != 0; 124 const bool is_synchronized = (access_flags & kAccSynchronized) != 0; 125 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx)); 126 InstructionSet instruction_set = compiler_options.GetInstructionSet(); 127 const InstructionSetFeatures* instruction_set_features = 128 compiler_options.GetInstructionSetFeatures(); 129 130 // i.e. if the method was annotated with @FastNative 131 const bool is_fast_native = (access_flags & kAccFastNative) != 0u; 132 133 // i.e. if the method was annotated with @CriticalNative 134 bool is_critical_native = (access_flags & kAccCriticalNative) != 0u; 135 136 VLOG(jni) << "JniCompile: Method :: " 137 << dex_file.PrettyMethod(method_idx, /* with signature */ true) 138 << " :: access_flags = " << std::hex << access_flags << std::dec; 139 140 if (UNLIKELY(is_fast_native)) { 141 VLOG(jni) << "JniCompile: Fast native method detected :: " 142 << dex_file.PrettyMethod(method_idx, /* with signature */ true); 143 } 144 145 if (UNLIKELY(is_critical_native)) { 146 VLOG(jni) << "JniCompile: Critical native method detected :: " 147 << dex_file.PrettyMethod(method_idx, /* with signature */ true); 148 } 149 150 if (kIsDebugBuild) { 151 // Don't allow both @FastNative and @CriticalNative. They are mutually exclusive. 152 if (UNLIKELY(is_fast_native && is_critical_native)) { 153 LOG(FATAL) << "JniCompile: Method cannot be both @CriticalNative and @FastNative" 154 << dex_file.PrettyMethod(method_idx, /* with_signature= */ true); 155 } 156 157 // @CriticalNative - extra checks: 158 // -- Don't allow virtual criticals 159 // -- Don't allow synchronized criticals 160 // -- Don't allow any objects as parameter or return value 161 if (UNLIKELY(is_critical_native)) { 162 CHECK(is_static) 163 << "@CriticalNative functions cannot be virtual since that would" 164 << "require passing a reference parameter (this), which is illegal " 165 << dex_file.PrettyMethod(method_idx, /* with_signature= */ true); 166 CHECK(!is_synchronized) 167 << "@CriticalNative functions cannot be synchronized since that would" 168 << "require passing a (class and/or this) reference parameter, which is illegal " 169 << dex_file.PrettyMethod(method_idx, /* with_signature= */ true); 170 for (size_t i = 0; i < strlen(shorty); ++i) { 171 CHECK_NE(Primitive::kPrimNot, Primitive::GetType(shorty[i])) 172 << "@CriticalNative methods' shorty types must not have illegal references " 173 << dex_file.PrettyMethod(method_idx, /* with_signature= */ true); 174 } 175 } 176 } 177 178 MallocArenaPool pool; 179 ArenaAllocator allocator(&pool); 180 181 // Calling conventions used to iterate over parameters to method 182 std::unique_ptr<JniCallingConvention> main_jni_conv = 183 JniCallingConvention::Create(&allocator, 184 is_static, 185 is_synchronized, 186 is_critical_native, 187 shorty, 188 instruction_set); 189 bool reference_return = main_jni_conv->IsReturnAReference(); 190 191 std::unique_ptr<ManagedRuntimeCallingConvention> mr_conv( 192 ManagedRuntimeCallingConvention::Create( 193 &allocator, is_static, is_synchronized, shorty, instruction_set)); 194 195 // Calling conventions to call into JNI method "end" possibly passing a returned reference, the 196 // method and the current thread. 197 const char* jni_end_shorty; 198 if (reference_return && is_synchronized) { 199 jni_end_shorty = "ILL"; 200 } else if (reference_return) { 201 jni_end_shorty = "IL"; 202 } else if (is_synchronized) { 203 jni_end_shorty = "VL"; 204 } else { 205 jni_end_shorty = "V"; 206 } 207 208 std::unique_ptr<JniCallingConvention> end_jni_conv( 209 JniCallingConvention::Create(&allocator, 210 is_static, 211 is_synchronized, 212 is_critical_native, 213 jni_end_shorty, 214 instruction_set)); 215 216 // Assembler that holds generated instructions 217 std::unique_ptr<JNIMacroAssembler<kPointerSize>> jni_asm = 218 GetMacroAssembler<kPointerSize>(&allocator, instruction_set, instruction_set_features); 219 jni_asm->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo()); 220 jni_asm->SetEmitRunTimeChecksInDebugMode(compiler_options.EmitRunTimeChecksInDebugMode()); 221 222 // 1. Build the frame saving all callee saves, Method*, and PC return address. 223 const size_t frame_size(main_jni_conv->FrameSize()); // Excludes outgoing args. 224 ArrayRef<const ManagedRegister> callee_save_regs = main_jni_conv->CalleeSaveRegisters(); 225 __ BuildFrame(frame_size, mr_conv->MethodRegister(), callee_save_regs, mr_conv->EntrySpills()); 226 DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size)); 227 228 if (LIKELY(!is_critical_native)) { 229 // NOTE: @CriticalNative methods don't have a HandleScope 230 // because they can't have any reference parameters or return values. 231 232 // 2. Set up the HandleScope 233 mr_conv->ResetIterator(FrameOffset(frame_size)); 234 main_jni_conv->ResetIterator(FrameOffset(0)); 235 __ StoreImmediateToFrame(main_jni_conv->HandleScopeNumRefsOffset(), 236 main_jni_conv->ReferenceCount(), 237 mr_conv->InterproceduralScratchRegister()); 238 239 __ CopyRawPtrFromThread(main_jni_conv->HandleScopeLinkOffset(), 240 Thread::TopHandleScopeOffset<kPointerSize>(), 241 mr_conv->InterproceduralScratchRegister()); 242 __ StoreStackOffsetToThread(Thread::TopHandleScopeOffset<kPointerSize>(), 243 main_jni_conv->HandleScopeOffset(), 244 mr_conv->InterproceduralScratchRegister()); 245 246 // 3. Place incoming reference arguments into handle scope 247 main_jni_conv->Next(); // Skip JNIEnv* 248 // 3.5. Create Class argument for static methods out of passed method 249 if (is_static) { 250 FrameOffset handle_scope_offset = main_jni_conv->CurrentParamHandleScopeEntryOffset(); 251 // Check handle scope offset is within frame 252 CHECK_LT(handle_scope_offset.Uint32Value(), frame_size); 253 // Note this LoadRef() doesn't need heap unpoisoning since it's from the ArtMethod. 254 // Note this LoadRef() does not include read barrier. It will be handled below. 255 // 256 // scratchRegister = *method[DeclaringClassOffset()]; 257 __ LoadRef(main_jni_conv->InterproceduralScratchRegister(), 258 mr_conv->MethodRegister(), ArtMethod::DeclaringClassOffset(), false); 259 __ VerifyObject(main_jni_conv->InterproceduralScratchRegister(), false); 260 // *handleScopeOffset = scratchRegister 261 __ StoreRef(handle_scope_offset, main_jni_conv->InterproceduralScratchRegister()); 262 main_jni_conv->Next(); // in handle scope so move to next argument 263 } 264 // Place every reference into the handle scope (ignore other parameters). 265 while (mr_conv->HasNext()) { 266 CHECK(main_jni_conv->HasNext()); 267 bool ref_param = main_jni_conv->IsCurrentParamAReference(); 268 CHECK(!ref_param || mr_conv->IsCurrentParamAReference()); 269 // References need placing in handle scope and the entry value passing 270 if (ref_param) { 271 // Compute handle scope entry, note null is placed in the handle scope but its boxed value 272 // must be null. 273 FrameOffset handle_scope_offset = main_jni_conv->CurrentParamHandleScopeEntryOffset(); 274 // Check handle scope offset is within frame and doesn't run into the saved segment state. 275 CHECK_LT(handle_scope_offset.Uint32Value(), frame_size); 276 CHECK_NE(handle_scope_offset.Uint32Value(), 277 main_jni_conv->SavedLocalReferenceCookieOffset().Uint32Value()); 278 bool input_in_reg = mr_conv->IsCurrentParamInRegister(); 279 bool input_on_stack = mr_conv->IsCurrentParamOnStack(); 280 CHECK(input_in_reg || input_on_stack); 281 282 if (input_in_reg) { 283 ManagedRegister in_reg = mr_conv->CurrentParamRegister(); 284 __ VerifyObject(in_reg, mr_conv->IsCurrentArgPossiblyNull()); 285 __ StoreRef(handle_scope_offset, in_reg); 286 } else if (input_on_stack) { 287 FrameOffset in_off = mr_conv->CurrentParamStackOffset(); 288 __ VerifyObject(in_off, mr_conv->IsCurrentArgPossiblyNull()); 289 __ CopyRef(handle_scope_offset, in_off, 290 mr_conv->InterproceduralScratchRegister()); 291 } 292 } 293 mr_conv->Next(); 294 main_jni_conv->Next(); 295 } 296 297 // 4. Write out the end of the quick frames. 298 __ StoreStackPointerToThread(Thread::TopOfManagedStackOffset<kPointerSize>()); 299 300 // NOTE: @CriticalNative does not need to store the stack pointer to the thread 301 // because garbage collections are disabled within the execution of a 302 // @CriticalNative method. 303 // (TODO: We could probably disable it for @FastNative too). 304 } // if (!is_critical_native) 305 306 // 5. Move frame down to allow space for out going args. 307 const size_t main_out_arg_size = main_jni_conv->OutArgSize(); 308 size_t current_out_arg_size = main_out_arg_size; 309 __ IncreaseFrameSize(main_out_arg_size); 310 311 // Call the read barrier for the declaring class loaded from the method for a static call. 312 // Skip this for @CriticalNative because we didn't build a HandleScope to begin with. 313 // Note that we always have outgoing param space available for at least two params. 314 if (kUseReadBarrier && is_static && !is_critical_native) { 315 const bool kReadBarrierFastPath = 316 (instruction_set != InstructionSet::kMips) && (instruction_set != InstructionSet::kMips64); 317 std::unique_ptr<JNIMacroLabel> skip_cold_path_label; 318 if (kReadBarrierFastPath) { 319 skip_cold_path_label = __ CreateLabel(); 320 // Fast path for supported targets. 321 // 322 // Check if gc_is_marking is set -- if it's not, we don't need 323 // a read barrier so skip it. 324 __ LoadFromThread(main_jni_conv->InterproceduralScratchRegister(), 325 Thread::IsGcMarkingOffset<kPointerSize>(), 326 Thread::IsGcMarkingSize()); 327 // Jump over the slow path if gc is marking is false. 328 __ Jump(skip_cold_path_label.get(), 329 JNIMacroUnaryCondition::kZero, 330 main_jni_conv->InterproceduralScratchRegister()); 331 } 332 333 // Construct slow path for read barrier: 334 // 335 // Call into the runtime's ReadBarrierJni and have it fix up 336 // the object address if it was moved. 337 338 ThreadOffset<kPointerSize> read_barrier = QUICK_ENTRYPOINT_OFFSET(kPointerSize, 339 pReadBarrierJni); 340 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 341 main_jni_conv->Next(); // Skip JNIEnv. 342 FrameOffset class_handle_scope_offset = main_jni_conv->CurrentParamHandleScopeEntryOffset(); 343 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 344 // Pass the handle for the class as the first argument. 345 if (main_jni_conv->IsCurrentParamOnStack()) { 346 FrameOffset out_off = main_jni_conv->CurrentParamStackOffset(); 347 __ CreateHandleScopeEntry(out_off, class_handle_scope_offset, 348 mr_conv->InterproceduralScratchRegister(), 349 false); 350 } else { 351 ManagedRegister out_reg = main_jni_conv->CurrentParamRegister(); 352 __ CreateHandleScopeEntry(out_reg, class_handle_scope_offset, 353 ManagedRegister::NoRegister(), false); 354 } 355 main_jni_conv->Next(); 356 // Pass the current thread as the second argument and call. 357 if (main_jni_conv->IsCurrentParamInRegister()) { 358 __ GetCurrentThread(main_jni_conv->CurrentParamRegister()); 359 __ Call(main_jni_conv->CurrentParamRegister(), 360 Offset(read_barrier), 361 main_jni_conv->InterproceduralScratchRegister()); 362 } else { 363 __ GetCurrentThread(main_jni_conv->CurrentParamStackOffset(), 364 main_jni_conv->InterproceduralScratchRegister()); 365 __ CallFromThread(read_barrier, main_jni_conv->InterproceduralScratchRegister()); 366 } 367 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); // Reset. 368 369 if (kReadBarrierFastPath) { 370 __ Bind(skip_cold_path_label.get()); 371 } 372 } 373 374 // 6. Call into appropriate JniMethodStart passing Thread* so that transition out of Runnable 375 // can occur. The result is the saved JNI local state that is restored by the exit call. We 376 // abuse the JNI calling convention here, that is guaranteed to support passing 2 pointer 377 // arguments. 378 FrameOffset locked_object_handle_scope_offset(0xBEEFDEAD); 379 if (LIKELY(!is_critical_native)) { 380 // Skip this for @CriticalNative methods. They do not call JniMethodStart. 381 ThreadOffset<kPointerSize> jni_start( 382 GetJniEntrypointThreadOffset<kPointerSize>(JniEntrypoint::kStart, 383 reference_return, 384 is_synchronized, 385 is_fast_native).SizeValue()); 386 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 387 locked_object_handle_scope_offset = FrameOffset(0); 388 if (is_synchronized) { 389 // Pass object for locking. 390 main_jni_conv->Next(); // Skip JNIEnv. 391 locked_object_handle_scope_offset = main_jni_conv->CurrentParamHandleScopeEntryOffset(); 392 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 393 if (main_jni_conv->IsCurrentParamOnStack()) { 394 FrameOffset out_off = main_jni_conv->CurrentParamStackOffset(); 395 __ CreateHandleScopeEntry(out_off, locked_object_handle_scope_offset, 396 mr_conv->InterproceduralScratchRegister(), false); 397 } else { 398 ManagedRegister out_reg = main_jni_conv->CurrentParamRegister(); 399 __ CreateHandleScopeEntry(out_reg, locked_object_handle_scope_offset, 400 ManagedRegister::NoRegister(), false); 401 } 402 main_jni_conv->Next(); 403 } 404 if (main_jni_conv->IsCurrentParamInRegister()) { 405 __ GetCurrentThread(main_jni_conv->CurrentParamRegister()); 406 __ Call(main_jni_conv->CurrentParamRegister(), 407 Offset(jni_start), 408 main_jni_conv->InterproceduralScratchRegister()); 409 } else { 410 __ GetCurrentThread(main_jni_conv->CurrentParamStackOffset(), 411 main_jni_conv->InterproceduralScratchRegister()); 412 __ CallFromThread(jni_start, main_jni_conv->InterproceduralScratchRegister()); 413 } 414 if (is_synchronized) { // Check for exceptions from monitor enter. 415 __ ExceptionPoll(main_jni_conv->InterproceduralScratchRegister(), main_out_arg_size); 416 } 417 } 418 419 // Store into stack_frame[saved_cookie_offset] the return value of JniMethodStart. 420 FrameOffset saved_cookie_offset( 421 FrameOffset(0xDEADBEEFu)); // @CriticalNative - use obviously bad value for debugging 422 if (LIKELY(!is_critical_native)) { 423 saved_cookie_offset = main_jni_conv->SavedLocalReferenceCookieOffset(); 424 __ Store(saved_cookie_offset, main_jni_conv->IntReturnRegister(), 4 /* sizeof cookie */); 425 } 426 427 // 7. Iterate over arguments placing values from managed calling convention in 428 // to the convention required for a native call (shuffling). For references 429 // place an index/pointer to the reference after checking whether it is 430 // null (which must be encoded as null). 431 // Note: we do this prior to materializing the JNIEnv* and static's jclass to 432 // give as many free registers for the shuffle as possible. 433 mr_conv->ResetIterator(FrameOffset(frame_size + main_out_arg_size)); 434 uint32_t args_count = 0; 435 while (mr_conv->HasNext()) { 436 args_count++; 437 mr_conv->Next(); 438 } 439 440 // Do a backward pass over arguments, so that the generated code will be "mov 441 // R2, R3; mov R1, R2" instead of "mov R1, R2; mov R2, R3." 442 // TODO: A reverse iterator to improve readability. 443 for (uint32_t i = 0; i < args_count; ++i) { 444 mr_conv->ResetIterator(FrameOffset(frame_size + main_out_arg_size)); 445 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 446 447 // Skip the extra JNI parameters for now. 448 if (LIKELY(!is_critical_native)) { 449 main_jni_conv->Next(); // Skip JNIEnv*. 450 if (is_static) { 451 main_jni_conv->Next(); // Skip Class for now. 452 } 453 } 454 // Skip to the argument we're interested in. 455 for (uint32_t j = 0; j < args_count - i - 1; ++j) { 456 mr_conv->Next(); 457 main_jni_conv->Next(); 458 } 459 CopyParameter(jni_asm.get(), mr_conv.get(), main_jni_conv.get(), frame_size, main_out_arg_size); 460 } 461 if (is_static && !is_critical_native) { 462 // Create argument for Class 463 mr_conv->ResetIterator(FrameOffset(frame_size + main_out_arg_size)); 464 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 465 main_jni_conv->Next(); // Skip JNIEnv* 466 FrameOffset handle_scope_offset = main_jni_conv->CurrentParamHandleScopeEntryOffset(); 467 if (main_jni_conv->IsCurrentParamOnStack()) { 468 FrameOffset out_off = main_jni_conv->CurrentParamStackOffset(); 469 __ CreateHandleScopeEntry(out_off, handle_scope_offset, 470 mr_conv->InterproceduralScratchRegister(), 471 false); 472 } else { 473 ManagedRegister out_reg = main_jni_conv->CurrentParamRegister(); 474 __ CreateHandleScopeEntry(out_reg, handle_scope_offset, 475 ManagedRegister::NoRegister(), false); 476 } 477 } 478 479 // Set the iterator back to the incoming Method*. 480 main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size)); 481 if (LIKELY(!is_critical_native)) { 482 // 8. Create 1st argument, the JNI environment ptr. 483 // Register that will hold local indirect reference table 484 if (main_jni_conv->IsCurrentParamInRegister()) { 485 ManagedRegister jni_env = main_jni_conv->CurrentParamRegister(); 486 DCHECK(!jni_env.Equals(main_jni_conv->InterproceduralScratchRegister())); 487 __ LoadRawPtrFromThread(jni_env, Thread::JniEnvOffset<kPointerSize>()); 488 } else { 489 FrameOffset jni_env = main_jni_conv->CurrentParamStackOffset(); 490 __ CopyRawPtrFromThread(jni_env, 491 Thread::JniEnvOffset<kPointerSize>(), 492 main_jni_conv->InterproceduralScratchRegister()); 493 } 494 } 495 496 // 9. Plant call to native code associated with method. 497 MemberOffset jni_entrypoint_offset = 498 ArtMethod::EntryPointFromJniOffset(InstructionSetPointerSize(instruction_set)); 499 // FIXME: Not sure if MethodStackOffset will work here. What does it even do? 500 __ Call(main_jni_conv->MethodStackOffset(), 501 jni_entrypoint_offset, 502 // XX: Why not the jni conv scratch register? 503 mr_conv->InterproceduralScratchRegister()); 504 505 // 10. Fix differences in result widths. 506 if (main_jni_conv->RequiresSmallResultTypeExtension()) { 507 if (main_jni_conv->GetReturnType() == Primitive::kPrimByte || 508 main_jni_conv->GetReturnType() == Primitive::kPrimShort) { 509 __ SignExtend(main_jni_conv->ReturnRegister(), 510 Primitive::ComponentSize(main_jni_conv->GetReturnType())); 511 } else if (main_jni_conv->GetReturnType() == Primitive::kPrimBoolean || 512 main_jni_conv->GetReturnType() == Primitive::kPrimChar) { 513 __ ZeroExtend(main_jni_conv->ReturnRegister(), 514 Primitive::ComponentSize(main_jni_conv->GetReturnType())); 515 } 516 } 517 518 // 11. Process return value 519 FrameOffset return_save_location = main_jni_conv->ReturnValueSaveLocation(); 520 if (main_jni_conv->SizeOfReturnValue() != 0 && !reference_return) { 521 if (LIKELY(!is_critical_native)) { 522 // For normal JNI, store the return value on the stack because the call to 523 // JniMethodEnd will clobber the return value. It will be restored in (13). 524 if ((instruction_set == InstructionSet::kMips || 525 instruction_set == InstructionSet::kMips64) && 526 main_jni_conv->GetReturnType() == Primitive::kPrimDouble && 527 return_save_location.Uint32Value() % 8 != 0) { 528 // Ensure doubles are 8-byte aligned for MIPS 529 return_save_location = FrameOffset(return_save_location.Uint32Value() 530 + static_cast<size_t>(kMipsPointerSize)); 531 // TODO: refactor this into the JniCallingConvention code 532 // as a return value alignment requirement. 533 } 534 CHECK_LT(return_save_location.Uint32Value(), frame_size + main_out_arg_size); 535 __ Store(return_save_location, 536 main_jni_conv->ReturnRegister(), 537 main_jni_conv->SizeOfReturnValue()); 538 } else { 539 // For @CriticalNative only, 540 // move the JNI return register into the managed return register (if they don't match). 541 ManagedRegister jni_return_reg = main_jni_conv->ReturnRegister(); 542 ManagedRegister mr_return_reg = mr_conv->ReturnRegister(); 543 544 // Check if the JNI return register matches the managed return register. 545 // If they differ, only then do we have to do anything about it. 546 // Otherwise the return value is already in the right place when we return. 547 if (!jni_return_reg.Equals(mr_return_reg)) { 548 // This is typically only necessary on ARM32 due to native being softfloat 549 // while managed is hardfloat. 550 // -- For example VMOV {r0, r1} -> D0; VMOV r0 -> S0. 551 __ Move(mr_return_reg, jni_return_reg, main_jni_conv->SizeOfReturnValue()); 552 } else if (jni_return_reg.IsNoRegister() && mr_return_reg.IsNoRegister()) { 553 // Sanity check: If the return value is passed on the stack for some reason, 554 // then make sure the size matches. 555 CHECK_EQ(main_jni_conv->SizeOfReturnValue(), mr_conv->SizeOfReturnValue()); 556 } 557 } 558 } 559 560 // Increase frame size for out args if needed by the end_jni_conv. 561 const size_t end_out_arg_size = end_jni_conv->OutArgSize(); 562 if (end_out_arg_size > current_out_arg_size) { 563 size_t out_arg_size_diff = end_out_arg_size - current_out_arg_size; 564 current_out_arg_size = end_out_arg_size; 565 // TODO: This is redundant for @CriticalNative but we need to 566 // conditionally do __DecreaseFrameSize below. 567 __ IncreaseFrameSize(out_arg_size_diff); 568 saved_cookie_offset = FrameOffset(saved_cookie_offset.SizeValue() + out_arg_size_diff); 569 locked_object_handle_scope_offset = 570 FrameOffset(locked_object_handle_scope_offset.SizeValue() + out_arg_size_diff); 571 return_save_location = FrameOffset(return_save_location.SizeValue() + out_arg_size_diff); 572 } 573 // thread. 574 end_jni_conv->ResetIterator(FrameOffset(end_out_arg_size)); 575 576 if (LIKELY(!is_critical_native)) { 577 // 12. Call JniMethodEnd 578 ThreadOffset<kPointerSize> jni_end( 579 GetJniEntrypointThreadOffset<kPointerSize>(JniEntrypoint::kEnd, 580 reference_return, 581 is_synchronized, 582 is_fast_native).SizeValue()); 583 if (reference_return) { 584 // Pass result. 585 SetNativeParameter(jni_asm.get(), end_jni_conv.get(), end_jni_conv->ReturnRegister()); 586 end_jni_conv->Next(); 587 } 588 // Pass saved local reference state. 589 if (end_jni_conv->IsCurrentParamOnStack()) { 590 FrameOffset out_off = end_jni_conv->CurrentParamStackOffset(); 591 __ Copy(out_off, saved_cookie_offset, end_jni_conv->InterproceduralScratchRegister(), 4); 592 } else { 593 ManagedRegister out_reg = end_jni_conv->CurrentParamRegister(); 594 __ Load(out_reg, saved_cookie_offset, 4); 595 } 596 end_jni_conv->Next(); 597 if (is_synchronized) { 598 // Pass object for unlocking. 599 if (end_jni_conv->IsCurrentParamOnStack()) { 600 FrameOffset out_off = end_jni_conv->CurrentParamStackOffset(); 601 __ CreateHandleScopeEntry(out_off, locked_object_handle_scope_offset, 602 end_jni_conv->InterproceduralScratchRegister(), 603 false); 604 } else { 605 ManagedRegister out_reg = end_jni_conv->CurrentParamRegister(); 606 __ CreateHandleScopeEntry(out_reg, locked_object_handle_scope_offset, 607 ManagedRegister::NoRegister(), false); 608 } 609 end_jni_conv->Next(); 610 } 611 if (end_jni_conv->IsCurrentParamInRegister()) { 612 __ GetCurrentThread(end_jni_conv->CurrentParamRegister()); 613 __ Call(end_jni_conv->CurrentParamRegister(), 614 Offset(jni_end), 615 end_jni_conv->InterproceduralScratchRegister()); 616 } else { 617 __ GetCurrentThread(end_jni_conv->CurrentParamStackOffset(), 618 end_jni_conv->InterproceduralScratchRegister()); 619 __ CallFromThread(jni_end, end_jni_conv->InterproceduralScratchRegister()); 620 } 621 622 // 13. Reload return value 623 if (main_jni_conv->SizeOfReturnValue() != 0 && !reference_return) { 624 __ Load(mr_conv->ReturnRegister(), return_save_location, mr_conv->SizeOfReturnValue()); 625 // NIT: If it's @CriticalNative then we actually only need to do this IF 626 // the calling convention's native return register doesn't match the managed convention's 627 // return register. 628 } 629 } // if (!is_critical_native) 630 631 // 14. Move frame up now we're done with the out arg space. 632 __ DecreaseFrameSize(current_out_arg_size); 633 634 // 15. Process pending exceptions from JNI call or monitor exit. 635 __ ExceptionPoll(main_jni_conv->InterproceduralScratchRegister(), 0 /* stack_adjust= */); 636 637 // 16. Remove activation - need to restore callee save registers since the GC may have changed 638 // them. 639 DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size)); 640 // We expect the compiled method to possibly be suspended during its 641 // execution, except in the case of a CriticalNative method. 642 bool may_suspend = !is_critical_native; 643 __ RemoveFrame(frame_size, callee_save_regs, may_suspend); 644 DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size)); 645 646 // 17. Finalize code generation 647 __ FinalizeCode(); 648 size_t cs = __ CodeSize(); 649 std::vector<uint8_t> managed_code(cs); 650 MemoryRegion code(&managed_code[0], managed_code.size()); 651 __ FinalizeInstructions(code); 652 653 return JniCompiledMethod(instruction_set, 654 std::move(managed_code), 655 frame_size, 656 main_jni_conv->CoreSpillMask(), 657 main_jni_conv->FpSpillMask(), 658 ArrayRef<const uint8_t>(*jni_asm->cfi().data())); 659 } 660 661 // Copy a single parameter from the managed to the JNI calling convention. 662 template <PointerSize kPointerSize> 663 static void CopyParameter(JNIMacroAssembler<kPointerSize>* jni_asm, 664 ManagedRuntimeCallingConvention* mr_conv, 665 JniCallingConvention* jni_conv, 666 size_t frame_size, 667 size_t out_arg_size) { 668 bool input_in_reg = mr_conv->IsCurrentParamInRegister(); 669 bool output_in_reg = jni_conv->IsCurrentParamInRegister(); 670 FrameOffset handle_scope_offset(0); 671 bool null_allowed = false; 672 bool ref_param = jni_conv->IsCurrentParamAReference(); 673 CHECK(!ref_param || mr_conv->IsCurrentParamAReference()); 674 // input may be in register, on stack or both - but not none! 675 CHECK(input_in_reg || mr_conv->IsCurrentParamOnStack()); 676 if (output_in_reg) { // output shouldn't straddle registers and stack 677 CHECK(!jni_conv->IsCurrentParamOnStack()); 678 } else { 679 CHECK(jni_conv->IsCurrentParamOnStack()); 680 } 681 // References need placing in handle scope and the entry address passing. 682 if (ref_param) { 683 null_allowed = mr_conv->IsCurrentArgPossiblyNull(); 684 // Compute handle scope offset. Note null is placed in the handle scope but the jobject 685 // passed to the native code must be null (not a pointer into the handle scope 686 // as with regular references). 687 handle_scope_offset = jni_conv->CurrentParamHandleScopeEntryOffset(); 688 // Check handle scope offset is within frame. 689 CHECK_LT(handle_scope_offset.Uint32Value(), (frame_size + out_arg_size)); 690 } 691 if (input_in_reg && output_in_reg) { 692 ManagedRegister in_reg = mr_conv->CurrentParamRegister(); 693 ManagedRegister out_reg = jni_conv->CurrentParamRegister(); 694 if (ref_param) { 695 __ CreateHandleScopeEntry(out_reg, handle_scope_offset, in_reg, null_allowed); 696 } else { 697 if (!mr_conv->IsCurrentParamOnStack()) { 698 // regular non-straddling move 699 __ Move(out_reg, in_reg, mr_conv->CurrentParamSize()); 700 } else { 701 UNIMPLEMENTED(FATAL); // we currently don't expect to see this case 702 } 703 } 704 } else if (!input_in_reg && !output_in_reg) { 705 FrameOffset out_off = jni_conv->CurrentParamStackOffset(); 706 if (ref_param) { 707 __ CreateHandleScopeEntry(out_off, handle_scope_offset, mr_conv->InterproceduralScratchRegister(), 708 null_allowed); 709 } else { 710 FrameOffset in_off = mr_conv->CurrentParamStackOffset(); 711 size_t param_size = mr_conv->CurrentParamSize(); 712 CHECK_EQ(param_size, jni_conv->CurrentParamSize()); 713 __ Copy(out_off, in_off, mr_conv->InterproceduralScratchRegister(), param_size); 714 } 715 } else if (!input_in_reg && output_in_reg) { 716 FrameOffset in_off = mr_conv->CurrentParamStackOffset(); 717 ManagedRegister out_reg = jni_conv->CurrentParamRegister(); 718 // Check that incoming stack arguments are above the current stack frame. 719 CHECK_GT(in_off.Uint32Value(), frame_size); 720 if (ref_param) { 721 __ CreateHandleScopeEntry(out_reg, handle_scope_offset, ManagedRegister::NoRegister(), null_allowed); 722 } else { 723 size_t param_size = mr_conv->CurrentParamSize(); 724 CHECK_EQ(param_size, jni_conv->CurrentParamSize()); 725 __ Load(out_reg, in_off, param_size); 726 } 727 } else { 728 CHECK(input_in_reg && !output_in_reg); 729 ManagedRegister in_reg = mr_conv->CurrentParamRegister(); 730 FrameOffset out_off = jni_conv->CurrentParamStackOffset(); 731 // Check outgoing argument is within frame 732 CHECK_LT(out_off.Uint32Value(), frame_size); 733 if (ref_param) { 734 // TODO: recycle value in in_reg rather than reload from handle scope 735 __ CreateHandleScopeEntry(out_off, handle_scope_offset, mr_conv->InterproceduralScratchRegister(), 736 null_allowed); 737 } else { 738 size_t param_size = mr_conv->CurrentParamSize(); 739 CHECK_EQ(param_size, jni_conv->CurrentParamSize()); 740 if (!mr_conv->IsCurrentParamOnStack()) { 741 // regular non-straddling store 742 __ Store(out_off, in_reg, param_size); 743 } else { 744 // store where input straddles registers and stack 745 CHECK_EQ(param_size, 8u); 746 FrameOffset in_off = mr_conv->CurrentParamStackOffset(); 747 __ StoreSpanning(out_off, in_reg, in_off, mr_conv->InterproceduralScratchRegister()); 748 } 749 } 750 } 751 } 752 753 template <PointerSize kPointerSize> 754 static void SetNativeParameter(JNIMacroAssembler<kPointerSize>* jni_asm, 755 JniCallingConvention* jni_conv, 756 ManagedRegister in_reg) { 757 if (jni_conv->IsCurrentParamOnStack()) { 758 FrameOffset dest = jni_conv->CurrentParamStackOffset(); 759 __ StoreRawPtr(dest, in_reg); 760 } else { 761 if (!jni_conv->CurrentParamRegister().Equals(in_reg)) { 762 __ Move(jni_conv->CurrentParamRegister(), in_reg, jni_conv->CurrentParamSize()); 763 } 764 } 765 } 766 767 JniCompiledMethod ArtQuickJniCompileMethod(const CompilerOptions& compiler_options, 768 uint32_t access_flags, 769 uint32_t method_idx, 770 const DexFile& dex_file) { 771 if (Is64BitInstructionSet(compiler_options.GetInstructionSet())) { 772 return ArtJniCompileMethodInternal<PointerSize::k64>( 773 compiler_options, access_flags, method_idx, dex_file); 774 } else { 775 return ArtJniCompileMethodInternal<PointerSize::k32>( 776 compiler_options, access_flags, method_idx, dex_file); 777 } 778 } 779 780 } // namespace art 781