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