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