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