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