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