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