art_method.cc revision bd89a5c556324062b7d841843b039392e84cfaf4
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 "arch/context.h"
20#include "art_field-inl.h"
21#include "art_method-inl.h"
22#include "base/stringpiece.h"
23#include "class_linker-inl.h"
24#include "debugger.h"
25#include "dex_file-inl.h"
26#include "dex_instruction.h"
27#include "entrypoints/runtime_asm_entrypoints.h"
28#include "gc/accounting/card_table-inl.h"
29#include "interpreter/interpreter.h"
30#include "jit/jit.h"
31#include "jit/jit_code_cache.h"
32#include "jit/profiling_info.h"
33#include "jni_internal.h"
34#include "mapping_table.h"
35#include "mirror/abstract_method.h"
36#include "mirror/class-inl.h"
37#include "mirror/object_array-inl.h"
38#include "mirror/object-inl.h"
39#include "mirror/string.h"
40#include "oat_file-inl.h"
41#include "scoped_thread_state_change.h"
42#include "well_known_classes.h"
43
44namespace art {
45
46extern "C" void art_quick_invoke_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
47                                      const char*);
48extern "C" void art_quick_invoke_static_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
49                                             const char*);
50
51ArtMethod* ArtMethod::FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable& soa,
52                                          jobject jlr_method) {
53  auto* abstract_method = soa.Decode<mirror::AbstractMethod*>(jlr_method);
54  DCHECK(abstract_method != nullptr);
55  return abstract_method->GetArtMethod();
56}
57
58mirror::String* ArtMethod::GetNameAsString(Thread* self) {
59  CHECK(!IsProxyMethod());
60  StackHandleScope<1> hs(self);
61  Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache()));
62  auto* dex_file = dex_cache->GetDexFile();
63  uint32_t dex_method_idx = GetDexMethodIndex();
64  const DexFile::MethodId& method_id = dex_file->GetMethodId(dex_method_idx);
65  return Runtime::Current()->GetClassLinker()->ResolveString(*dex_file, method_id.name_idx_,
66                                                             dex_cache);
67}
68
69void ArtMethod::ThrowInvocationTimeError() {
70  DCHECK(!IsInvokable());
71  // NOTE: IsDefaultConflicting must be first since the actual method might or might not be abstract
72  //       due to the way we select it.
73  if (IsDefaultConflicting()) {
74    ThrowIncompatibleClassChangeErrorForMethodConflict(this);
75  } else {
76    DCHECK(IsAbstract());
77    ThrowAbstractMethodError(this);
78  }
79}
80
81InvokeType ArtMethod::GetInvokeType() {
82  // TODO: kSuper?
83  if (GetDeclaringClass()->IsInterface()) {
84    return kInterface;
85  } else if (IsStatic()) {
86    return kStatic;
87  } else if (IsDirect()) {
88    return kDirect;
89  } else {
90    return kVirtual;
91  }
92}
93
94size_t ArtMethod::NumArgRegisters(const StringPiece& shorty) {
95  CHECK_LE(1U, shorty.length());
96  uint32_t num_registers = 0;
97  for (size_t i = 1; i < shorty.length(); ++i) {
98    char ch = shorty[i];
99    if (ch == 'D' || ch == 'J') {
100      num_registers += 2;
101    } else {
102      num_registers += 1;
103    }
104  }
105  return num_registers;
106}
107
108bool ArtMethod::HasSameNameAndSignature(ArtMethod* other) {
109  ScopedAssertNoThreadSuspension ants(Thread::Current(), "HasSameNameAndSignature");
110  const DexFile* dex_file = GetDexFile();
111  const DexFile::MethodId& mid = dex_file->GetMethodId(GetDexMethodIndex());
112  if (GetDexCache() == other->GetDexCache()) {
113    const DexFile::MethodId& mid2 = dex_file->GetMethodId(other->GetDexMethodIndex());
114    return mid.name_idx_ == mid2.name_idx_ && mid.proto_idx_ == mid2.proto_idx_;
115  }
116  const DexFile* dex_file2 = other->GetDexFile();
117  const DexFile::MethodId& mid2 = dex_file2->GetMethodId(other->GetDexMethodIndex());
118  if (!DexFileStringEquals(dex_file, mid.name_idx_, dex_file2, mid2.name_idx_)) {
119    return false;  // Name mismatch.
120  }
121  return dex_file->GetMethodSignature(mid) == dex_file2->GetMethodSignature(mid2);
122}
123
124ArtMethod* ArtMethod::FindOverriddenMethod(size_t pointer_size) {
125  if (IsStatic()) {
126    return nullptr;
127  }
128  mirror::Class* declaring_class = GetDeclaringClass();
129  mirror::Class* super_class = declaring_class->GetSuperClass();
130  uint16_t method_index = GetMethodIndex();
131  ArtMethod* result = nullptr;
132  // Did this method override a super class method? If so load the result from the super class'
133  // vtable
134  if (super_class->HasVTable() && method_index < super_class->GetVTableLength()) {
135    result = super_class->GetVTableEntry(method_index, pointer_size);
136  } else {
137    // Method didn't override superclass method so search interfaces
138    if (IsProxyMethod()) {
139      result = mirror::DexCache::GetElementPtrSize(GetDexCacheResolvedMethods(pointer_size),
140                                                   GetDexMethodIndex(),
141                                                   pointer_size);
142      CHECK_EQ(result,
143               Runtime::Current()->GetClassLinker()->FindMethodForProxy(GetDeclaringClass(), this));
144    } else {
145      mirror::IfTable* iftable = GetDeclaringClass()->GetIfTable();
146      for (size_t i = 0; i < iftable->Count() && result == nullptr; i++) {
147        mirror::Class* interface = iftable->GetInterface(i);
148        for (ArtMethod& interface_method : interface->GetVirtualMethods(pointer_size)) {
149          if (HasSameNameAndSignature(interface_method.GetInterfaceMethodIfProxy(pointer_size))) {
150            result = &interface_method;
151            break;
152          }
153        }
154      }
155    }
156  }
157  DCHECK(result == nullptr ||
158         GetInterfaceMethodIfProxy(pointer_size)->HasSameNameAndSignature(
159             result->GetInterfaceMethodIfProxy(pointer_size)));
160  return result;
161}
162
163uint32_t ArtMethod::FindDexMethodIndexInOtherDexFile(const DexFile& other_dexfile,
164                                                     uint32_t name_and_signature_idx) {
165  const DexFile* dexfile = GetDexFile();
166  const uint32_t dex_method_idx = GetDexMethodIndex();
167  const DexFile::MethodId& mid = dexfile->GetMethodId(dex_method_idx);
168  const DexFile::MethodId& name_and_sig_mid = other_dexfile.GetMethodId(name_and_signature_idx);
169  DCHECK_STREQ(dexfile->GetMethodName(mid), other_dexfile.GetMethodName(name_and_sig_mid));
170  DCHECK_EQ(dexfile->GetMethodSignature(mid), other_dexfile.GetMethodSignature(name_and_sig_mid));
171  if (dexfile == &other_dexfile) {
172    return dex_method_idx;
173  }
174  const char* mid_declaring_class_descriptor = dexfile->StringByTypeIdx(mid.class_idx_);
175  const DexFile::TypeId* other_type_id = other_dexfile.FindTypeId(mid_declaring_class_descriptor);
176  if (other_type_id != nullptr) {
177    const DexFile::MethodId* other_mid = other_dexfile.FindMethodId(
178        *other_type_id, other_dexfile.GetStringId(name_and_sig_mid.name_idx_),
179        other_dexfile.GetProtoId(name_and_sig_mid.proto_idx_));
180    if (other_mid != nullptr) {
181      return other_dexfile.GetIndexForMethodId(*other_mid);
182    }
183  }
184  return DexFile::kDexNoIndex;
185}
186
187uint32_t ArtMethod::FindCatchBlock(Handle<mirror::Class> exception_type,
188                                   uint32_t dex_pc, bool* has_no_move_exception) {
189  const DexFile::CodeItem* code_item = GetCodeItem();
190  // Set aside the exception while we resolve its type.
191  Thread* self = Thread::Current();
192  StackHandleScope<1> hs(self);
193  Handle<mirror::Throwable> exception(hs.NewHandle(self->GetException()));
194  self->ClearException();
195  // Default to handler not found.
196  uint32_t found_dex_pc = DexFile::kDexNoIndex;
197  // Iterate over the catch handlers associated with dex_pc.
198  size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
199  for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) {
200    uint16_t iter_type_idx = it.GetHandlerTypeIndex();
201    // Catch all case
202    if (iter_type_idx == DexFile::kDexNoIndex16) {
203      found_dex_pc = it.GetHandlerAddress();
204      break;
205    }
206    // Does this catch exception type apply?
207    mirror::Class* iter_exception_type = GetClassFromTypeIndex(iter_type_idx,
208                                                               true /* resolve */,
209                                                               pointer_size);
210    if (UNLIKELY(iter_exception_type == nullptr)) {
211      // Now have a NoClassDefFoundError as exception. Ignore in case the exception class was
212      // removed by a pro-guard like tool.
213      // Note: this is not RI behavior. RI would have failed when loading the class.
214      self->ClearException();
215      // Delete any long jump context as this routine is called during a stack walk which will
216      // release its in use context at the end.
217      delete self->GetLongJumpContext();
218      LOG(WARNING) << "Unresolved exception class when finding catch block: "
219        << DescriptorToDot(GetTypeDescriptorFromTypeIdx(iter_type_idx));
220    } else if (iter_exception_type->IsAssignableFrom(exception_type.Get())) {
221      found_dex_pc = it.GetHandlerAddress();
222      break;
223    }
224  }
225  if (found_dex_pc != DexFile::kDexNoIndex) {
226    const Instruction* first_catch_instr =
227        Instruction::At(&code_item->insns_[found_dex_pc]);
228    *has_no_move_exception = (first_catch_instr->Opcode() != Instruction::MOVE_EXCEPTION);
229  }
230  // Put the exception back.
231  if (exception.Get() != nullptr) {
232    self->SetException(exception.Get());
233  }
234  return found_dex_pc;
235}
236
237void ArtMethod::Invoke(Thread* self, uint32_t* args, uint32_t args_size, JValue* result,
238                       const char* shorty) {
239  if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEnd())) {
240    ThrowStackOverflowError(self);
241    return;
242  }
243
244  if (kIsDebugBuild) {
245    self->AssertThreadSuspensionIsAllowable();
246    CHECK_EQ(kRunnable, self->GetState());
247    CHECK_STREQ(GetInterfaceMethodIfProxy(sizeof(void*))->GetShorty(), shorty);
248  }
249
250  // Push a transition back into managed code onto the linked list in thread.
251  ManagedStack fragment;
252  self->PushManagedStackFragment(&fragment);
253
254  Runtime* runtime = Runtime::Current();
255  // Call the invoke stub, passing everything as arguments.
256  // If the runtime is not yet started or it is required by the debugger, then perform the
257  // Invocation by the interpreter.
258  if (UNLIKELY(!runtime->IsStarted() || Dbg::IsForcedInterpreterNeededForCalling(self, this))) {
259    if (IsStatic()) {
260      art::interpreter::EnterInterpreterFromInvoke(self, this, nullptr, args, result);
261    } else {
262      mirror::Object* receiver =
263          reinterpret_cast<StackReference<mirror::Object>*>(&args[0])->AsMirrorPtr();
264      art::interpreter::EnterInterpreterFromInvoke(self, this, receiver, args + 1, result);
265    }
266  } else {
267    DCHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), sizeof(void*));
268
269    constexpr bool kLogInvocationStartAndReturn = false;
270    bool have_quick_code = GetEntryPointFromQuickCompiledCode() != nullptr;
271    if (LIKELY(have_quick_code)) {
272      if (kLogInvocationStartAndReturn) {
273        LOG(INFO) << StringPrintf(
274            "Invoking '%s' quick code=%p static=%d", PrettyMethod(this).c_str(),
275            GetEntryPointFromQuickCompiledCode(), static_cast<int>(IsStatic() ? 1 : 0));
276      }
277
278      // Ensure that we won't be accidentally calling quick compiled code when -Xint.
279      if (kIsDebugBuild && runtime->GetInstrumentation()->IsForcedInterpretOnly()) {
280        CHECK(!runtime->UseJit());
281        const void* oat_quick_code = runtime->GetClassLinker()->GetOatMethodQuickCodeFor(this);
282        CHECK(oat_quick_code == nullptr || oat_quick_code != GetEntryPointFromQuickCompiledCode())
283            << "Don't call compiled code when -Xint " << PrettyMethod(this);
284      }
285
286      if (!IsStatic()) {
287        (*art_quick_invoke_stub)(this, args, args_size, self, result, shorty);
288      } else {
289        (*art_quick_invoke_static_stub)(this, args, args_size, self, result, shorty);
290      }
291      if (UNLIKELY(self->GetException() == Thread::GetDeoptimizationException())) {
292        // Unusual case where we were running generated code and an
293        // exception was thrown to force the activations to be removed from the
294        // stack. Continue execution in the interpreter.
295        self->ClearException();
296        ShadowFrame* shadow_frame =
297            self->PopStackedShadowFrame(StackedShadowFrameType::kDeoptimizationShadowFrame);
298        mirror::Throwable* pending_exception = nullptr;
299        bool from_code = false;
300        self->PopDeoptimizationContext(result, &pending_exception, &from_code);
301        CHECK(!from_code);
302        self->SetTopOfStack(nullptr);
303        self->SetTopOfShadowStack(shadow_frame);
304
305        // Restore the exception that was pending before deoptimization then interpret the
306        // deoptimized frames.
307        if (pending_exception != nullptr) {
308          self->SetException(pending_exception);
309        }
310        interpreter::EnterInterpreterFromDeoptimize(self, shadow_frame, from_code, result);
311      }
312      if (kLogInvocationStartAndReturn) {
313        LOG(INFO) << StringPrintf("Returned '%s' quick code=%p", PrettyMethod(this).c_str(),
314                                  GetEntryPointFromQuickCompiledCode());
315      }
316    } else {
317      LOG(INFO) << "Not invoking '" << PrettyMethod(this) << "' code=null";
318      if (result != nullptr) {
319        result->SetJ(0);
320      }
321    }
322  }
323
324  // Pop transition.
325  self->PopManagedStackFragment(fragment);
326}
327
328void ArtMethod::RegisterNative(const void* native_method, bool is_fast) {
329  CHECK(IsNative()) << PrettyMethod(this);
330  CHECK(!IsFastNative()) << PrettyMethod(this);
331  CHECK(native_method != nullptr) << PrettyMethod(this);
332  if (is_fast) {
333    SetAccessFlags(GetAccessFlags() | kAccFastNative);
334  }
335  SetEntryPointFromJni(native_method);
336}
337
338void ArtMethod::UnregisterNative() {
339  CHECK(IsNative() && !IsFastNative()) << PrettyMethod(this);
340  // restore stub to lookup native pointer via dlsym
341  RegisterNative(GetJniDlsymLookupStub(), false);
342}
343
344bool ArtMethod::IsOverridableByDefaultMethod() {
345  return GetDeclaringClass()->IsInterface();
346}
347
348bool ArtMethod::EqualParameters(Handle<mirror::ObjectArray<mirror::Class>> params) {
349  auto* dex_cache = GetDexCache();
350  auto* dex_file = dex_cache->GetDexFile();
351  const auto& method_id = dex_file->GetMethodId(GetDexMethodIndex());
352  const auto& proto_id = dex_file->GetMethodPrototype(method_id);
353  const DexFile::TypeList* proto_params = dex_file->GetProtoParameters(proto_id);
354  auto count = proto_params != nullptr ? proto_params->Size() : 0u;
355  auto param_len = params.Get() != nullptr ? params->GetLength() : 0u;
356  if (param_len != count) {
357    return false;
358  }
359  auto* cl = Runtime::Current()->GetClassLinker();
360  for (size_t i = 0; i < count; ++i) {
361    auto type_idx = proto_params->GetTypeItem(i).type_idx_;
362    auto* type = cl->ResolveType(type_idx, this);
363    if (type == nullptr) {
364      Thread::Current()->AssertPendingException();
365      return false;
366    }
367    if (type != params->GetWithoutChecks(i)) {
368      return false;
369    }
370  }
371  return true;
372}
373
374const uint8_t* ArtMethod::GetQuickenedInfo() {
375  bool found = false;
376  OatFile::OatMethod oat_method =
377      Runtime::Current()->GetClassLinker()->FindOatMethodFor(this, &found);
378  if (!found || (oat_method.GetQuickCode() != nullptr)) {
379    return nullptr;
380  }
381  return oat_method.GetVmapTable();
382}
383
384const OatQuickMethodHeader* ArtMethod::GetOatQuickMethodHeader(uintptr_t pc) {
385  // Our callers should make sure they don't pass the instrumentation exit pc,
386  // as this method does not look at the side instrumentation stack.
387  DCHECK_NE(pc, reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()));
388
389  if (IsRuntimeMethod()) {
390    return nullptr;
391  }
392
393  Runtime* runtime = Runtime::Current();
394  const void* existing_entry_point = GetEntryPointFromQuickCompiledCode();
395  DCHECK(existing_entry_point != nullptr);
396  ClassLinker* class_linker = runtime->GetClassLinker();
397
398  if (class_linker->IsQuickGenericJniStub(existing_entry_point)) {
399    // The generic JNI does not have any method header.
400    return nullptr;
401  }
402
403  if (existing_entry_point == GetQuickProxyInvokeHandler()) {
404    DCHECK(IsProxyMethod() && !IsConstructor());
405    // The proxy entry point does not have any method header.
406    return nullptr;
407  }
408
409  // Check whether the current entry point contains this pc.
410  if (!class_linker->IsQuickResolutionStub(existing_entry_point) &&
411      !class_linker->IsQuickToInterpreterBridge(existing_entry_point)) {
412    OatQuickMethodHeader* method_header =
413        OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
414
415    if (method_header->Contains(pc)) {
416      return method_header;
417    }
418  }
419
420  // Check whether the pc is in the JIT code cache.
421  jit::Jit* jit = Runtime::Current()->GetJit();
422  if (jit != nullptr) {
423    jit::JitCodeCache* code_cache = jit->GetCodeCache();
424    OatQuickMethodHeader* method_header = code_cache->LookupMethodHeader(pc, this);
425    if (method_header != nullptr) {
426      DCHECK(method_header->Contains(pc));
427      return method_header;
428    } else {
429      DCHECK(!code_cache->ContainsPc(reinterpret_cast<const void*>(pc))) << std::hex << pc;
430    }
431  }
432
433  // The code has to be in an oat file.
434  bool found;
435  OatFile::OatMethod oat_method = class_linker->FindOatMethodFor(this, &found);
436  if (!found) {
437    if (class_linker->IsQuickResolutionStub(existing_entry_point)) {
438      // We are running the generic jni stub, but the entry point of the method has not
439      // been updated yet.
440      DCHECK_EQ(pc, 0u) << "Should be a downcall";
441      DCHECK(IsNative());
442      return nullptr;
443    }
444    if (existing_entry_point == GetQuickInstrumentationEntryPoint()) {
445      // We are running the generic jni stub, but the method is being instrumented.
446      DCHECK_EQ(pc, 0u) << "Should be a downcall";
447      DCHECK(IsNative());
448      return nullptr;
449    }
450    // Only for unit tests.
451    // TODO(ngeoffray): Update these tests to pass the right pc?
452    return OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
453  }
454  const void* oat_entry_point = oat_method.GetQuickCode();
455  if (oat_entry_point == nullptr || class_linker->IsQuickGenericJniStub(oat_entry_point)) {
456    DCHECK(IsNative()) << PrettyMethod(this);
457    return nullptr;
458  }
459
460  OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromEntryPoint(oat_entry_point);
461  if (pc == 0) {
462    // This is a downcall, it can only happen for a native method.
463    DCHECK(IsNative());
464    return method_header;
465  }
466
467  DCHECK(method_header->Contains(pc))
468      << PrettyMethod(this)
469      << std::hex << pc << " " << oat_entry_point
470      << " " << (uintptr_t)(method_header->code_ + method_header->code_size_);
471  return method_header;
472}
473
474bool ArtMethod::HasAnyCompiledCode() {
475  // Check whether the JIT has compiled it.
476  jit::Jit* jit = Runtime::Current()->GetJit();
477  if (jit != nullptr && jit->GetCodeCache()->ContainsMethod(this)) {
478    return true;
479  }
480
481  // Check whether we have AOT code.
482  return Runtime::Current()->GetClassLinker()->GetOatMethodQuickCodeFor(this) != nullptr;
483}
484
485void ArtMethod::CopyFrom(ArtMethod* src, size_t image_pointer_size) {
486  memcpy(reinterpret_cast<void*>(this), reinterpret_cast<const void*>(src),
487         Size(image_pointer_size));
488  declaring_class_ = GcRoot<mirror::Class>(const_cast<ArtMethod*>(src)->GetDeclaringClass());
489
490  // If the entry point of the method we are copying from is from JIT code, we just
491  // put the entry point of the new method to interpreter. We could set the entry point
492  // to the JIT code, but this would require taking the JIT code cache lock to notify
493  // it, which we do not want at this level.
494  Runtime* runtime = Runtime::Current();
495  if (runtime->GetJit() != nullptr) {
496    if (runtime->GetJit()->GetCodeCache()->ContainsPc(GetEntryPointFromQuickCompiledCode())) {
497      SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(), image_pointer_size);
498    }
499  }
500  // Clear the profiling info for the same reasons as the JIT code.
501  if (!src->IsNative()) {
502    SetProfilingInfoPtrSize(nullptr, image_pointer_size);
503  }
504  // Clear hotness to let the JIT properly decide when to compile this method.
505  hotness_count_ = 0;
506}
507
508}  // namespace art
509