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