xref: /aosp_15_r20/art/runtime/art_method.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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 "art_method.h"
18 
19 #include <algorithm>
20 #include <cstddef>
21 
22 #include "android-base/stringprintf.h"
23 
24 #include "arch/context.h"
25 #include "art_method-inl.h"
26 #include "base/pointer_size.h"
27 #include "base/stl_util.h"
28 #include "class_linker-inl.h"
29 #include "class_root-inl.h"
30 #include "debugger.h"
31 #include "dex/class_accessor-inl.h"
32 #include "dex/descriptors_names.h"
33 #include "dex/dex_file-inl.h"
34 #include "dex/dex_file_exception_helpers.h"
35 #include "dex/dex_instruction.h"
36 #include "dex/signature-inl.h"
37 #include "entrypoints/runtime_asm_entrypoints.h"
38 #include "gc/accounting/card_table-inl.h"
39 #include "hidden_api.h"
40 #include "interpreter/interpreter.h"
41 #include "intrinsics_enum.h"
42 #include "jit/jit.h"
43 #include "jit/jit_code_cache.h"
44 #include "jit/profiling_info.h"
45 #include "jni/jni_internal.h"
46 #include "mirror/class-inl.h"
47 #include "mirror/class_ext-inl.h"
48 #include "mirror/executable.h"
49 #include "mirror/object-inl.h"
50 #include "mirror/object_array-inl.h"
51 #include "mirror/string.h"
52 #include "oat/oat_file-inl.h"
53 #include "runtime_callbacks.h"
54 #include "scoped_thread_state_change-inl.h"
55 #include "vdex_file.h"
56 
57 namespace art HIDDEN {
58 
59 using android::base::StringPrintf;
60 
61 extern "C" void art_quick_invoke_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
62                                       const char*);
63 extern "C" void art_quick_invoke_static_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
64                                              const char*);
65 
66 // Enforce that we have the right index for runtime methods.
67 static_assert(ArtMethod::kRuntimeMethodDexMethodIndex == dex::kDexNoIndex,
68               "Wrong runtime-method dex method index");
69 
GetCanonicalMethod(PointerSize pointer_size)70 ArtMethod* ArtMethod::GetCanonicalMethod(PointerSize pointer_size) {
71   if (LIKELY(!IsCopied())) {
72     return this;
73   } else {
74     ObjPtr<mirror::Class> declaring_class = GetDeclaringClass();
75     DCHECK(declaring_class->IsInterface());
76     ArtMethod* ret = declaring_class->FindInterfaceMethod(GetDexCache(),
77                                                           GetDexMethodIndex(),
78                                                           pointer_size);
79     DCHECK(ret != nullptr);
80     return ret;
81   }
82 }
83 
GetNonObsoleteMethod()84 ArtMethod* ArtMethod::GetNonObsoleteMethod() {
85   if (LIKELY(!IsObsolete())) {
86     return this;
87   }
88   DCHECK_EQ(kRuntimePointerSize, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
89   if (IsDirect()) {
90     return &GetDeclaringClass()->GetDirectMethodsSlice(kRuntimePointerSize)[GetMethodIndex()];
91   } else {
92     return GetDeclaringClass()->GetVTableEntry(GetMethodIndex(), kRuntimePointerSize);
93   }
94 }
95 
GetSingleImplementation(PointerSize pointer_size)96 ArtMethod* ArtMethod::GetSingleImplementation(PointerSize pointer_size) {
97   if (IsInvokable()) {
98     // An invokable method single implementation is itself.
99     return this;
100   }
101   DCHECK(!IsDefaultConflicting());
102   ArtMethod* m = reinterpret_cast<ArtMethod*>(GetDataPtrSize(pointer_size));
103   CHECK(m == nullptr || !m->IsDefaultConflicting());
104   return m;
105 }
106 
FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable & soa,jobject jlr_method)107 ArtMethod* ArtMethod::FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable& soa,
108                                           jobject jlr_method) {
109   ObjPtr<mirror::Executable> executable = soa.Decode<mirror::Executable>(jlr_method);
110   DCHECK(executable != nullptr);
111   return executable->GetArtMethod();
112 }
113 
114 template <ReadBarrierOption kReadBarrierOption>
GetObsoleteDexCache()115 ObjPtr<mirror::DexCache> ArtMethod::GetObsoleteDexCache() {
116   // Note: The class redefinition happens with GC disabled, so at the point where we
117   // create obsolete methods, the `ClassExt` and its obsolete methods and dex caches
118   // members are reachable without a read barrier. If we start a GC later, and we
119   // look at these objects without read barriers (`kWithoutReadBarrier`), the method
120   // pointers shall be the same in from-space array as in to-space array (if these
121   // arrays are different) and the dex cache array entry can point to from-space or
122   // to-space `DexCache` but either is a valid result for `kWithoutReadBarrier`.
123   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
124   std::optional<ScopedDebugDisallowReadBarriers> sddrb(std::nullopt);
125   if (kIsDebugBuild && kReadBarrierOption == kWithoutReadBarrier) {
126     sddrb.emplace(Thread::Current());
127   }
128   PointerSize pointer_size = kRuntimePointerSize;
129   DCHECK(!Runtime::Current()->IsAotCompiler()) << PrettyMethod();
130   DCHECK(IsObsolete());
131   ObjPtr<mirror::Class> declaring_class = GetDeclaringClass<kReadBarrierOption>();
132   ObjPtr<mirror::ClassExt> ext =
133       declaring_class->GetExtData<kDefaultVerifyFlags, kReadBarrierOption>();
134   ObjPtr<mirror::PointerArray> obsolete_methods(
135       ext.IsNull() ? nullptr : ext->GetObsoleteMethods<kDefaultVerifyFlags, kReadBarrierOption>());
136   int32_t len = 0;
137   ObjPtr<mirror::ObjectArray<mirror::DexCache>> obsolete_dex_caches = nullptr;
138   if (!obsolete_methods.IsNull()) {
139     len = obsolete_methods->GetLength();
140     obsolete_dex_caches = ext->GetObsoleteDexCaches<kDefaultVerifyFlags, kReadBarrierOption>();
141     // FIXME: `ClassExt::SetObsoleteArrays()` is not atomic, so one of the arrays we see here
142     // could be extended for a new class redefinition while the other may be shorter.
143     // Furthermore, there is no synchronization to ensure that copied contents of an old
144     // obsolete array are visible to a thread reading the new array.
145     DCHECK_EQ(len, obsolete_dex_caches->GetLength())
146         << " ext->GetObsoleteDexCaches()=" << obsolete_dex_caches;
147   }
148   // Using kRuntimePointerSize (instead of using the image's pointer size) is fine since images
149   // should never have obsolete methods in them so they should always be the same.
150   DCHECK_EQ(pointer_size, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
151   for (int32_t i = 0; i < len; i++) {
152     if (this == obsolete_methods->GetElementPtrSize<ArtMethod*>(i, pointer_size)) {
153       return obsolete_dex_caches->GetWithoutChecks<kDefaultVerifyFlags, kReadBarrierOption>(i);
154     }
155   }
156   CHECK(declaring_class->IsObsoleteObject())
157       << "This non-structurally obsolete method does not appear in the obsolete map of its class: "
158       << declaring_class->PrettyClass() << " Searched " << len << " caches.";
159   CHECK_EQ(this,
160            std::clamp(this,
161                       &(*declaring_class->GetMethods(pointer_size).begin()),
162                       &(*declaring_class->GetMethods(pointer_size).end())))
163       << "class is marked as structurally obsolete method but not found in normal obsolete-map "
164       << "despite not being the original method pointer for " << GetDeclaringClass()->PrettyClass();
165   return declaring_class->template GetDexCache<kDefaultVerifyFlags, kReadBarrierOption>();
166 }
167 
168 template ObjPtr<mirror::DexCache> ArtMethod::GetObsoleteDexCache<kWithReadBarrier>();
169 template ObjPtr<mirror::DexCache> ArtMethod::GetObsoleteDexCache<kWithoutReadBarrier>();
170 
FindObsoleteDexClassDefIndex()171 uint16_t ArtMethod::FindObsoleteDexClassDefIndex() {
172   DCHECK(!Runtime::Current()->IsAotCompiler()) << PrettyMethod();
173   DCHECK(IsObsolete());
174   const DexFile* dex_file = GetDexFile();
175   const dex::TypeIndex declaring_class_type = dex_file->GetMethodId(GetDexMethodIndex()).class_idx_;
176   const dex::ClassDef* class_def = dex_file->FindClassDef(declaring_class_type);
177   CHECK(class_def != nullptr);
178   return dex_file->GetIndexForClassDef(*class_def);
179 }
180 
ThrowInvocationTimeError(ObjPtr<mirror::Object> receiver)181 void ArtMethod::ThrowInvocationTimeError(ObjPtr<mirror::Object> receiver) {
182   DCHECK(!IsInvokable());
183   if (IsDefaultConflicting()) {
184     ThrowIncompatibleClassChangeErrorForMethodConflict(this);
185   } else if (GetDeclaringClass()->IsInterface() && receiver != nullptr) {
186     // If this was an interface call, check whether there is a method in the
187     // superclass chain that isn't public. In this situation, we should throw an
188     // IllegalAccessError.
189     DCHECK(IsAbstract());
190     ObjPtr<mirror::Class> current = receiver->GetClass();
191     std::string_view name = GetNameView();
192     Signature signature = GetSignature();
193     while (current != nullptr) {
194       for (ArtMethod& method : current->GetDeclaredMethodsSlice(kRuntimePointerSize)) {
195         ArtMethod* np_method = method.GetInterfaceMethodIfProxy(kRuntimePointerSize);
196         if (!np_method->IsStatic() &&
197             np_method->GetNameView() == name &&
198             np_method->GetSignature() == signature) {
199           if (!np_method->IsPublic()) {
200             ThrowIllegalAccessErrorForImplementingMethod(receiver->GetClass(), np_method, this);
201             return;
202           } else if (np_method->IsAbstract()) {
203             ThrowAbstractMethodError(this);
204             return;
205           }
206         }
207       }
208       current = current->GetSuperClass();
209     }
210     ThrowAbstractMethodError(this);
211   } else {
212     DCHECK(IsAbstract());
213     ThrowAbstractMethodError(this);
214   }
215 }
216 
GetInvokeType()217 InvokeType ArtMethod::GetInvokeType() {
218   // TODO: kSuper?
219   if (IsStatic()) {
220     return kStatic;
221   } else if (GetDeclaringClass()->IsInterface()) {
222     return kInterface;
223   } else if (IsDirect()) {
224     return kDirect;
225   } else if (IsSignaturePolymorphic()) {
226     return kPolymorphic;
227   } else {
228     return kVirtual;
229   }
230 }
231 
NumArgRegisters(std::string_view shorty)232 size_t ArtMethod::NumArgRegisters(std::string_view shorty) {
233   CHECK(!shorty.empty());
234   uint32_t num_registers = 0;
235   for (char c : shorty.substr(1u)) {
236     if (c == 'D' || c == 'J') {
237       num_registers += 2;
238     } else {
239       num_registers += 1;
240     }
241   }
242   return num_registers;
243 }
244 
HasSameNameAndSignature(ArtMethod * other)245 bool ArtMethod::HasSameNameAndSignature(ArtMethod* other) {
246   ScopedAssertNoThreadSuspension ants("HasSameNameAndSignature");
247   const DexFile* dex_file = GetDexFile();
248   const dex::MethodId& mid = dex_file->GetMethodId(GetDexMethodIndex());
249   if (GetDexCache() == other->GetDexCache()) {
250     const dex::MethodId& mid2 = dex_file->GetMethodId(other->GetDexMethodIndex());
251     return mid.name_idx_ == mid2.name_idx_ && mid.proto_idx_ == mid2.proto_idx_;
252   }
253   const DexFile* dex_file2 = other->GetDexFile();
254   const dex::MethodId& mid2 = dex_file2->GetMethodId(other->GetDexMethodIndex());
255   if (!DexFile::StringEquals(dex_file, mid.name_idx_, dex_file2, mid2.name_idx_)) {
256     return false;  // Name mismatch.
257   }
258   return dex_file->GetMethodSignature(mid) == dex_file2->GetMethodSignature(mid2);
259 }
260 
FindOverriddenMethod(PointerSize pointer_size)261 ArtMethod* ArtMethod::FindOverriddenMethod(PointerSize pointer_size) {
262   if (IsStatic()) {
263     return nullptr;
264   }
265   ObjPtr<mirror::Class> declaring_class = GetDeclaringClass();
266   ObjPtr<mirror::Class> super_class = declaring_class->GetSuperClass();
267   uint16_t method_index = GetMethodIndex();
268   ArtMethod* result = nullptr;
269   // Did this method override a super class method? If so load the result from the super class'
270   // vtable
271   if (super_class->HasVTable() && method_index < super_class->GetVTableLength()) {
272     result = super_class->GetVTableEntry(method_index, pointer_size);
273   } else {
274     // Method didn't override superclass method so search interfaces
275     if (IsProxyMethod()) {
276       result = GetInterfaceMethodIfProxy(pointer_size);
277       DCHECK(result != nullptr);
278     } else {
279       ObjPtr<mirror::IfTable> iftable = GetDeclaringClass()->GetIfTable();
280       for (size_t i = 0; i < iftable->Count() && result == nullptr; i++) {
281         ObjPtr<mirror::Class> interface = iftable->GetInterface(i);
282         for (ArtMethod& interface_method : interface->GetVirtualMethods(pointer_size)) {
283           if (HasSameNameAndSignature(interface_method.GetInterfaceMethodIfProxy(pointer_size))) {
284             result = &interface_method;
285             break;
286           }
287         }
288       }
289     }
290   }
291   DCHECK(result == nullptr ||
292          GetInterfaceMethodIfProxy(pointer_size)->HasSameNameAndSignature(
293              result->GetInterfaceMethodIfProxy(pointer_size)));
294   return result;
295 }
296 
FindDexMethodIndexInOtherDexFile(const DexFile & other_dexfile,uint32_t name_and_signature_idx)297 uint32_t ArtMethod::FindDexMethodIndexInOtherDexFile(const DexFile& other_dexfile,
298                                                      uint32_t name_and_signature_idx) {
299   const DexFile* dexfile = GetDexFile();
300   const uint32_t dex_method_idx = GetDexMethodIndex();
301   const dex::MethodId& mid = dexfile->GetMethodId(dex_method_idx);
302   const dex::MethodId& name_and_sig_mid = other_dexfile.GetMethodId(name_and_signature_idx);
303   DCHECK_STREQ(dexfile->GetMethodName(mid), other_dexfile.GetMethodName(name_and_sig_mid));
304   DCHECK_EQ(dexfile->GetMethodSignature(mid), other_dexfile.GetMethodSignature(name_and_sig_mid));
305   if (dexfile == &other_dexfile) {
306     return dex_method_idx;
307   }
308   std::string_view mid_declaring_class_descriptor = dexfile->GetTypeDescriptorView(mid.class_idx_);
309   const dex::TypeId* other_type_id = other_dexfile.FindTypeId(mid_declaring_class_descriptor);
310   if (other_type_id != nullptr) {
311     const dex::MethodId* other_mid = other_dexfile.FindMethodId(
312         *other_type_id, other_dexfile.GetStringId(name_and_sig_mid.name_idx_),
313         other_dexfile.GetProtoId(name_and_sig_mid.proto_idx_));
314     if (other_mid != nullptr) {
315       return other_dexfile.GetIndexForMethodId(*other_mid);
316     }
317   }
318   return dex::kDexNoIndex;
319 }
320 
FindCatchBlock(Handle<mirror::Class> exception_type,uint32_t dex_pc,bool * has_no_move_exception)321 uint32_t ArtMethod::FindCatchBlock(Handle<mirror::Class> exception_type,
322                                    uint32_t dex_pc, bool* has_no_move_exception) {
323   // Set aside the exception while we resolve its type.
324   Thread* self = Thread::Current();
325   StackHandleScope<1> hs(self);
326   Handle<mirror::Throwable> exception(hs.NewHandle(self->GetException()));
327   self->ClearException();
328   // Default to handler not found.
329   uint32_t found_dex_pc = dex::kDexNoIndex;
330   // Iterate over the catch handlers associated with dex_pc.
331   CodeItemDataAccessor accessor(DexInstructionData());
332   for (CatchHandlerIterator it(accessor, dex_pc); it.HasNext(); it.Next()) {
333     dex::TypeIndex iter_type_idx = it.GetHandlerTypeIndex();
334     // Catch all case
335     if (!iter_type_idx.IsValid()) {
336       found_dex_pc = it.GetHandlerAddress();
337       break;
338     }
339     // Does this catch exception type apply?
340     ObjPtr<mirror::Class> iter_exception_type = ResolveClassFromTypeIndex(iter_type_idx);
341     if (UNLIKELY(iter_exception_type == nullptr)) {
342       // Now have a NoClassDefFoundError as exception. Ignore in case the exception class was
343       // removed by a pro-guard like tool.
344       // Note: this is not RI behavior. RI would have failed when loading the class.
345       self->ClearException();
346       LOG(WARNING) << "Unresolved exception class when finding catch block: "
347         << DescriptorToDot(GetTypeDescriptorFromTypeIdx(iter_type_idx));
348     } else if (iter_exception_type->IsAssignableFrom(exception_type.Get())) {
349       found_dex_pc = it.GetHandlerAddress();
350       break;
351     }
352   }
353   if (found_dex_pc != dex::kDexNoIndex) {
354     const Instruction& first_catch_instr = accessor.InstructionAt(found_dex_pc);
355     *has_no_move_exception = (first_catch_instr.Opcode() != Instruction::MOVE_EXCEPTION);
356   }
357   // Put the exception back.
358   if (exception != nullptr) {
359     self->SetException(exception.Get());
360   }
361   return found_dex_pc;
362 }
363 
364 NO_STACK_PROTECTOR
Invoke(Thread * self,uint32_t * args,uint32_t args_size,JValue * result,const char * shorty)365 void ArtMethod::Invoke(Thread* self, uint32_t* args, uint32_t args_size, JValue* result,
366                        const char* shorty) {
367   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEnd<kNativeStackType>())) {
368     ThrowStackOverflowError<kNativeStackType>(self);
369     return;
370   }
371 
372   if (kIsDebugBuild) {
373     self->AssertThreadSuspensionIsAllowable();
374     CHECK_EQ(ThreadState::kRunnable, self->GetState());
375     CHECK_STREQ(GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(), shorty);
376   }
377 
378   // Push a transition back into managed code onto the linked list in thread.
379   ManagedStack fragment;
380   self->PushManagedStackFragment(&fragment);
381 
382   Runtime* runtime = Runtime::Current();
383   // Call the invoke stub, passing everything as arguments.
384   // If the runtime is not yet started or it is required by the debugger, then perform the
385   // Invocation by the interpreter, explicitly forcing interpretation over JIT to prevent
386   // cycling around the various JIT/Interpreter methods that handle method invocation.
387   if (UNLIKELY(!runtime->IsStarted() ||
388                (self->IsForceInterpreter() && !IsNative() && !IsProxyMethod() && IsInvokable()))) {
389     if (IsStatic()) {
390       art::interpreter::EnterInterpreterFromInvoke(
391           self, this, nullptr, args, result, /*stay_in_interpreter=*/ true);
392     } else {
393       mirror::Object* receiver =
394           reinterpret_cast<StackReference<mirror::Object>*>(&args[0])->AsMirrorPtr();
395       art::interpreter::EnterInterpreterFromInvoke(
396           self, this, receiver, args + 1, result, /*stay_in_interpreter=*/ true);
397     }
398   } else {
399     DCHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
400 
401     constexpr bool kLogInvocationStartAndReturn = false;
402     bool have_quick_code = GetEntryPointFromQuickCompiledCode() != nullptr;
403     if (LIKELY(have_quick_code)) {
404       if (kLogInvocationStartAndReturn) {
405         LOG(INFO) << StringPrintf(
406             "Invoking '%s' quick code=%p static=%d", PrettyMethod().c_str(),
407             GetEntryPointFromQuickCompiledCode(), static_cast<int>(IsStatic() ? 1 : 0));
408       }
409 
410       // Ensure that we won't be accidentally calling quick compiled code when -Xint.
411       if (kIsDebugBuild && runtime->GetInstrumentation()->IsForcedInterpretOnly()) {
412         CHECK(!runtime->UseJitCompilation());
413         const void* oat_quick_code =
414             (IsNative() || !IsInvokable() || IsProxyMethod() || IsObsolete())
415             ? nullptr
416             : GetOatMethodQuickCode(runtime->GetClassLinker()->GetImagePointerSize());
417         CHECK(oat_quick_code == nullptr || oat_quick_code != GetEntryPointFromQuickCompiledCode())
418             << "Don't call compiled code when -Xint " << PrettyMethod();
419       }
420 
421       if (!IsStatic()) {
422         (*art_quick_invoke_stub)(this, args, args_size, self, result, shorty);
423       } else {
424         (*art_quick_invoke_static_stub)(this, args, args_size, self, result, shorty);
425       }
426       if (UNLIKELY(self->GetException() == Thread::GetDeoptimizationException())) {
427         // Unusual case where we were running generated code and an
428         // exception was thrown to force the activations to be removed from the
429         // stack. Continue execution in the interpreter.
430         self->DeoptimizeWithDeoptimizationException(result);
431       }
432       if (kLogInvocationStartAndReturn) {
433         LOG(INFO) << StringPrintf("Returned '%s' quick code=%p", PrettyMethod().c_str(),
434                                   GetEntryPointFromQuickCompiledCode());
435       }
436     } else {
437       LOG(INFO) << "Not invoking '" << PrettyMethod() << "' code=null";
438       if (result != nullptr) {
439         result->SetJ(0);
440       }
441     }
442   }
443 
444   // Pop transition.
445   self->PopManagedStackFragment(fragment);
446 }
447 
IsSignaturePolymorphic()448 bool ArtMethod::IsSignaturePolymorphic() {
449   // Methods with a polymorphic signature have constraints that they
450   // are native and varargs and belong to either MethodHandle or VarHandle.
451   if (!IsNative() || !IsVarargs()) {
452     return false;
453   }
454   ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
455       Runtime::Current()->GetClassLinker()->GetClassRoots();
456   ObjPtr<mirror::Class> cls = GetDeclaringClass();
457   return (cls == GetClassRoot<mirror::MethodHandle>(class_roots) ||
458           cls == GetClassRoot<mirror::VarHandle>(class_roots));
459 }
460 
GetOatMethodIndexFromMethodIndex(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)461 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
462                                                  uint16_t class_def_idx,
463                                                  uint32_t method_idx) {
464   ClassAccessor accessor(dex_file, class_def_idx);
465   uint32_t class_def_method_index = 0u;
466   for (const ClassAccessor::Method& method : accessor.GetMethods()) {
467     if (method.GetIndex() == method_idx) {
468       return class_def_method_index;
469     }
470     class_def_method_index++;
471   }
472   LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
473   UNREACHABLE();
474 }
475 
476 // We use the method's DexFile and declaring class name to find the OatMethod for an obsolete
477 // method.  This is extremely slow but we need it if we want to be able to have obsolete native
478 // methods since we need this to find the size of its stack frames.
479 //
480 // NB We could (potentially) do this differently and rely on the way the transformation is applied
481 // in order to use the entrypoint to find this information. However, for debugging reasons (most
482 // notably making sure that new invokes of obsolete methods fail) we choose to instead get the data
483 // directly from the dex file.
FindOatMethodFromDexFileFor(ArtMethod * method,bool * found)484 static const OatFile::OatMethod FindOatMethodFromDexFileFor(ArtMethod* method, bool* found)
485     REQUIRES_SHARED(Locks::mutator_lock_) {
486   DCHECK(method->IsObsolete() && method->IsNative());
487   const DexFile* dex_file = method->GetDexFile();
488 
489   // recreate the class_def_index from the descriptor.
490   const dex::TypeId* declaring_class_type_id =
491       dex_file->FindTypeId(method->GetDeclaringClassDescriptorView());
492   CHECK(declaring_class_type_id != nullptr);
493   dex::TypeIndex declaring_class_type_index = dex_file->GetIndexForTypeId(*declaring_class_type_id);
494   const dex::ClassDef* declaring_class_type_def =
495       dex_file->FindClassDef(declaring_class_type_index);
496   CHECK(declaring_class_type_def != nullptr);
497   uint16_t declaring_class_def_index = dex_file->GetIndexForClassDef(*declaring_class_type_def);
498 
499   size_t oat_method_index = GetOatMethodIndexFromMethodIndex(*dex_file,
500                                                              declaring_class_def_index,
501                                                              method->GetDexMethodIndex());
502 
503   OatFile::OatClass oat_class = OatFile::FindOatClass(*dex_file,
504                                                       declaring_class_def_index,
505                                                       found);
506   if (!(*found)) {
507     return OatFile::OatMethod::Invalid();
508   }
509   return oat_class.GetOatMethod(oat_method_index);
510 }
511 
FindOatMethodFor(ArtMethod * method,PointerSize pointer_size,bool * found)512 static const OatFile::OatMethod FindOatMethodFor(ArtMethod* method,
513                                                  PointerSize pointer_size,
514                                                  bool* found)
515     REQUIRES_SHARED(Locks::mutator_lock_) {
516   if (UNLIKELY(method->IsObsolete())) {
517     // We shouldn't be calling this with obsolete methods except for native obsolete methods for
518     // which we need to use the oat method to figure out how large the quick frame is.
519     DCHECK(method->IsNative()) << "We should only be finding the OatMethod of obsolete methods in "
520                                << "order to allow stack walking. Other obsolete methods should "
521                                << "never need to access this information.";
522     DCHECK_EQ(pointer_size, kRuntimePointerSize) << "Obsolete method in compiler!";
523     return FindOatMethodFromDexFileFor(method, found);
524   }
525   // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
526   // method for direct methods (or virtual methods made direct).
527   ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
528   size_t oat_method_index;
529   if (method->IsStatic() || method->IsDirect()) {
530     // Simple case where the oat method index was stashed at load time.
531     oat_method_index = method->GetMethodIndex();
532   } else {
533     // Compute the oat_method_index by search for its position in the declared virtual methods.
534     oat_method_index = declaring_class->NumDirectMethods();
535     bool found_virtual = false;
536     for (ArtMethod& art_method : declaring_class->GetVirtualMethods(pointer_size)) {
537       // Check method index instead of identity in case of duplicate method definitions.
538       if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) {
539         found_virtual = true;
540         break;
541       }
542       oat_method_index++;
543     }
544     CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
545                          << method->PrettyMethod();
546   }
547   DCHECK_EQ(oat_method_index,
548             GetOatMethodIndexFromMethodIndex(declaring_class->GetDexFile(),
549                                              method->GetDeclaringClass()->GetDexClassDefIndex(),
550                                              method->GetDexMethodIndex()));
551   OatFile::OatClass oat_class = OatFile::FindOatClass(declaring_class->GetDexFile(),
552                                                       declaring_class->GetDexClassDefIndex(),
553                                                       found);
554   if (!(*found)) {
555     return OatFile::OatMethod::Invalid();
556   }
557   return oat_class.GetOatMethod(oat_method_index);
558 }
559 
EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params)560 bool ArtMethod::EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params) {
561   const DexFile* dex_file = GetDexFile();
562   const auto& method_id = dex_file->GetMethodId(GetDexMethodIndex());
563   const auto& proto_id = dex_file->GetMethodPrototype(method_id);
564   const dex::TypeList* proto_params = dex_file->GetProtoParameters(proto_id);
565   auto count = proto_params != nullptr ? proto_params->Size() : 0u;
566   auto param_len = params != nullptr ? params->GetLength() : 0u;
567   if (param_len != count) {
568     return false;
569   }
570   auto* cl = Runtime::Current()->GetClassLinker();
571   for (size_t i = 0; i < count; ++i) {
572     dex::TypeIndex type_idx = proto_params->GetTypeItem(i).type_idx_;
573     ObjPtr<mirror::Class> type = cl->ResolveType(type_idx, this);
574     if (type == nullptr) {
575       Thread::Current()->AssertPendingException();
576       return false;
577     }
578     if (type != params->GetWithoutChecks(i)) {
579       return false;
580     }
581   }
582   return true;
583 }
584 
GetOatQuickMethodHeader(uintptr_t pc)585 const OatQuickMethodHeader* ArtMethod::GetOatQuickMethodHeader(uintptr_t pc) {
586   if (IsRuntimeMethod()) {
587     return nullptr;
588   }
589 
590   Runtime* runtime = Runtime::Current();
591   const void* existing_entry_point = GetEntryPointFromQuickCompiledCode();
592   CHECK(existing_entry_point != nullptr) << PrettyMethod() << "@" << this;
593   ClassLinker* class_linker = runtime->GetClassLinker();
594 
595   if (existing_entry_point == GetQuickProxyInvokeHandler()) {
596     DCHECK(IsProxyMethod() && !IsConstructor());
597     // The proxy entry point does not have any method header.
598     return nullptr;
599   }
600 
601   // We should not reach here with a pc of 0. pc can be 0 for downcalls when walking the stack.
602   // For native methods this case is handled by the caller by checking the quick frame tag. See
603   // StackVisitor::WalkStack for more details. For non-native methods pc can be 0 only for runtime
604   // methods or proxy invoke handlers which are handled earlier.
605   DCHECK_NE(pc, 0u) << "PC 0 for " << PrettyMethod();
606 
607   // Check whether the current entry point contains this pc. We need to manually
608   // check some entrypoints in case they are trampolines in the oat file.
609   if (!class_linker->IsQuickGenericJniStub(existing_entry_point) &&
610       !class_linker->IsQuickResolutionStub(existing_entry_point) &&
611       !class_linker->IsQuickToInterpreterBridge(existing_entry_point) &&
612       !OatQuickMethodHeader::IsStub(
613           reinterpret_cast<const uint8_t*>(existing_entry_point)).value_or(true)) {
614     OatQuickMethodHeader* method_header =
615         OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
616 
617     if (method_header->Contains(pc)) {
618       return method_header;
619     }
620   }
621 
622   if (OatQuickMethodHeader::IsNterpPc(pc)) {
623     return OatQuickMethodHeader::NterpMethodHeader;
624   }
625 
626   // Check whether the pc is in the JIT code cache.
627   jit::Jit* jit = runtime->GetJit();
628   if (jit != nullptr) {
629     jit::JitCodeCache* code_cache = jit->GetCodeCache();
630     OatQuickMethodHeader* method_header = code_cache->LookupMethodHeader(pc, this);
631     if (method_header != nullptr) {
632       DCHECK(method_header->Contains(pc));
633       return method_header;
634     } else {
635       if (kIsDebugBuild && code_cache->ContainsPc(reinterpret_cast<const void*>(pc))) {
636         code_cache->DumpAllCompiledMethods(LOG_STREAM(FATAL_WITHOUT_ABORT));
637         LOG(FATAL)
638             << PrettyMethod()
639             << ", pc=" << std::hex << pc
640             << ", entry_point=" << std::hex << reinterpret_cast<uintptr_t>(existing_entry_point)
641             << ", copy=" << std::boolalpha << IsCopied()
642             << ", proxy=" << std::boolalpha << IsProxyMethod()
643             << ", is_native=" << std::boolalpha << IsNative();
644       }
645     }
646   }
647 
648   // The code has to be in an oat file.
649   bool found;
650   OatFile::OatMethod oat_method =
651       FindOatMethodFor(this, class_linker->GetImagePointerSize(), &found);
652   if (!found) {
653     if (!IsNative()) {
654       PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
655       MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
656       LOG(FATAL)
657           << PrettyMethod()
658           << " pc=" << pc
659           << ", entrypoint= " << std::hex << reinterpret_cast<uintptr_t>(existing_entry_point)
660           << ", jit= " << jit;
661     }
662     // We are running the GenericJNI stub. The entrypoint may point
663     // to different entrypoints, to a JIT-compiled JNI stub, or to a shared boot
664     // image stub.
665     DCHECK(class_linker->IsQuickGenericJniStub(existing_entry_point) ||
666            class_linker->IsQuickResolutionStub(existing_entry_point) ||
667            (jit != nullptr && jit->GetCodeCache()->ContainsPc(existing_entry_point)) ||
668            (class_linker->FindBootJniStub(this) != nullptr))
669         << " method: " << PrettyMethod()
670         << " entrypoint: " << existing_entry_point
671         << " size: " << OatQuickMethodHeader::FromEntryPoint(existing_entry_point)->GetCodeSize()
672         << " pc: " << reinterpret_cast<const void*>(pc);
673     return nullptr;
674   }
675   const void* oat_entry_point = oat_method.GetQuickCode();
676   if (oat_entry_point == nullptr || class_linker->IsQuickGenericJniStub(oat_entry_point)) {
677     if (kIsDebugBuild && !IsNative()) {
678       PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
679       MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
680       LOG(FATAL)
681           << PrettyMethod()
682           << std::hex
683           << " pc=" << pc
684           << ", entrypoint= " << reinterpret_cast<uintptr_t>(existing_entry_point)
685           << ", jit= " << jit
686           << ", nterp_start= "
687           << reinterpret_cast<uintptr_t>(OatQuickMethodHeader::NterpImpl.data())
688           << ", nterp_end= "
689           << reinterpret_cast<uintptr_t>(
690                  OatQuickMethodHeader::NterpImpl.data() + OatQuickMethodHeader::NterpImpl.size());
691     }
692     return nullptr;
693   }
694 
695   OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromEntryPoint(oat_entry_point);
696   // We could have existing Oat code for native methods but we may not use it if the runtime is java
697   // debuggable or when profiling boot class path. There is no easy way to check if the pc
698   // corresponds to QuickGenericJniStub. Since we have eliminated all the other cases, if the pc
699   // doesn't correspond to the AOT code then we must be running QuickGenericJniStub.
700   if (IsNative() && !method_header->Contains(pc)) {
701     DCHECK_NE(pc, 0u) << "PC 0 for " << PrettyMethod();
702     return nullptr;
703   }
704 
705   DCHECK(method_header->Contains(pc))
706       << PrettyMethod()
707       << " " << std::hex << pc << " " << oat_entry_point
708       << " " << (uintptr_t)(method_header->GetCode() + method_header->GetCodeSize());
709   return method_header;
710 }
711 
GetOatMethodQuickCode(PointerSize pointer_size)712 const void* ArtMethod::GetOatMethodQuickCode(PointerSize pointer_size) {
713   bool found;
714   OatFile::OatMethod oat_method = FindOatMethodFor(this, pointer_size, &found);
715   if (found) {
716     return oat_method.GetQuickCode();
717   }
718   return nullptr;
719 }
720 
SetIntrinsic(Intrinsics intrinsic)721 void ArtMethod::SetIntrinsic(Intrinsics intrinsic) {
722   // Currently we only do intrinsics for static/final methods or methods of final
723   // classes. We don't set kHasSingleImplementation for those methods.
724   DCHECK(IsStatic() || IsFinal() || GetDeclaringClass()->IsFinal()) <<
725       "Potential conflict with kAccSingleImplementation";
726   static constexpr int kAccFlagsShift = CTZ(kAccIntrinsicBits);
727   uint32_t intrinsic_u32 = enum_cast<uint32_t>(intrinsic);
728   DCHECK_LE(intrinsic_u32, kAccIntrinsicBits >> kAccFlagsShift);
729   uint32_t intrinsic_bits = intrinsic_u32 << kAccFlagsShift;
730   uint32_t new_value = (GetAccessFlags() & ~kAccIntrinsicBits) | kAccIntrinsic | intrinsic_bits;
731 
732   // These flags shouldn't be overridden by setting the intrinsic.
733   uint32_t java_flags = (GetAccessFlags() & kAccJavaFlagsMask);
734   bool is_constructor = IsConstructor();
735   bool is_synchronized = IsSynchronized();
736   bool skip_access_checks = SkipAccessChecks();
737   bool is_fast_native = IsFastNative();
738   bool is_critical_native = IsCriticalNative();
739   bool is_copied = IsCopied();
740   bool is_miranda = IsMiranda();
741   bool is_default = IsDefault();
742   bool is_default_conflict = IsDefaultConflicting();
743   bool is_compilable = IsCompilable();
744   bool must_count_locks = MustCountLocks();
745 
746 #ifdef ART_TARGET_ANDROID
747   // Recompute flags instead of getting them from the current access flags because
748   // access flags may have been changed to deduplicate warning messages (b/129063331).
749   // For host builds, the flags from the api list (i.e. hiddenapi::CreateRuntimeFlags) might not
750   // have the right value.
751   uint32_t hiddenapi_flags = hiddenapi::CreateRuntimeFlags(this);
752 #endif
753 
754   SetAccessFlags(new_value);
755   // Intrinsics are considered hot from the first call.
756   SetHotCounter();
757 
758   // DCHECK that the flags weren't overridden.
759   DCHECK_EQ(java_flags, (GetAccessFlags() & kAccJavaFlagsMask));
760   DCHECK_EQ(is_constructor, IsConstructor());
761   DCHECK_EQ(is_synchronized, IsSynchronized());
762   DCHECK_EQ(skip_access_checks, SkipAccessChecks());
763   DCHECK_EQ(is_fast_native, IsFastNative());
764   DCHECK_EQ(is_critical_native, IsCriticalNative());
765   DCHECK_EQ(is_copied, IsCopied());
766   DCHECK_EQ(is_miranda, IsMiranda());
767   DCHECK_EQ(is_default, IsDefault());
768   DCHECK_EQ(is_default_conflict, IsDefaultConflicting());
769   DCHECK_EQ(is_compilable, IsCompilable());
770   DCHECK_EQ(must_count_locks, MustCountLocks());
771 
772 #ifdef ART_TARGET_ANDROID
773   DCHECK_EQ(hiddenapi_flags, hiddenapi::GetRuntimeFlags(this)) << PrettyMethod();
774 #endif
775 }
776 
SetNotIntrinsic()777 void ArtMethod::SetNotIntrinsic() {
778   if (!IsIntrinsic()) {
779     return;
780   }
781 
782   // Read the existing hiddenapi flags.
783   uint32_t hiddenapi_runtime_flags = hiddenapi::GetRuntimeFlags(this);
784 
785   // Clear intrinsic-related access flags.
786   ClearAccessFlags(kAccIntrinsic | kAccIntrinsicBits);
787 
788   // Re-apply hidden API access flags now that the method is not an intrinsic.
789   SetAccessFlags(GetAccessFlags() | hiddenapi_runtime_flags);
790   DCHECK_EQ(hiddenapi_runtime_flags, hiddenapi::GetRuntimeFlags(this));
791 }
792 
CopyFrom(ArtMethod * src,PointerSize image_pointer_size)793 void ArtMethod::CopyFrom(ArtMethod* src, PointerSize image_pointer_size) {
794   memcpy(reinterpret_cast<void*>(this), reinterpret_cast<const void*>(src),
795          Size(image_pointer_size));
796   declaring_class_ = GcRoot<mirror::Class>(const_cast<ArtMethod*>(src)->GetDeclaringClass());
797 
798   // If the entry point of the method we are copying from is from JIT code, we just
799   // put the entry point of the new method to interpreter or GenericJNI. We could set
800   // the entry point to the JIT code, but this would require taking the JIT code cache
801   // lock to notify it, which we do not want at this level.
802   Runtime* runtime = Runtime::Current();
803   const void* entry_point = GetEntryPointFromQuickCompiledCodePtrSize(image_pointer_size);
804   if (runtime->UseJitCompilation()) {
805     if (runtime->GetJit()->GetCodeCache()->ContainsPc(entry_point)) {
806       SetNativePointer(EntryPointFromQuickCompiledCodeOffset(image_pointer_size),
807                        src->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge(),
808                        image_pointer_size);
809     }
810   }
811   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
812   if (interpreter::IsNterpSupported() && class_linker->IsNterpEntryPoint(entry_point)) {
813     // If the entrypoint is nterp, it's too early to check if the new method
814     // will support it. So for simplicity, use the interpreter bridge.
815     SetNativePointer(EntryPointFromQuickCompiledCodeOffset(image_pointer_size),
816                      GetQuickToInterpreterBridge(),
817                      image_pointer_size);
818   }
819 
820   // Clear the data pointer, it will be set if needed by the caller.
821   if (!src->HasCodeItem() && !src->IsNative()) {
822     SetDataPtrSize(nullptr, image_pointer_size);
823   }
824   // Clear hotness to let the JIT properly decide when to compile this method.
825   ResetCounter(runtime->GetJITOptions()->GetWarmupThreshold());
826 }
827 
IsImagePointerSize(PointerSize pointer_size)828 bool ArtMethod::IsImagePointerSize(PointerSize pointer_size) {
829   // Hijack this function to get access to PtrSizedFieldsOffset.
830   //
831   // Ensure that PrtSizedFieldsOffset is correct. We rely here on usually having both 32-bit and
832   // 64-bit builds.
833   static_assert(std::is_standard_layout<ArtMethod>::value, "ArtMethod is not standard layout.");
834   static_assert(
835       (sizeof(void*) != 4) ||
836           (offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k32)),
837       "Unexpected 32-bit class layout.");
838   static_assert(
839       (sizeof(void*) != 8) ||
840           (offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k64)),
841       "Unexpected 64-bit class layout.");
842 
843   Runtime* runtime = Runtime::Current();
844   if (runtime == nullptr) {
845     return true;
846   }
847   return runtime->GetClassLinker()->GetImagePointerSize() == pointer_size;
848 }
849 
PrettyMethod(ArtMethod * m,bool with_signature)850 std::string ArtMethod::PrettyMethod(ArtMethod* m, bool with_signature) {
851   if (m == nullptr) {
852     return "null";
853   }
854   return m->PrettyMethod(with_signature);
855 }
856 
PrettyMethod(bool with_signature)857 std::string ArtMethod::PrettyMethod(bool with_signature) {
858   if (UNLIKELY(IsRuntimeMethod())) {
859     std::string result = "<runtime method>.";
860     result += GetName();
861     // Do not add "<no signature>" even if `with_signature` is true.
862     return result;
863   }
864   ArtMethod* m =
865       GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
866   std::string res(m->GetDexFile()->PrettyMethod(m->GetDexMethodIndex(), with_signature));
867   if (with_signature && m->IsObsolete()) {
868     return "<OBSOLETE> " + res;
869   } else {
870     return res;
871   }
872 }
873 
JniShortName()874 std::string ArtMethod::JniShortName() {
875   return GetJniShortName(GetDeclaringClassDescriptor(), GetName());
876 }
877 
JniLongName()878 std::string ArtMethod::JniLongName() {
879   std::string long_name;
880   long_name += JniShortName();
881   long_name += "__";
882 
883   std::string signature(GetSignature().ToString());
884   signature.erase(0, 1);
885   signature.erase(signature.begin() + signature.find(')'), signature.end());
886 
887   long_name += MangleForJni(signature);
888 
889   return long_name;
890 }
891 
GetRuntimeMethodName()892 const char* ArtMethod::GetRuntimeMethodName() {
893   Runtime* const runtime = Runtime::Current();
894   if (this == runtime->GetResolutionMethod()) {
895     return "<runtime internal resolution method>";
896   } else if (this == runtime->GetImtConflictMethod()) {
897     return "<runtime internal imt conflict method>";
898   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves)) {
899     return "<runtime internal callee-save all registers method>";
900   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly)) {
901     return "<runtime internal callee-save reference registers method>";
902   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs)) {
903     return "<runtime internal callee-save reference and argument registers method>";
904   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything)) {
905     return "<runtime internal save-every-register method>";
906   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit)) {
907     return "<runtime internal save-every-register method for clinit>";
908   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck)) {
909     return "<runtime internal save-every-register method for suspend check>";
910   } else {
911     return "<unknown runtime internal method>";
912   }
913 }
914 
SetCodeItem(const dex::CodeItem * code_item,bool is_compact_dex_code_item)915 void ArtMethod::SetCodeItem(const dex::CodeItem* code_item, bool is_compact_dex_code_item) {
916   DCHECK(HasCodeItem());
917   // We mark the lowest bit for the interpreter to know whether it's executing a
918   // method in a compact or standard dex file.
919   uintptr_t data =
920       reinterpret_cast<uintptr_t>(code_item) | (is_compact_dex_code_item ? 1 : 0);
921   SetDataPtrSize(reinterpret_cast<void*>(data), kRuntimePointerSize);
922 }
923 
924 // AssertSharedHeld doesn't work in GetAccessFlags, so use a NO_THREAD_SAFETY_ANALYSIS helper.
925 // TODO: Figure out why ASSERT_SHARED_CAPABILITY doesn't work.
926 template <ReadBarrierOption kReadBarrierOption>
DoGetAccessFlagsHelper(ArtMethod * method)927 ALWAYS_INLINE static inline void DoGetAccessFlagsHelper(ArtMethod* method)
928     NO_THREAD_SAFETY_ANALYSIS {
929   CHECK(method->IsRuntimeMethod() ||
930         method->GetDeclaringClass<kReadBarrierOption>()->IsIdxLoaded() ||
931         method->GetDeclaringClass<kReadBarrierOption>()->IsErroneous());
932 }
933 
934 }  // namespace art
935