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