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-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 "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 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 
IsOverridableByDefaultMethod()395 bool ArtMethod::IsOverridableByDefaultMethod() {
396   return GetDeclaringClass()->IsInterface();
397 }
398 
IsPolymorphicSignature()399 bool ArtMethod::IsPolymorphicSignature() {
400   // Methods with a polymorphic signature have constraints that they
401   // are native and varargs and belong to either MethodHandle or VarHandle.
402   if (!IsNative() || !IsVarargs()) {
403     return false;
404   }
405   ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
406       Runtime::Current()->GetClassLinker()->GetClassRoots();
407   ObjPtr<mirror::Class> cls = GetDeclaringClass();
408   return (cls == GetClassRoot<mirror::MethodHandle>(class_roots) ||
409           cls == GetClassRoot<mirror::VarHandle>(class_roots));
410 }
411 
GetOatMethodIndexFromMethodIndex(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)412 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
413                                                  uint16_t class_def_idx,
414                                                  uint32_t method_idx) {
415   ClassAccessor accessor(dex_file, class_def_idx);
416   uint32_t class_def_method_index = 0u;
417   for (const ClassAccessor::Method& method : accessor.GetMethods()) {
418     if (method.GetIndex() == method_idx) {
419       return class_def_method_index;
420     }
421     class_def_method_index++;
422   }
423   LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
424   UNREACHABLE();
425 }
426 
427 // We use the method's DexFile and declaring class name to find the OatMethod for an obsolete
428 // method.  This is extremely slow but we need it if we want to be able to have obsolete native
429 // methods since we need this to find the size of its stack frames.
430 //
431 // NB We could (potentially) do this differently and rely on the way the transformation is applied
432 // in order to use the entrypoint to find this information. However, for debugging reasons (most
433 // notably making sure that new invokes of obsolete methods fail) we choose to instead get the data
434 // directly from the dex file.
FindOatMethodFromDexFileFor(ArtMethod * method,bool * found)435 static const OatFile::OatMethod FindOatMethodFromDexFileFor(ArtMethod* method, bool* found)
436     REQUIRES_SHARED(Locks::mutator_lock_) {
437   DCHECK(method->IsObsolete() && method->IsNative());
438   const DexFile* dex_file = method->GetDexFile();
439 
440   // recreate the class_def_index from the descriptor.
441   std::string descriptor_storage;
442   const dex::TypeId* declaring_class_type_id =
443       dex_file->FindTypeId(method->GetDeclaringClass()->GetDescriptor(&descriptor_storage));
444   CHECK(declaring_class_type_id != nullptr);
445   dex::TypeIndex declaring_class_type_index = dex_file->GetIndexForTypeId(*declaring_class_type_id);
446   const dex::ClassDef* declaring_class_type_def =
447       dex_file->FindClassDef(declaring_class_type_index);
448   CHECK(declaring_class_type_def != nullptr);
449   uint16_t declaring_class_def_index = dex_file->GetIndexForClassDef(*declaring_class_type_def);
450 
451   size_t oat_method_index = GetOatMethodIndexFromMethodIndex(*dex_file,
452                                                              declaring_class_def_index,
453                                                              method->GetDexMethodIndex());
454 
455   OatFile::OatClass oat_class = OatFile::FindOatClass(*dex_file,
456                                                       declaring_class_def_index,
457                                                       found);
458   if (!(*found)) {
459     return OatFile::OatMethod::Invalid();
460   }
461   return oat_class.GetOatMethod(oat_method_index);
462 }
463 
FindOatMethodFor(ArtMethod * method,PointerSize pointer_size,bool * found)464 static const OatFile::OatMethod FindOatMethodFor(ArtMethod* method,
465                                                  PointerSize pointer_size,
466                                                  bool* found)
467     REQUIRES_SHARED(Locks::mutator_lock_) {
468   if (UNLIKELY(method->IsObsolete())) {
469     // We shouldn't be calling this with obsolete methods except for native obsolete methods for
470     // which we need to use the oat method to figure out how large the quick frame is.
471     DCHECK(method->IsNative()) << "We should only be finding the OatMethod of obsolete methods in "
472                                << "order to allow stack walking. Other obsolete methods should "
473                                << "never need to access this information.";
474     DCHECK_EQ(pointer_size, kRuntimePointerSize) << "Obsolete method in compiler!";
475     return FindOatMethodFromDexFileFor(method, found);
476   }
477   // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
478   // method for direct methods (or virtual methods made direct).
479   ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
480   size_t oat_method_index;
481   if (method->IsStatic() || method->IsDirect()) {
482     // Simple case where the oat method index was stashed at load time.
483     oat_method_index = method->GetMethodIndex();
484   } else {
485     // Compute the oat_method_index by search for its position in the declared virtual methods.
486     oat_method_index = declaring_class->NumDirectMethods();
487     bool found_virtual = false;
488     for (ArtMethod& art_method : declaring_class->GetVirtualMethods(pointer_size)) {
489       // Check method index instead of identity in case of duplicate method definitions.
490       if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) {
491         found_virtual = true;
492         break;
493       }
494       oat_method_index++;
495     }
496     CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
497                          << method->PrettyMethod();
498   }
499   DCHECK_EQ(oat_method_index,
500             GetOatMethodIndexFromMethodIndex(declaring_class->GetDexFile(),
501                                              method->GetDeclaringClass()->GetDexClassDefIndex(),
502                                              method->GetDexMethodIndex()));
503   OatFile::OatClass oat_class = OatFile::FindOatClass(declaring_class->GetDexFile(),
504                                                       declaring_class->GetDexClassDefIndex(),
505                                                       found);
506   if (!(*found)) {
507     return OatFile::OatMethod::Invalid();
508   }
509   return oat_class.GetOatMethod(oat_method_index);
510 }
511 
EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params)512 bool ArtMethod::EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params) {
513   const DexFile* dex_file = GetDexFile();
514   const auto& method_id = dex_file->GetMethodId(GetDexMethodIndex());
515   const auto& proto_id = dex_file->GetMethodPrototype(method_id);
516   const dex::TypeList* proto_params = dex_file->GetProtoParameters(proto_id);
517   auto count = proto_params != nullptr ? proto_params->Size() : 0u;
518   auto param_len = params != nullptr ? params->GetLength() : 0u;
519   if (param_len != count) {
520     return false;
521   }
522   auto* cl = Runtime::Current()->GetClassLinker();
523   for (size_t i = 0; i < count; ++i) {
524     dex::TypeIndex type_idx = proto_params->GetTypeItem(i).type_idx_;
525     ObjPtr<mirror::Class> type = cl->ResolveType(type_idx, this);
526     if (type == nullptr) {
527       Thread::Current()->AssertPendingException();
528       return false;
529     }
530     if (type != params->GetWithoutChecks(i)) {
531       return false;
532     }
533   }
534   return true;
535 }
536 
GetQuickenedInfo()537 ArrayRef<const uint8_t> ArtMethod::GetQuickenedInfo() {
538   const DexFile& dex_file = *GetDexFile();
539   const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
540   if (oat_dex_file == nullptr) {
541     return ArrayRef<const uint8_t>();
542   }
543   return oat_dex_file->GetQuickenedInfoOf(dex_file, GetDexMethodIndex());
544 }
545 
GetIndexFromQuickening(uint32_t dex_pc)546 uint16_t ArtMethod::GetIndexFromQuickening(uint32_t dex_pc) {
547   ArrayRef<const uint8_t> data = GetQuickenedInfo();
548   if (data.empty()) {
549     return DexFile::kDexNoIndex16;
550   }
551   QuickenInfoTable table(data);
552   uint32_t quicken_index = 0;
553   for (const DexInstructionPcPair& pair : DexInstructions()) {
554     if (pair.DexPc() == dex_pc) {
555       return table.GetData(quicken_index);
556     }
557     if (QuickenInfoTable::NeedsIndexForInstruction(&pair.Inst())) {
558       ++quicken_index;
559     }
560   }
561   return DexFile::kDexNoIndex16;
562 }
563 
GetOatQuickMethodHeader(uintptr_t pc)564 const OatQuickMethodHeader* ArtMethod::GetOatQuickMethodHeader(uintptr_t pc) {
565   // Our callers should make sure they don't pass the instrumentation exit pc,
566   // as this method does not look at the side instrumentation stack.
567   DCHECK_NE(pc, reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()));
568 
569   if (IsRuntimeMethod()) {
570     return nullptr;
571   }
572 
573   Runtime* runtime = Runtime::Current();
574   const void* existing_entry_point = GetEntryPointFromQuickCompiledCode();
575   CHECK(existing_entry_point != nullptr) << PrettyMethod() << "@" << this;
576   ClassLinker* class_linker = runtime->GetClassLinker();
577 
578   if (existing_entry_point == GetQuickProxyInvokeHandler()) {
579     DCHECK(IsProxyMethod() && !IsConstructor());
580     // The proxy entry point does not have any method header.
581     return nullptr;
582   }
583 
584   // Check whether the current entry point contains this pc.
585   if (!class_linker->IsQuickGenericJniStub(existing_entry_point) &&
586       !class_linker->IsQuickResolutionStub(existing_entry_point) &&
587       !class_linker->IsQuickToInterpreterBridge(existing_entry_point) &&
588       existing_entry_point != GetQuickInstrumentationEntryPoint()) {
589     OatQuickMethodHeader* method_header =
590         OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
591 
592     if (method_header->Contains(pc)) {
593       return method_header;
594     }
595   }
596 
597   if (OatQuickMethodHeader::NterpMethodHeader != nullptr &&
598       OatQuickMethodHeader::NterpMethodHeader->Contains(pc)) {
599     return OatQuickMethodHeader::NterpMethodHeader;
600   }
601 
602   // Check whether the pc is in the JIT code cache.
603   jit::Jit* jit = runtime->GetJit();
604   if (jit != nullptr) {
605     jit::JitCodeCache* code_cache = jit->GetCodeCache();
606     OatQuickMethodHeader* method_header = code_cache->LookupMethodHeader(pc, this);
607     if (method_header != nullptr) {
608       DCHECK(method_header->Contains(pc));
609       return method_header;
610     } else {
611       DCHECK(!code_cache->ContainsPc(reinterpret_cast<const void*>(pc)))
612           << PrettyMethod()
613           << ", pc=" << std::hex << pc
614           << ", entry_point=" << std::hex << reinterpret_cast<uintptr_t>(existing_entry_point)
615           << ", copy=" << std::boolalpha << IsCopied()
616           << ", proxy=" << std::boolalpha << IsProxyMethod();
617     }
618   }
619 
620   // The code has to be in an oat file.
621   bool found;
622   OatFile::OatMethod oat_method =
623       FindOatMethodFor(this, class_linker->GetImagePointerSize(), &found);
624   if (!found) {
625     if (IsNative()) {
626       // We are running the GenericJNI stub. The entrypoint may point
627       // to different entrypoints or to a JIT-compiled JNI stub.
628       DCHECK(class_linker->IsQuickGenericJniStub(existing_entry_point) ||
629              class_linker->IsQuickResolutionStub(existing_entry_point) ||
630              existing_entry_point == GetQuickInstrumentationEntryPoint() ||
631              (jit != nullptr && jit->GetCodeCache()->ContainsPc(existing_entry_point)));
632       return nullptr;
633     }
634     // Only for unit tests.
635     // TODO(ngeoffray): Update these tests to pass the right pc?
636     return OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
637   }
638   const void* oat_entry_point = oat_method.GetQuickCode();
639   if (oat_entry_point == nullptr || class_linker->IsQuickGenericJniStub(oat_entry_point)) {
640     DCHECK(IsNative()) << PrettyMethod();
641     return nullptr;
642   }
643 
644   OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromEntryPoint(oat_entry_point);
645   if (pc == 0) {
646     // This is a downcall, it can only happen for a native method.
647     DCHECK(IsNative());
648     return method_header;
649   }
650 
651   DCHECK(method_header->Contains(pc))
652       << PrettyMethod()
653       << " " << std::hex << pc << " " << oat_entry_point
654       << " " << (uintptr_t)(method_header->GetCode() + method_header->GetCodeSize());
655   return method_header;
656 }
657 
GetOatMethodQuickCode(PointerSize pointer_size)658 const void* ArtMethod::GetOatMethodQuickCode(PointerSize pointer_size) {
659   bool found;
660   OatFile::OatMethod oat_method = FindOatMethodFor(this, pointer_size, &found);
661   if (found) {
662     return oat_method.GetQuickCode();
663   }
664   return nullptr;
665 }
666 
HasAnyCompiledCode()667 bool ArtMethod::HasAnyCompiledCode() {
668   if (IsNative() || !IsInvokable() || IsProxyMethod()) {
669     return false;
670   }
671 
672   // Check whether the JIT has compiled it.
673   Runtime* runtime = Runtime::Current();
674   jit::Jit* jit = runtime->GetJit();
675   if (jit != nullptr && jit->GetCodeCache()->ContainsMethod(this)) {
676     return true;
677   }
678 
679   // Check whether we have AOT code.
680   return GetOatMethodQuickCode(runtime->GetClassLinker()->GetImagePointerSize()) != nullptr;
681 }
682 
SetIntrinsic(uint32_t intrinsic)683 void ArtMethod::SetIntrinsic(uint32_t intrinsic) {
684   // Currently we only do intrinsics for static/final methods or methods of final
685   // classes. We don't set kHasSingleImplementation for those methods.
686   DCHECK(IsStatic() || IsFinal() || GetDeclaringClass()->IsFinal()) <<
687       "Potential conflict with kAccSingleImplementation";
688   static const int kAccFlagsShift = CTZ(kAccIntrinsicBits);
689   DCHECK_LE(intrinsic, kAccIntrinsicBits >> kAccFlagsShift);
690   uint32_t intrinsic_bits = intrinsic << kAccFlagsShift;
691   uint32_t new_value = (GetAccessFlags() & ~kAccIntrinsicBits) | kAccIntrinsic | intrinsic_bits;
692   if (kIsDebugBuild) {
693     uint32_t java_flags = (GetAccessFlags() & kAccJavaFlagsMask);
694     bool is_constructor = IsConstructor();
695     bool is_synchronized = IsSynchronized();
696     bool skip_access_checks = SkipAccessChecks();
697     bool is_fast_native = IsFastNative();
698     bool is_critical_native = IsCriticalNative();
699     bool is_copied = IsCopied();
700     bool is_miranda = IsMiranda();
701     bool is_default = IsDefault();
702     bool is_default_conflict = IsDefaultConflicting();
703     bool is_compilable = IsCompilable();
704     bool must_count_locks = MustCountLocks();
705     // Recompute flags instead of getting them from the current access flags because
706     // access flags may have been changed to deduplicate warning messages (b/129063331).
707     uint32_t hiddenapi_flags = hiddenapi::CreateRuntimeFlags(this);
708     SetAccessFlags(new_value);
709     DCHECK_EQ(java_flags, (GetAccessFlags() & kAccJavaFlagsMask));
710     DCHECK_EQ(is_constructor, IsConstructor());
711     DCHECK_EQ(is_synchronized, IsSynchronized());
712     DCHECK_EQ(skip_access_checks, SkipAccessChecks());
713     DCHECK_EQ(is_fast_native, IsFastNative());
714     DCHECK_EQ(is_critical_native, IsCriticalNative());
715     DCHECK_EQ(is_copied, IsCopied());
716     DCHECK_EQ(is_miranda, IsMiranda());
717     DCHECK_EQ(is_default, IsDefault());
718     DCHECK_EQ(is_default_conflict, IsDefaultConflicting());
719     DCHECK_EQ(is_compilable, IsCompilable());
720     DCHECK_EQ(must_count_locks, MustCountLocks());
721     // Only DCHECK that we have preserved the hidden API access flags if the
722     // original method was not on the whitelist. This is because the core image
723     // does not have the access flags set (b/77733081).
724     if ((hiddenapi_flags & kAccHiddenapiBits) != kAccPublicApi) {
725       DCHECK_EQ(hiddenapi_flags, hiddenapi::GetRuntimeFlags(this)) << PrettyMethod();
726     }
727   } else {
728     SetAccessFlags(new_value);
729   }
730 }
731 
SetNotIntrinsic()732 void ArtMethod::SetNotIntrinsic() {
733   if (!IsIntrinsic()) {
734     return;
735   }
736 
737   // Read the existing hiddenapi flags.
738   uint32_t hiddenapi_runtime_flags = hiddenapi::GetRuntimeFlags(this);
739 
740   // Clear intrinsic-related access flags.
741   ClearAccessFlags(kAccIntrinsic | kAccIntrinsicBits);
742 
743   // Re-apply hidden API access flags now that the method is not an intrinsic.
744   SetAccessFlags(GetAccessFlags() | hiddenapi_runtime_flags);
745   DCHECK_EQ(hiddenapi_runtime_flags, hiddenapi::GetRuntimeFlags(this));
746 }
747 
CopyFrom(ArtMethod * src,PointerSize image_pointer_size)748 void ArtMethod::CopyFrom(ArtMethod* src, PointerSize image_pointer_size) {
749   memcpy(reinterpret_cast<void*>(this), reinterpret_cast<const void*>(src),
750          Size(image_pointer_size));
751   declaring_class_ = GcRoot<mirror::Class>(const_cast<ArtMethod*>(src)->GetDeclaringClass());
752 
753   // If the entry point of the method we are copying from is from JIT code, we just
754   // put the entry point of the new method to interpreter or GenericJNI. We could set
755   // the entry point to the JIT code, but this would require taking the JIT code cache
756   // lock to notify it, which we do not want at this level.
757   Runtime* runtime = Runtime::Current();
758   if (runtime->UseJitCompilation()) {
759     if (runtime->GetJit()->GetCodeCache()->ContainsPc(GetEntryPointFromQuickCompiledCode())) {
760       SetEntryPointFromQuickCompiledCodePtrSize(
761           src->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge(),
762           image_pointer_size);
763     }
764   }
765     if (interpreter::IsNterpSupported() &&
766         (GetEntryPointFromQuickCompiledCodePtrSize(image_pointer_size) ==
767             interpreter::GetNterpEntryPoint())) {
768     // If the entrypoint is nterp, it's too early to check if the new method
769     // will support it. So for simplicity, use the interpreter bridge.
770     SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(), image_pointer_size);
771   }
772 
773   // Clear the data pointer, it will be set if needed by the caller.
774   if (!src->IsNative()) {
775     SetDataPtrSize(nullptr, image_pointer_size);
776   }
777   // Clear hotness to let the JIT properly decide when to compile this method.
778   hotness_count_ = 0;
779 }
780 
IsImagePointerSize(PointerSize pointer_size)781 bool ArtMethod::IsImagePointerSize(PointerSize pointer_size) {
782   // Hijack this function to get access to PtrSizedFieldsOffset.
783   //
784   // Ensure that PrtSizedFieldsOffset is correct. We rely here on usually having both 32-bit and
785   // 64-bit builds.
786   static_assert(std::is_standard_layout<ArtMethod>::value, "ArtMethod is not standard layout.");
787   static_assert(
788       (sizeof(void*) != 4) ||
789           (offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k32)),
790       "Unexpected 32-bit class layout.");
791   static_assert(
792       (sizeof(void*) != 8) ||
793           (offsetof(ArtMethod, ptr_sized_fields_) == PtrSizedFieldsOffset(PointerSize::k64)),
794       "Unexpected 64-bit class layout.");
795 
796   Runtime* runtime = Runtime::Current();
797   if (runtime == nullptr) {
798     return true;
799   }
800   return runtime->GetClassLinker()->GetImagePointerSize() == pointer_size;
801 }
802 
PrettyMethod(ArtMethod * m,bool with_signature)803 std::string ArtMethod::PrettyMethod(ArtMethod* m, bool with_signature) {
804   if (m == nullptr) {
805     return "null";
806   }
807   return m->PrettyMethod(with_signature);
808 }
809 
PrettyMethod(bool with_signature)810 std::string ArtMethod::PrettyMethod(bool with_signature) {
811   if (UNLIKELY(IsRuntimeMethod())) {
812     std::string result = GetDeclaringClassDescriptor();
813     result += '.';
814     result += GetName();
815     // Do not add "<no signature>" even if `with_signature` is true.
816     return result;
817   }
818   ArtMethod* m =
819       GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
820   std::string res(m->GetDexFile()->PrettyMethod(m->GetDexMethodIndex(), with_signature));
821   if (with_signature && m->IsObsolete()) {
822     return "<OBSOLETE> " + res;
823   } else {
824     return res;
825   }
826 }
827 
JniShortName()828 std::string ArtMethod::JniShortName() {
829   return GetJniShortName(GetDeclaringClassDescriptor(), GetName());
830 }
831 
JniLongName()832 std::string ArtMethod::JniLongName() {
833   std::string long_name;
834   long_name += JniShortName();
835   long_name += "__";
836 
837   std::string signature(GetSignature().ToString());
838   signature.erase(0, 1);
839   signature.erase(signature.begin() + signature.find(')'), signature.end());
840 
841   long_name += MangleForJni(signature);
842 
843   return long_name;
844 }
845 
GetRuntimeMethodName()846 const char* ArtMethod::GetRuntimeMethodName() {
847   Runtime* const runtime = Runtime::Current();
848   if (this == runtime->GetResolutionMethod()) {
849     return "<runtime internal resolution method>";
850   } else if (this == runtime->GetImtConflictMethod()) {
851     return "<runtime internal imt conflict method>";
852   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves)) {
853     return "<runtime internal callee-save all registers method>";
854   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly)) {
855     return "<runtime internal callee-save reference registers method>";
856   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs)) {
857     return "<runtime internal callee-save reference and argument registers method>";
858   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything)) {
859     return "<runtime internal save-every-register method>";
860   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit)) {
861     return "<runtime internal save-every-register method for clinit>";
862   } else if (this == runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck)) {
863     return "<runtime internal save-every-register method for suspend check>";
864   } else {
865     return "<unknown runtime internal method>";
866   }
867 }
868 
869 // AssertSharedHeld doesn't work in GetAccessFlags, so use a NO_THREAD_SAFETY_ANALYSIS helper.
870 // TODO: Figure out why ASSERT_SHARED_CAPABILITY doesn't work.
871 template <ReadBarrierOption kReadBarrierOption>
DoGetAccessFlagsHelper(ArtMethod * method)872 ALWAYS_INLINE static inline void DoGetAccessFlagsHelper(ArtMethod* method)
873     NO_THREAD_SAFETY_ANALYSIS {
874   CHECK(method->IsRuntimeMethod() ||
875         method->GetDeclaringClass<kReadBarrierOption>()->IsIdxLoaded() ||
876         method->GetDeclaringClass<kReadBarrierOption>()->IsErroneous());
877 }
878 
879 }  // namespace art
880