xref: /aosp_15_r20/art/runtime/entrypoints/jni/jni_entrypoints.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1 /*
2  * Copyright (C) 2012 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 <android-base/logging.h>
18 
19 #include "arch/arm/jni_frame_arm.h"
20 #include "arch/arm64/jni_frame_arm64.h"
21 #include "arch/instruction_set.h"
22 #include "arch/riscv64/jni_frame_riscv64.h"
23 #include "arch/x86/jni_frame_x86.h"
24 #include "arch/x86_64/jni_frame_x86_64.h"
25 #include "art_method-inl.h"
26 #include "dex/dex_instruction-inl.h"
27 #include "dex/method_reference.h"
28 #include "entrypoints/entrypoint_utils-inl.h"
29 #include "jni/java_vm_ext.h"
30 #include "mirror/object-inl.h"
31 #include "oat/oat_quick_method_header.h"
32 #include "oat/stack_map.h"
33 #include "scoped_thread_state_change-inl.h"
34 #include "thread.h"
35 
36 namespace art HIDDEN {
37 
GetInvokeStaticMethodIndex(ArtMethod * caller,uint32_t dex_pc)38 static inline uint32_t GetInvokeStaticMethodIndex(ArtMethod* caller, uint32_t dex_pc)
39     REQUIRES_SHARED(Locks::mutator_lock_) {
40   // Get the DexFile and method index.
41   const Instruction& instruction = caller->DexInstructions().InstructionAt(dex_pc);
42   DCHECK(instruction.Opcode() == Instruction::INVOKE_STATIC ||
43          instruction.Opcode() == Instruction::INVOKE_STATIC_RANGE);
44   uint32_t method_idx = (instruction.Opcode() == Instruction::INVOKE_STATIC)
45       ? instruction.VRegB_35c()
46       : instruction.VRegB_3rc();
47   return method_idx;
48 }
49 
50 // Used by the JNI dlsym stub to find the native method to invoke if none is registered.
artFindNativeMethodRunnable(Thread * self)51 extern "C" const void* artFindNativeMethodRunnable(Thread* self)
52     REQUIRES_SHARED(Locks::mutator_lock_) {
53   Locks::mutator_lock_->AssertSharedHeld(self);  // We come here as Runnable.
54   uint32_t dex_pc;
55   ArtMethod* method = self->GetCurrentMethod(&dex_pc);
56   DCHECK(method != nullptr);
57   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
58 
59   if (!method->IsNative()) {
60     // We're coming from compiled managed code and the `method` we see here is the caller.
61     // Resolve target @CriticalNative method for a direct call from compiled managed code.
62     uint32_t method_idx = GetInvokeStaticMethodIndex(method, dex_pc);
63     ArtMethod* target_method = class_linker->ResolveMethodId(method_idx, method);
64     if (target_method == nullptr) {
65       self->AssertPendingException();
66       return nullptr;
67     }
68     DCHECK(target_method->IsCriticalNative());
69     // Note that the BSS also contains entries used for super calls. Given we
70     // only deal with invokestatic in this code path, we don't need to adjust
71     // the method index.
72     MaybeUpdateBssMethodEntry(target_method,
73                               MethodReference(method->GetDexFile(), method_idx),
74                               GetCalleeSaveOuterMethod(self, CalleeSaveType::kSaveRefsAndArgs));
75 
76     // These calls do not have an explicit class initialization check, so do the check now.
77     // (When going through the stub or GenericJNI, the check was already done.)
78     DCHECK(target_method->NeedsClinitCheckBeforeCall());
79     ObjPtr<mirror::Class> declaring_class = target_method->GetDeclaringClass();
80     if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
81       StackHandleScope<1> hs(self);
82       Handle<mirror::Class> h_class(hs.NewHandle(declaring_class));
83       if (!class_linker->EnsureInitialized(self, h_class, true, true)) {
84         DCHECK(self->IsExceptionPending()) << method->PrettyMethod();
85         return nullptr;
86       }
87     }
88 
89     // Replace the runtime method on the stack with the target method.
90     DCHECK(!self->GetManagedStack()->GetTopQuickFrameGenericJniTag());
91     ArtMethod** sp = self->GetManagedStack()->GetTopQuickFrameKnownNotTagged();
92     DCHECK(*sp == Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
93     *sp = target_method;
94     self->SetTopOfStackGenericJniTagged(sp);  // Fake GenericJNI frame.
95 
96     // Continue with the target method.
97     method = target_method;
98   }
99   DCHECK(method == self->GetCurrentMethod(/*dex_pc=*/ nullptr));
100 
101   // Check whether we already have a registered native code.
102   // For @CriticalNative it may not be stored in the ArtMethod as a JNI entrypoint if the class
103   // was not visibly initialized yet. Do this check also for @FastNative and normal native for
104   // consistency; though success would mean that another thread raced to do this lookup.
105   const void* native_code = class_linker->GetRegisteredNative(self, method);
106   if (native_code != nullptr) {
107     return native_code;
108   }
109 
110   // Lookup symbol address for method, on failure we'll return null with an exception set,
111   // otherwise we return the address of the method we found.
112   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
113   std::string error_msg;
114   native_code = vm->FindCodeForNativeMethod(method, &error_msg, /*can_suspend=*/ true);
115   if (native_code == nullptr) {
116     LOG(ERROR) << error_msg;
117     self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", error_msg.c_str());
118     return nullptr;
119   }
120 
121   // Register the code. This usually prevents future calls from coming to this function again.
122   // We can still come here if the ClassLinker cannot set the entrypoint in the ArtMethod,
123   // i.e. for @CriticalNative methods with the declaring class not visibly initialized.
124   return class_linker->RegisterNative(self, method, native_code);
125 }
126 
127 // Used by the JNI dlsym stub to find the native method to invoke if none is registered.
artFindNativeMethod(Thread * self)128 extern "C" const void* artFindNativeMethod(Thread* self) {
129   DCHECK_EQ(self, Thread::Current());
130   Locks::mutator_lock_->AssertNotHeld(self);  // We come here as Native.
131   ScopedObjectAccess soa(self);
132   return artFindNativeMethodRunnable(self);
133 }
134 
artCriticalNativeFrameSize(ArtMethod * method,uintptr_t caller_pc)135 extern "C" size_t artCriticalNativeFrameSize(ArtMethod* method, uintptr_t caller_pc)
136     REQUIRES_SHARED(Locks::mutator_lock_)  {
137   if (method->IsNative()) {
138     // Get the method's shorty.
139     DCHECK(method->IsCriticalNative());
140     std::string_view shorty = method->GetShortyView();
141 
142     // Return the platform-dependent stub frame size.
143     switch (kRuntimeISA) {
144       case InstructionSet::kArm:
145       case InstructionSet::kThumb2:
146         return arm::GetCriticalNativeStubFrameSize(shorty);
147       case InstructionSet::kArm64:
148         return arm64::GetCriticalNativeStubFrameSize(shorty);
149       case InstructionSet::kRiscv64:
150         return riscv64::GetCriticalNativeStubFrameSize(shorty);
151       case InstructionSet::kX86:
152         return x86::GetCriticalNativeStubFrameSize(shorty);
153       case InstructionSet::kX86_64:
154         return x86_64::GetCriticalNativeStubFrameSize(shorty);
155       default:
156         UNIMPLEMENTED(FATAL) << kRuntimeISA;
157         UNREACHABLE();
158     }
159   } else {
160     // We're coming from compiled managed code and the `method` we see here is the compiled
161     // method that made the call. Get the actual caller (may be inlined) and dex pc.
162     const OatQuickMethodHeader* current_code = method->GetOatQuickMethodHeader(caller_pc);
163     DCHECK(current_code != nullptr);
164     DCHECK(current_code->IsOptimized());
165     uintptr_t native_pc_offset = current_code->NativeQuickPcOffset(caller_pc);
166     CodeInfo code_info = CodeInfo::DecodeInlineInfoOnly(current_code);
167     StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
168     DCHECK(stack_map.IsValid());
169     BitTableRange<InlineInfo> inline_infos = code_info.GetInlineInfosOf(stack_map);
170     ArtMethod* caller =
171         inline_infos.empty() ? method : GetResolvedMethod(method, code_info, inline_infos);
172     uint32_t dex_pc = inline_infos.empty() ? stack_map.GetDexPc() : inline_infos.back().GetDexPc();
173 
174     // Get the callee shorty.
175     const DexFile* dex_file = caller->GetDexFile();
176     uint32_t method_idx = GetInvokeStaticMethodIndex(caller, dex_pc);
177     std::string_view shorty = dex_file->GetMethodShortyView(method_idx);
178 
179     // Return the platform-dependent direct call frame size.
180     switch (kRuntimeISA) {
181       case InstructionSet::kArm:
182       case InstructionSet::kThumb2:
183         return arm::GetCriticalNativeDirectCallFrameSize(shorty);
184       case InstructionSet::kArm64:
185         return arm64::GetCriticalNativeDirectCallFrameSize(shorty);
186       case InstructionSet::kRiscv64:
187         return riscv64::GetCriticalNativeDirectCallFrameSize(shorty);
188       case InstructionSet::kX86:
189         return x86::GetCriticalNativeDirectCallFrameSize(shorty);
190       case InstructionSet::kX86_64:
191         return x86_64::GetCriticalNativeDirectCallFrameSize(shorty);
192       default:
193         UNIMPLEMENTED(FATAL) << kRuntimeISA;
194         UNREACHABLE();
195     }
196   }
197 }
198 
199 }  // namespace art
200