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