• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/arena_containers.h"
28 #include "base/logging.h"  // For VLOG.
29 #include "base/macros.h"
30 #include "base/memory_region.h"
31 #include "base/pointer_size.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 "driver/compiler_options.h"
37 #include "entrypoints/quick/quick_entrypoints.h"
38 #include "instrumentation.h"
39 #include "jni/jni_env_ext.h"
40 #include "jni/local_reference_table.h"
41 #include "runtime.h"
42 #include "thread.h"
43 #include "utils/arm/managed_register_arm.h"
44 #include "utils/arm64/managed_register_arm64.h"
45 #include "utils/assembler.h"
46 #include "utils/jni_macro_assembler.h"
47 #include "utils/managed_register.h"
48 #include "utils/x86/managed_register_x86.h"
49 
50 #define __ jni_asm->
51 
52 namespace art HIDDEN {
53 
54 template <PointerSize kPointerSize>
55 static void SetNativeParameter(JNIMacroAssembler<kPointerSize>* jni_asm,
56                                JniCallingConvention* jni_conv,
57                                ManagedRegister in_reg);
58 
59 template <PointerSize kPointerSize>
60 static void CallDecodeReferenceResult(JNIMacroAssembler<kPointerSize>* jni_asm,
61                                       JniCallingConvention* jni_conv,
62                                       ManagedRegister mr_return_reg,
63                                       size_t main_out_arg_size);
64 
65 template <PointerSize kPointerSize>
GetMacroAssembler(ArenaAllocator * allocator,InstructionSet isa,const InstructionSetFeatures * features)66 static std::unique_ptr<JNIMacroAssembler<kPointerSize>> GetMacroAssembler(
67     ArenaAllocator* allocator, InstructionSet isa, const InstructionSetFeatures* features) {
68   return JNIMacroAssembler<kPointerSize>::Create(allocator, isa, features);
69 }
70 
71 
72 // Generate the JNI bridge for the given method, general contract:
73 // - Arguments are in the managed runtime format, either on stack or in
74 //   registers, a reference to the method object is supplied as part of this
75 //   convention.
76 //
77 template <PointerSize kPointerSize>
ArtJniCompileMethodInternal(const CompilerOptions & compiler_options,std::string_view shorty,uint32_t access_flags,ArenaAllocator * allocator)78 static JniCompiledMethod ArtJniCompileMethodInternal(const CompilerOptions& compiler_options,
79                                                      std::string_view shorty,
80                                                      uint32_t access_flags,
81                                                      ArenaAllocator* allocator) {
82   constexpr size_t kRawPointerSize = static_cast<size_t>(kPointerSize);
83   CHECK_NE(access_flags & kAccNative, 0u);
84   const bool is_static = (access_flags & kAccStatic) != 0;
85   const bool is_synchronized = (access_flags & kAccSynchronized) != 0;
86   const bool is_fast_native = (access_flags & kAccFastNative) != 0u;
87   const bool is_critical_native = (access_flags & kAccCriticalNative) != 0u;
88 
89   InstructionSet instruction_set = compiler_options.GetInstructionSet();
90   const InstructionSetFeatures* instruction_set_features =
91       compiler_options.GetInstructionSetFeatures();
92   bool emit_read_barrier = compiler_options.EmitReadBarrier();
93   bool is_debuggable = compiler_options.GetDebuggable();
94   bool needs_entry_exit_hooks = is_debuggable && compiler_options.IsJitCompiler();
95   // We don't support JITing stubs for critical native methods in debuggable runtimes yet.
96   // TODO(mythria): Add support required for calling method entry / exit hooks from critical native
97   // methods.
98   DCHECK_IMPLIES(needs_entry_exit_hooks, !is_critical_native);
99 
100   // The fast-path for decoding a reference skips CheckJNI checks, so we do not inline the
101   // decoding in debug build or for debuggable apps (both cases enable CheckJNI by default).
102   bool inline_decode_reference = !kIsDebugBuild && !is_debuggable;
103 
104   // When  walking the stack the top frame doesn't have a pc associated with it. We then depend on
105   // the invariant that we don't have JITed code when AOT code is available. In debuggable runtimes
106   // this invariant doesn't hold. So we tag the SP for JITed code to indentify if we are executing
107   // JITed code or AOT code. Since tagging involves additional instructions we tag only in
108   // debuggable runtimes.
109   bool should_tag_sp = needs_entry_exit_hooks;
110 
111   VLOG(jni) << "JniCompile: shorty=\"" << shorty
112             << "\", access_flags=0x" << std::hex << access_flags
113             << (is_static ? " static" : "")
114             << (is_synchronized ? " synchronized" : "")
115             << (is_fast_native ? " @FastNative" : "")
116             << (is_critical_native ? " @CriticalNative" : "");
117 
118   if (kIsDebugBuild) {
119     // Don't allow both @FastNative and @CriticalNative. They are mutually exclusive.
120     if (UNLIKELY(is_fast_native && is_critical_native)) {
121       LOG(FATAL) << "JniCompile: Method cannot be both @CriticalNative and @FastNative, \""
122                  << shorty << "\", 0x" << std::hex << access_flags;
123     }
124 
125     // @CriticalNative - extra checks:
126     // -- Don't allow virtual criticals
127     // -- Don't allow synchronized criticals
128     // -- Don't allow any objects as parameter or return value
129     if (UNLIKELY(is_critical_native)) {
130       CHECK(is_static)
131           << "@CriticalNative functions cannot be virtual since that would "
132           << "require passing a reference parameter (this), which is illegal, \""
133           << shorty << "\", 0x" << std::hex << access_flags;
134       CHECK(!is_synchronized)
135           << "@CriticalNative functions cannot be synchronized since that would "
136           << "require passing a (class and/or this) reference parameter, which is illegal, \""
137           << shorty << "\", 0x" << std::hex << access_flags;
138       for (char c : shorty) {
139         CHECK_NE(Primitive::kPrimNot, Primitive::GetType(c))
140             << "@CriticalNative methods' shorty types must not have illegal references, \""
141             << shorty << "\", 0x" << std::hex << access_flags;
142       }
143     }
144   }
145 
146   // Calling conventions used to iterate over parameters to method
147   std::unique_ptr<JniCallingConvention> main_jni_conv =
148       JniCallingConvention::Create(allocator,
149                                    is_static,
150                                    is_synchronized,
151                                    is_fast_native,
152                                    is_critical_native,
153                                    shorty,
154                                    instruction_set);
155   bool reference_return = main_jni_conv->IsReturnAReference();
156 
157   std::unique_ptr<ManagedRuntimeCallingConvention> mr_conv(
158       ManagedRuntimeCallingConvention::Create(
159           allocator, is_static, is_synchronized, shorty, instruction_set));
160 
161   // Assembler that holds generated instructions
162   std::unique_ptr<JNIMacroAssembler<kPointerSize>> jni_asm =
163       GetMacroAssembler<kPointerSize>(allocator, instruction_set, instruction_set_features);
164   jni_asm->cfi().SetEnabled(compiler_options.GenerateAnyDebugInfo());
165   jni_asm->SetEmitRunTimeChecksInDebugMode(compiler_options.EmitRunTimeChecksInDebugMode());
166 
167   // 1. Build and register the native method frame.
168 
169   // 1.1. Build the frame saving all callee saves, Method*, and PC return address.
170   //      For @CriticalNative, this includes space for out args, otherwise just the managed frame.
171   const size_t managed_frame_size = main_jni_conv->FrameSize();
172   const size_t main_out_arg_size = main_jni_conv->OutFrameSize();
173   size_t current_frame_size = is_critical_native ? main_out_arg_size : managed_frame_size;
174   ManagedRegister method_register =
175       is_critical_native ? ManagedRegister::NoRegister() : mr_conv->MethodRegister();
176   ArrayRef<const ManagedRegister> callee_save_regs = main_jni_conv->CalleeSaveRegisters();
177   __ BuildFrame(current_frame_size, method_register, callee_save_regs);
178   DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(current_frame_size));
179 
180   // 1.2. Check if we need to go to the slow path to emit the read barrier
181   //      for the declaring class in the method for a static call.
182   //      Skip this for @CriticalNative because we're not passing a `jclass` to the native method.
183   std::unique_ptr<JNIMacroLabel> jclass_read_barrier_slow_path;
184   std::unique_ptr<JNIMacroLabel> jclass_read_barrier_return;
185   if (emit_read_barrier && is_static && LIKELY(!is_critical_native)) {
186     jclass_read_barrier_slow_path = __ CreateLabel();
187     jclass_read_barrier_return = __ CreateLabel();
188 
189     // Check if gc_is_marking is set -- if it's not, we don't need a read barrier.
190     __ TestGcMarking(jclass_read_barrier_slow_path.get(), JNIMacroUnaryCondition::kNotZero);
191 
192     // If marking, the slow path returns after the check.
193     __ Bind(jclass_read_barrier_return.get());
194   }
195 
196   // 1.3 Spill reference register arguments.
197   constexpr FrameOffset kInvalidReferenceOffset =
198       JNIMacroAssembler<kPointerSize>::kInvalidReferenceOffset;
199   ArenaVector<ArgumentLocation> src_args(allocator->Adapter());
200   ArenaVector<ArgumentLocation> dest_args(allocator->Adapter());
201   ArenaVector<FrameOffset> refs(allocator->Adapter());
202   if (LIKELY(!is_critical_native)) {
203     mr_conv->ResetIterator(FrameOffset(current_frame_size));
204     for (; mr_conv->HasNext(); mr_conv->Next()) {
205       if (mr_conv->IsCurrentParamInRegister() && mr_conv->IsCurrentParamAReference()) {
206         // Spill the reference as raw data.
207         src_args.emplace_back(mr_conv->CurrentParamRegister(), kObjectReferenceSize);
208         dest_args.emplace_back(mr_conv->CurrentParamStackOffset(), kObjectReferenceSize);
209         refs.push_back(kInvalidReferenceOffset);
210       }
211     }
212     __ MoveArguments(ArrayRef<ArgumentLocation>(dest_args),
213                      ArrayRef<ArgumentLocation>(src_args),
214                      ArrayRef<FrameOffset>(refs));
215   }
216 
217   // 1.4. Write out the end of the quick frames. After this, we can walk the stack.
218   // NOTE: @CriticalNative does not need to store the stack pointer to the thread
219   //       because garbage collections are disabled within the execution of a
220   //       @CriticalNative method.
221   if (LIKELY(!is_critical_native)) {
222     __ StoreStackPointerToThread(Thread::TopOfManagedStackOffset<kPointerSize>(), should_tag_sp);
223   }
224 
225   // 1.5. Call any method entry hooks if required.
226   // For critical native methods, we don't JIT stubs in debuggable runtimes (see
227   // OptimizingCompiler::JitCompile).
228   // TODO(mythria): Add support to call method entry / exit hooks for critical native methods too.
229   std::unique_ptr<JNIMacroLabel> method_entry_hook_slow_path;
230   std::unique_ptr<JNIMacroLabel> method_entry_hook_return;
231   if (UNLIKELY(needs_entry_exit_hooks)) {
232     uint64_t address = reinterpret_cast64<uint64_t>(Runtime::Current()->GetInstrumentation());
233     int offset = instrumentation::Instrumentation::HaveMethodEntryListenersOffset().Int32Value();
234     method_entry_hook_slow_path = __ CreateLabel();
235     method_entry_hook_return = __ CreateLabel();
236     __ TestByteAndJumpIfNotZero(address + offset, method_entry_hook_slow_path.get());
237     __ Bind(method_entry_hook_return.get());
238   }
239 
240   // 2. Lock the object (if synchronized) and transition out of Runnable (if normal native).
241 
242   // 2.1. Lock the synchronization object (`this` or class) for synchronized methods.
243   if (UNLIKELY(is_synchronized)) {
244     // We are using a custom calling convention for locking where the assembly thunk gets
245     // the object to lock in a register (even on x86), it can use callee-save registers
246     // as temporaries (they were saved above) and must preserve argument registers.
247     ManagedRegister to_lock = main_jni_conv->LockingArgumentRegister();
248     if (is_static) {
249       // Pass the declaring class. It was already marked if needed.
250       DCHECK_EQ(ArtMethod::DeclaringClassOffset().SizeValue(), 0u);
251       __ Load(to_lock, method_register, MemberOffset(0u), kObjectReferenceSize);
252     } else {
253       // Pass the `this` argument.
254       mr_conv->ResetIterator(FrameOffset(current_frame_size));
255       if (mr_conv->IsCurrentParamInRegister()) {
256         __ Move(to_lock, mr_conv->CurrentParamRegister(), kObjectReferenceSize);
257       } else {
258         __ Load(to_lock, mr_conv->CurrentParamStackOffset(), kObjectReferenceSize);
259       }
260     }
261     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniLockObject));
262   }
263 
264   // 2.2. Transition from Runnable to Suspended.
265   // Managed callee-saves were already saved, so these registers are now available.
266   ArrayRef<const ManagedRegister> callee_save_scratch_regs = UNLIKELY(is_critical_native)
267       ? ArrayRef<const ManagedRegister>()
268       : main_jni_conv->CalleeSaveScratchRegisters();
269   std::unique_ptr<JNIMacroLabel> transition_to_native_slow_path;
270   std::unique_ptr<JNIMacroLabel> transition_to_native_resume;
271   if (LIKELY(!is_critical_native && !is_fast_native)) {
272     transition_to_native_slow_path = __ CreateLabel();
273     transition_to_native_resume = __ CreateLabel();
274     __ TryToTransitionFromRunnableToNative(transition_to_native_slow_path.get(),
275                                            callee_save_scratch_regs);
276     __ Bind(transition_to_native_resume.get());
277   }
278 
279   // 3. Push local reference frame.
280   // Skip this for @CriticalNative methods, they cannot use any references.
281   ManagedRegister jni_env_reg = ManagedRegister::NoRegister();
282   ManagedRegister previous_state_reg = ManagedRegister::NoRegister();
283   ManagedRegister current_state_reg = ManagedRegister::NoRegister();
284   ManagedRegister callee_save_temp = ManagedRegister::NoRegister();
285   if (LIKELY(!is_critical_native)) {
286     // To pop the local reference frame later, we shall need the JNI environment pointer
287     // as well as the cookie, so we preserve them across calls in callee-save registers.
288     CHECK_GE(callee_save_scratch_regs.size(), 3u);  // At least 3 for each supported architecture.
289     jni_env_reg = callee_save_scratch_regs[0];
290     constexpr size_t kLRTSegmentStateSize = sizeof(jni::LRTSegmentState);
291     previous_state_reg = __ CoreRegisterWithSize(callee_save_scratch_regs[1], kLRTSegmentStateSize);
292     current_state_reg = __ CoreRegisterWithSize(callee_save_scratch_regs[2], kLRTSegmentStateSize);
293     if (callee_save_scratch_regs.size() >= 4) {
294       callee_save_temp = callee_save_scratch_regs[3];
295     }
296     const MemberOffset previous_state_offset = JNIEnvExt::LrtPreviousStateOffset(kPointerSize);
297 
298     // Load the JNI environment pointer.
299     __ LoadRawPtrFromThread(jni_env_reg, Thread::JniEnvOffset<kPointerSize>());
300 
301     // Load the local reference frame states.
302     __ LoadLocalReferenceTableStates(jni_env_reg, previous_state_reg, current_state_reg);
303 
304     // Store the current state as the previous state (push the LRT frame).
305     __ Store(jni_env_reg, previous_state_offset, current_state_reg, kLRTSegmentStateSize);
306   }
307 
308   // 4. Make the main native call.
309 
310   // 4.1. Move frame down to allow space for out going args.
311   size_t current_out_arg_size = main_out_arg_size;
312   if (UNLIKELY(is_critical_native)) {
313     DCHECK_EQ(main_out_arg_size, current_frame_size);
314   } else {
315     __ IncreaseFrameSize(main_out_arg_size);
316     current_frame_size += main_out_arg_size;
317   }
318 
319   // 4.2. Fill arguments except the `JNIEnv*`.
320   // Note: Non-null reference arguments in registers may point to the from-space if we
321   // took the slow-path for locking or transition to Native. However, we only need to
322   // compare them with null to construct `jobject`s, so we can still use them.
323   src_args.clear();
324   dest_args.clear();
325   refs.clear();
326   mr_conv->ResetIterator(FrameOffset(current_frame_size));
327   main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size));
328   bool check_method_not_clobbered = false;
329   if (UNLIKELY(is_critical_native)) {
330     // Move the method pointer to the hidden argument register.
331     // TODO: Pass this as the last argument, not first. Change ARM assembler
332     // not to expect all register destinations at the beginning.
333     src_args.emplace_back(mr_conv->MethodRegister(), kRawPointerSize);
334     dest_args.emplace_back(main_jni_conv->HiddenArgumentRegister(), kRawPointerSize);
335     refs.push_back(kInvalidReferenceOffset);
336   } else {
337     main_jni_conv->Next();    // Skip JNIEnv*.
338     FrameOffset method_offset(current_out_arg_size + mr_conv->MethodStackOffset().SizeValue());
339     if (main_jni_conv->IsCurrentParamOnStack()) {
340       // This is for x86 only. The method shall not be clobbered by argument moves
341       // because all arguments are passed on the stack to the native method.
342       check_method_not_clobbered = true;
343       DCHECK(callee_save_temp.IsNoRegister());
344     } else if (!is_static) {
345       // The method shall not be available in the `jclass` argument register.
346       // Make sure it is available in `callee_save_temp` for the call below.
347       // (The old method register can be clobbered by argument moves.)
348       DCHECK(!callee_save_temp.IsNoRegister());
349       ManagedRegister new_method_reg = __ CoreRegisterWithSize(callee_save_temp, kRawPointerSize);
350       DCHECK(!method_register.IsNoRegister());
351       __ Move(new_method_reg, method_register, kRawPointerSize);
352       method_register = new_method_reg;
353     }
354     if (is_static) {
355       // For static methods, move/load the method to the `jclass` argument.
356       DCHECK_EQ(ArtMethod::DeclaringClassOffset().SizeValue(), 0u);
357       if (method_register.IsNoRegister()) {
358         DCHECK(main_jni_conv->IsCurrentParamInRegister());
359         src_args.emplace_back(method_offset, kRawPointerSize);
360       } else {
361         src_args.emplace_back(method_register, kRawPointerSize);
362       }
363       if (main_jni_conv->IsCurrentParamInRegister()) {
364         // The `jclass` argument becomes the new method register needed for the call.
365         method_register = main_jni_conv->CurrentParamRegister();
366         dest_args.emplace_back(method_register, kRawPointerSize);
367       } else {
368         dest_args.emplace_back(main_jni_conv->CurrentParamStackOffset(), kRawPointerSize);
369       }
370       refs.push_back(kInvalidReferenceOffset);
371       main_jni_conv->Next();
372     }
373   }
374   // Move normal arguments to their locations.
375   for (; mr_conv->HasNext(); mr_conv->Next(), main_jni_conv->Next()) {
376     DCHECK(main_jni_conv->HasNext());
377     static_assert(kObjectReferenceSize == 4u);
378     bool is_reference = mr_conv->IsCurrentParamAReference();
379     size_t src_size = mr_conv->CurrentParamSize();
380     size_t dest_size = main_jni_conv->CurrentParamSize();
381     src_args.push_back(mr_conv->IsCurrentParamInRegister()
382         ? ArgumentLocation(mr_conv->CurrentParamRegister(), src_size)
383         : ArgumentLocation(mr_conv->CurrentParamStackOffset(), src_size));
384     dest_args.push_back(main_jni_conv->IsCurrentParamInRegister()
385         ? ArgumentLocation(main_jni_conv->CurrentParamRegister(), dest_size)
386         : ArgumentLocation(main_jni_conv->CurrentParamStackOffset(), dest_size));
387     refs.push_back(is_reference ? mr_conv->CurrentParamStackOffset() : kInvalidReferenceOffset);
388   }
389   DCHECK(!main_jni_conv->HasNext());
390   DCHECK_IMPLIES(check_method_not_clobbered,
391                  std::all_of(dest_args.begin(),
392                              dest_args.end(),
393                              [](const ArgumentLocation& loc) { return !loc.IsRegister(); }));
394   __ MoveArguments(ArrayRef<ArgumentLocation>(dest_args),
395                    ArrayRef<ArgumentLocation>(src_args),
396                    ArrayRef<FrameOffset>(refs));
397 
398   // 4.3. Create 1st argument, the JNI environment ptr.
399   if (LIKELY(!is_critical_native)) {
400     main_jni_conv->ResetIterator(FrameOffset(main_out_arg_size));
401     if (main_jni_conv->IsCurrentParamInRegister()) {
402       ManagedRegister jni_env_arg = main_jni_conv->CurrentParamRegister();
403       __ Move(jni_env_arg, jni_env_reg, kRawPointerSize);
404     } else {
405       FrameOffset jni_env_arg_offset = main_jni_conv->CurrentParamStackOffset();
406       __ Store(jni_env_arg_offset, jni_env_reg, kRawPointerSize);
407     }
408   }
409 
410   // 4.4. Plant call to native code associated with method.
411   MemberOffset jni_entrypoint_offset =
412       ArtMethod::EntryPointFromJniOffset(InstructionSetPointerSize(instruction_set));
413   if (UNLIKELY(is_critical_native)) {
414     if (main_jni_conv->UseTailCall()) {
415       __ Jump(main_jni_conv->HiddenArgumentRegister(), jni_entrypoint_offset);
416     } else {
417       __ Call(main_jni_conv->HiddenArgumentRegister(), jni_entrypoint_offset);
418     }
419   } else {
420     DCHECK(method_register.IsRegister());
421     __ Call(method_register, jni_entrypoint_offset);
422     // We shall not need the method register anymore. And we may clobber it below
423     // if it's the `callee_save_temp`, so clear it here to make sure it's not used.
424     method_register = ManagedRegister::NoRegister();
425   }
426 
427   // 4.5. Fix differences in result widths.
428   if (main_jni_conv->RequiresSmallResultTypeExtension()) {
429     DCHECK(main_jni_conv->HasSmallReturnType());
430     CHECK_IMPLIES(is_critical_native, !main_jni_conv->UseTailCall());
431     if (main_jni_conv->GetReturnType() == Primitive::kPrimByte ||
432         main_jni_conv->GetReturnType() == Primitive::kPrimShort) {
433       __ SignExtend(main_jni_conv->ReturnRegister(),
434                     Primitive::ComponentSize(main_jni_conv->GetReturnType()));
435     } else {
436       CHECK(main_jni_conv->GetReturnType() == Primitive::kPrimBoolean ||
437             main_jni_conv->GetReturnType() == Primitive::kPrimChar);
438       __ ZeroExtend(main_jni_conv->ReturnRegister(),
439                     Primitive::ComponentSize(main_jni_conv->GetReturnType()));
440     }
441   }
442 
443   // 4.6. Move the JNI return register into the managed return register (if they don't match).
444   if (main_jni_conv->SizeOfReturnValue() != 0) {
445     ManagedRegister jni_return_reg = main_jni_conv->ReturnRegister();
446     ManagedRegister mr_return_reg = mr_conv->ReturnRegister();
447 
448     // Check if the JNI return register matches the managed return register.
449     // If they differ, only then do we have to do anything about it.
450     // Otherwise the return value is already in the right place when we return.
451     if (!jni_return_reg.Equals(mr_return_reg)) {
452       CHECK_IMPLIES(is_critical_native, !main_jni_conv->UseTailCall());
453       // This is typically only necessary on ARM32 due to native being softfloat
454       // while managed is hardfloat.
455       // -- For example VMOV {r0, r1} -> D0; VMOV r0 -> S0.
456       __ Move(mr_return_reg, jni_return_reg, main_jni_conv->SizeOfReturnValue());
457     } else if (jni_return_reg.IsNoRegister() && mr_return_reg.IsNoRegister()) {
458       // Check that if the return value is passed on the stack for some reason,
459       // that the size matches.
460       CHECK_EQ(main_jni_conv->SizeOfReturnValue(), mr_conv->SizeOfReturnValue());
461     }
462   }
463 
464   // 5. Transition to Runnable (if normal native).
465 
466   // 5.1. Try transitioning to Runnable with a fast-path implementation.
467   //      If fast-path fails, make a slow-path call to `JniMethodEnd()`.
468   std::unique_ptr<JNIMacroLabel> transition_to_runnable_slow_path;
469   std::unique_ptr<JNIMacroLabel> transition_to_runnable_resume;
470   if (LIKELY(!is_critical_native && !is_fast_native)) {
471     transition_to_runnable_slow_path = __ CreateLabel();
472     transition_to_runnable_resume = __ CreateLabel();
473     __ TryToTransitionFromNativeToRunnable(transition_to_runnable_slow_path.get(),
474                                            main_jni_conv->ArgumentScratchRegisters(),
475                                            mr_conv->ReturnRegister());
476     __ Bind(transition_to_runnable_resume.get());
477   }
478 
479   // 5.2. For methods that return a reference, do an exception check before decoding the reference.
480   std::unique_ptr<JNIMacroLabel> exception_slow_path =
481       LIKELY(!is_critical_native) ? __ CreateLabel() : nullptr;
482   if (reference_return) {
483     DCHECK(!is_critical_native);
484     __ ExceptionPoll(exception_slow_path.get());
485   }
486 
487   // 5.3. For @FastNative that returns a reference, do an early suspend check so that we
488   //      do not need to encode the decoded reference in a stack map.
489   std::unique_ptr<JNIMacroLabel> suspend_check_slow_path =
490       UNLIKELY(is_fast_native) ? __ CreateLabel() : nullptr;
491   std::unique_ptr<JNIMacroLabel> suspend_check_resume =
492       UNLIKELY(is_fast_native) ? __ CreateLabel() : nullptr;
493   if (UNLIKELY(is_fast_native) && reference_return) {
494     __ SuspendCheck(suspend_check_slow_path.get());
495     __ Bind(suspend_check_resume.get());
496   }
497 
498   // 5.4 For methods with reference return, decode the `jobject`, either directly
499   //     or with a call to `JniDecodeReferenceResult()`.
500   std::unique_ptr<JNIMacroLabel> decode_reference_slow_path;
501   std::unique_ptr<JNIMacroLabel> decode_reference_resume;
502   if (reference_return) {
503     DCHECK(!is_critical_native);
504     if (inline_decode_reference) {
505       // Decode local and JNI transition references in the main path.
506       decode_reference_slow_path = __ CreateLabel();
507       decode_reference_resume = __ CreateLabel();
508       __ DecodeJNITransitionOrLocalJObject(mr_conv->ReturnRegister(),
509                                            decode_reference_slow_path.get(),
510                                            decode_reference_resume.get());
511       __ Bind(decode_reference_resume.get());
512     } else {
513       CallDecodeReferenceResult<kPointerSize>(
514           jni_asm.get(), main_jni_conv.get(), mr_conv->ReturnRegister(), main_out_arg_size);
515     }
516   }  // if (!is_critical_native)
517 
518   // 6. Pop local reference frame.
519   if (LIKELY(!is_critical_native)) {
520     __ StoreLocalReferenceTableStates(jni_env_reg, previous_state_reg, current_state_reg);
521     // For x86, the `callee_save_temp` is not valid, so let's simply change it to one
522     // of the callee save registers that we don't need anymore for all architectures.
523     callee_save_temp = current_state_reg;
524   }
525 
526   // 7. Return from the JNI stub.
527 
528   // 7.1. Move frame up now we're done with the out arg space.
529   //      @CriticalNative remove out args together with the frame in RemoveFrame().
530   if (LIKELY(!is_critical_native)) {
531     __ DecreaseFrameSize(current_out_arg_size);
532     current_frame_size -= current_out_arg_size;
533   }
534 
535   // 7.2 Unlock the synchronization object for synchronized methods.
536   //     Do this before exception poll to avoid extra unlocking in the exception slow path.
537   if (UNLIKELY(is_synchronized)) {
538     ManagedRegister to_lock = main_jni_conv->LockingArgumentRegister();
539     mr_conv->ResetIterator(FrameOffset(current_frame_size));
540     if (is_static) {
541       // Pass the declaring class.
542       DCHECK(method_register.IsNoRegister());  // TODO: Preserve the method in `callee_save_temp`.
543       ManagedRegister temp = __ CoreRegisterWithSize(callee_save_temp, kRawPointerSize);
544       FrameOffset method_offset = mr_conv->MethodStackOffset();
545       __ Load(temp, method_offset, kRawPointerSize);
546       DCHECK_EQ(ArtMethod::DeclaringClassOffset().SizeValue(), 0u);
547       __ LoadGcRootWithoutReadBarrier(to_lock, temp, MemberOffset(0u));
548     } else {
549       // Pass the `this` argument from its spill slot.
550       __ LoadStackReference(to_lock, mr_conv->CurrentParamStackOffset());
551     }
552     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniUnlockObject));
553   }
554 
555   // 7.3. Process pending exceptions from JNI call or monitor exit.
556   //      @CriticalNative methods do not need exception poll in the stub.
557   //      Methods with reference return emit the exception poll earlier.
558   if (LIKELY(!is_critical_native) && !reference_return) {
559     __ ExceptionPoll(exception_slow_path.get());
560   }
561 
562   // 7.4. For @FastNative, we never transitioned out of runnable, so there is no transition back.
563   //      Perform a suspend check if there is a flag raised, unless we have done that above
564   //      for reference return.
565   if (UNLIKELY(is_fast_native) && !reference_return) {
566     __ SuspendCheck(suspend_check_slow_path.get());
567     __ Bind(suspend_check_resume.get());
568   }
569 
570   // 7.5. Check if method exit hooks needs to be called
571   // For critical native methods, we don't JIT stubs in debuggable runtimes.
572   // TODO(mythria): Add support to call method entry / exit hooks for critical native methods too.
573   std::unique_ptr<JNIMacroLabel> method_exit_hook_slow_path;
574   std::unique_ptr<JNIMacroLabel> method_exit_hook_return;
575   if (UNLIKELY(needs_entry_exit_hooks)) {
576     uint64_t address = reinterpret_cast64<uint64_t>(Runtime::Current()->GetInstrumentation());
577     int offset = instrumentation::Instrumentation::RunExitHooksOffset().Int32Value();
578     method_exit_hook_slow_path = __ CreateLabel();
579     method_exit_hook_return = __ CreateLabel();
580     __ TestByteAndJumpIfNotZero(address + offset, method_exit_hook_slow_path.get());
581     __ Bind(method_exit_hook_return.get());
582   }
583 
584   // 7.6. Remove activation - need to restore callee save registers since the GC
585   //      may have changed them.
586   DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(current_frame_size));
587   if (LIKELY(!is_critical_native) || !main_jni_conv->UseTailCall()) {
588     // We expect the compiled method to possibly be suspended during its
589     // execution, except in the case of a CriticalNative method.
590     bool may_suspend = !is_critical_native;
591     __ RemoveFrame(current_frame_size, callee_save_regs, may_suspend);
592     DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(current_frame_size));
593   }
594 
595   // 8. Emit slow paths.
596 
597   // 8.1. Read barrier slow path for the declaring class in the method for a static call.
598   //      Skip this for @CriticalNative because we're not passing a `jclass` to the native method.
599   if (emit_read_barrier && is_static && !is_critical_native) {
600     __ Bind(jclass_read_barrier_slow_path.get());
601 
602     // Construct slow path for read barrier:
603     //
604     // For baker read barrier, do a fast check whether the class is already marked.
605     //
606     // Call into the runtime's `art_jni_read_barrier` and have it fix up
607     // the class address if it was moved.
608     //
609     // The entrypoint preserves the method register and argument registers.
610 
611     if (kUseBakerReadBarrier) {
612       // We enter the slow path with the method register unclobbered and callee-save
613       // registers already spilled, so we can use callee-save scratch registers.
614       method_register = mr_conv->MethodRegister();
615       ManagedRegister temp = __ CoreRegisterWithSize(
616           main_jni_conv->CalleeSaveScratchRegisters()[0], kObjectReferenceSize);
617       // Load the declaring class reference.
618       DCHECK_EQ(ArtMethod::DeclaringClassOffset().SizeValue(), 0u);
619       __ LoadGcRootWithoutReadBarrier(temp, method_register, MemberOffset(0u));
620       // Return to main path if the class object is marked.
621       __ TestMarkBit(temp, jclass_read_barrier_return.get(), JNIMacroUnaryCondition::kNotZero);
622     }
623 
624     ThreadOffset<kPointerSize> read_barrier = QUICK_ENTRYPOINT_OFFSET(kPointerSize,
625                                                                       pJniReadBarrier);
626     __ CallFromThread(read_barrier);
627 
628     // Return to main path.
629     __ Jump(jclass_read_barrier_return.get());
630   }
631 
632   // 8.2. Slow path for transition to Native.
633   if (LIKELY(!is_critical_native && !is_fast_native)) {
634     __ Bind(transition_to_native_slow_path.get());
635     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodStart));
636     __ Jump(transition_to_native_resume.get());
637   }
638 
639   // 8.3. Slow path for transition to Runnable.
640   if (LIKELY(!is_critical_native && !is_fast_native)) {
641     __ Bind(transition_to_runnable_slow_path.get());
642     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEnd));
643     __ Jump(transition_to_runnable_resume.get());
644   }
645 
646   // 8.4. Exception poll slow path(s).
647   if (LIKELY(!is_critical_native)) {
648     __ Bind(exception_slow_path.get());
649     if (reference_return) {
650       // We performed the exception check early, so we need to adjust SP and pop IRT frame.
651       if (main_out_arg_size != 0) {
652         jni_asm->cfi().AdjustCFAOffset(main_out_arg_size);
653         __ DecreaseFrameSize(main_out_arg_size);
654       }
655       __ StoreLocalReferenceTableStates(jni_env_reg, previous_state_reg, current_state_reg);
656     }
657     DCHECK_EQ(jni_asm->cfi().GetCurrentCFAOffset(), static_cast<int>(current_frame_size));
658     __ DeliverPendingException();
659   }
660 
661   // 8.5 Slow path for decoding the `jobject`.
662   if (reference_return && inline_decode_reference) {
663     __ Bind(decode_reference_slow_path.get());
664     if (main_out_arg_size != 0) {
665       jni_asm->cfi().AdjustCFAOffset(main_out_arg_size);
666     }
667     CallDecodeReferenceResult<kPointerSize>(
668         jni_asm.get(), main_jni_conv.get(), mr_conv->ReturnRegister(), main_out_arg_size);
669     __ Jump(decode_reference_resume.get());
670     if (main_out_arg_size != 0) {
671       jni_asm->cfi().AdjustCFAOffset(-main_out_arg_size);
672     }
673   }
674 
675   // 8.6. Suspend check slow path.
676   if (UNLIKELY(is_fast_native)) {
677     __ Bind(suspend_check_slow_path.get());
678     if (reference_return && main_out_arg_size != 0) {
679       jni_asm->cfi().AdjustCFAOffset(main_out_arg_size);
680       __ DecreaseFrameSize(main_out_arg_size);
681     }
682     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pTestSuspend));
683     if (reference_return) {
684       // Suspend check entry point overwrites top of managed stack and leaves it clobbered.
685       // We need to restore the top for subsequent runtime call to `JniDecodeReferenceResult()`.
686       __ StoreStackPointerToThread(Thread::TopOfManagedStackOffset<kPointerSize>(), should_tag_sp);
687     }
688     if (reference_return && main_out_arg_size != 0) {
689       __ IncreaseFrameSize(main_out_arg_size);
690     }
691     __ Jump(suspend_check_resume.get());
692     if (reference_return && main_out_arg_size != 0) {
693       jni_asm->cfi().AdjustCFAOffset(-main_out_arg_size);
694     }
695   }
696 
697   // 8.7. Method entry / exit hooks slow paths.
698   if (UNLIKELY(needs_entry_exit_hooks)) {
699     __ Bind(method_entry_hook_slow_path.get());
700     // Use Jni specific method entry hook that saves all the arguments. We have only saved the
701     // callee save registers at this point. So go through Jni specific stub that saves the rest
702     // of the live registers.
703     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniMethodEntryHook));
704     __ ExceptionPoll(exception_slow_path.get());
705     __ Jump(method_entry_hook_return.get());
706 
707     __ Bind(method_exit_hook_slow_path.get());
708     // Method exit hooks is called just before tearing down the frame. So there are no live
709     // registers and we can directly call the method exit hook and don't need a Jni specific
710     // entrypoint.
711     __ Move(mr_conv->ArgumentRegisterForMethodExitHook(), managed_frame_size);
712     __ CallFromThread(QUICK_ENTRYPOINT_OFFSET(kPointerSize, pMethodExitHook));
713     __ Jump(method_exit_hook_return.get());
714   }
715 
716   // 9. Finalize code generation.
717   __ FinalizeCode();
718   size_t cs = __ CodeSize();
719   std::vector<uint8_t> managed_code(cs);
720   MemoryRegion code(&managed_code[0], managed_code.size());
721   __ CopyInstructions(code);
722 
723   return JniCompiledMethod(instruction_set,
724                            std::move(managed_code),
725                            managed_frame_size,
726                            main_jni_conv->CoreSpillMask(),
727                            main_jni_conv->FpSpillMask(),
728                            ArrayRef<const uint8_t>(*jni_asm->cfi().data()));
729 }
730 
731 template <PointerSize kPointerSize>
SetNativeParameter(JNIMacroAssembler<kPointerSize> * jni_asm,JniCallingConvention * jni_conv,ManagedRegister in_reg)732 static void SetNativeParameter(JNIMacroAssembler<kPointerSize>* jni_asm,
733                                JniCallingConvention* jni_conv,
734                                ManagedRegister in_reg) {
735   if (jni_conv->IsCurrentParamOnStack()) {
736     FrameOffset dest = jni_conv->CurrentParamStackOffset();
737     __ StoreRawPtr(dest, in_reg);
738   } else {
739     if (!jni_conv->CurrentParamRegister().Equals(in_reg)) {
740       __ Move(jni_conv->CurrentParamRegister(), in_reg, jni_conv->CurrentParamSize());
741     }
742   }
743 }
744 
745 template <PointerSize kPointerSize>
CallDecodeReferenceResult(JNIMacroAssembler<kPointerSize> * jni_asm,JniCallingConvention * jni_conv,ManagedRegister mr_return_reg,size_t main_out_arg_size)746 static void CallDecodeReferenceResult(JNIMacroAssembler<kPointerSize>* jni_asm,
747                                       JniCallingConvention* jni_conv,
748                                       ManagedRegister mr_return_reg,
749                                       size_t main_out_arg_size) {
750   // We abuse the JNI calling convention here, that is guaranteed to support passing
751   // two pointer arguments, `JNIEnv*` and `jclass`/`jobject`.
752   jni_conv->ResetIterator(FrameOffset(main_out_arg_size));
753   ThreadOffset<kPointerSize> jni_decode_reference_result =
754       QUICK_ENTRYPOINT_OFFSET(kPointerSize, pJniDecodeReferenceResult);
755   // Pass result.
756   SetNativeParameter(jni_asm, jni_conv, mr_return_reg);
757   jni_conv->Next();
758   if (jni_conv->IsCurrentParamInRegister()) {
759     __ GetCurrentThread(jni_conv->CurrentParamRegister());
760     __ Call(jni_conv->CurrentParamRegister(), Offset(jni_decode_reference_result));
761   } else {
762     __ GetCurrentThread(jni_conv->CurrentParamStackOffset());
763     __ CallFromThread(jni_decode_reference_result);
764   }
765   // Note: If the native ABI returns the pointer in a register different from
766   // `mr_return_register`, the `JniDecodeReferenceResult` entrypoint must be
767   // a stub that moves the result to `mr_return_register`.
768 }
769 
ArtQuickJniCompileMethod(const CompilerOptions & compiler_options,std::string_view shorty,uint32_t access_flags,ArenaAllocator * allocator)770 JniCompiledMethod ArtQuickJniCompileMethod(const CompilerOptions& compiler_options,
771                                            std::string_view shorty,
772                                            uint32_t access_flags,
773                                            ArenaAllocator* allocator) {
774   if (Is64BitInstructionSet(compiler_options.GetInstructionSet())) {
775     return ArtJniCompileMethodInternal<PointerSize::k64>(
776         compiler_options, shorty, access_flags, allocator);
777   } else {
778     return ArtJniCompileMethodInternal<PointerSize::k32>(
779         compiler_options, shorty, access_flags, allocator);
780   }
781 }
782 
783 }  // namespace art
784