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-inl.h"
24 #include "dex_file-inl.h"
25 #include "dex_instruction.h"
26 #include "gc/accounting/card_table-inl.h"
27 #include "interpreter/interpreter.h"
28 #include "jni_internal.h"
29 #include "mapping_table.h"
30 #include "method_helper-inl.h"
31 #include "object_array-inl.h"
32 #include "object_array.h"
33 #include "object-inl.h"
34 #include "scoped_thread_state_change.h"
35 #include "string.h"
36 #include "well_known_classes.h"
37
38 namespace art {
39 namespace mirror {
40
41 extern "C" void art_portable_invoke_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*, char);
42 extern "C" void art_quick_invoke_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
43 const char*);
44 #ifdef __LP64__
45 extern "C" void art_quick_invoke_static_stub(ArtMethod*, uint32_t*, uint32_t, Thread*, JValue*,
46 const char*);
47 #endif
48
49 // TODO: get global references for these
50 GcRoot<Class> ArtMethod::java_lang_reflect_ArtMethod_;
51
FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable & soa,jobject jlr_method)52 ArtMethod* ArtMethod::FromReflectedMethod(const ScopedObjectAccessAlreadyRunnable& soa,
53 jobject jlr_method) {
54 mirror::ArtField* f =
55 soa.DecodeField(WellKnownClasses::java_lang_reflect_AbstractMethod_artMethod);
56 mirror::ArtMethod* method = f->GetObject(soa.Decode<mirror::Object*>(jlr_method))->AsArtMethod();
57 DCHECK(method != nullptr);
58 return method;
59 }
60
61
VisitRoots(RootCallback * callback,void * arg)62 void ArtMethod::VisitRoots(RootCallback* callback, void* arg) {
63 if (!java_lang_reflect_ArtMethod_.IsNull()) {
64 java_lang_reflect_ArtMethod_.VisitRoot(callback, arg, 0, kRootStickyClass);
65 }
66 }
67
GetInvokeType()68 InvokeType ArtMethod::GetInvokeType() {
69 // TODO: kSuper?
70 if (GetDeclaringClass()->IsInterface()) {
71 return kInterface;
72 } else if (IsStatic()) {
73 return kStatic;
74 } else if (IsDirect()) {
75 return kDirect;
76 } else {
77 return kVirtual;
78 }
79 }
80
SetClass(Class * java_lang_reflect_ArtMethod)81 void ArtMethod::SetClass(Class* java_lang_reflect_ArtMethod) {
82 CHECK(java_lang_reflect_ArtMethod_.IsNull());
83 CHECK(java_lang_reflect_ArtMethod != NULL);
84 java_lang_reflect_ArtMethod_ = GcRoot<Class>(java_lang_reflect_ArtMethod);
85 }
86
ResetClass()87 void ArtMethod::ResetClass() {
88 CHECK(!java_lang_reflect_ArtMethod_.IsNull());
89 java_lang_reflect_ArtMethod_ = GcRoot<Class>(nullptr);
90 }
91
SetDexCacheStrings(ObjectArray<String> * new_dex_cache_strings)92 void ArtMethod::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
93 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(ArtMethod, dex_cache_strings_),
94 new_dex_cache_strings);
95 }
96
SetDexCacheResolvedMethods(ObjectArray<ArtMethod> * new_dex_cache_methods)97 void ArtMethod::SetDexCacheResolvedMethods(ObjectArray<ArtMethod>* new_dex_cache_methods) {
98 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(ArtMethod, dex_cache_resolved_methods_),
99 new_dex_cache_methods);
100 }
101
SetDexCacheResolvedTypes(ObjectArray<Class> * new_dex_cache_classes)102 void ArtMethod::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
103 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(ArtMethod, dex_cache_resolved_types_),
104 new_dex_cache_classes);
105 }
106
NumArgRegisters(const StringPiece & shorty)107 size_t ArtMethod::NumArgRegisters(const StringPiece& shorty) {
108 CHECK_LE(1, shorty.length());
109 uint32_t num_registers = 0;
110 for (int i = 1; i < shorty.length(); ++i) {
111 char ch = shorty[i];
112 if (ch == 'D' || ch == 'J') {
113 num_registers += 2;
114 } else {
115 num_registers += 1;
116 }
117 }
118 return num_registers;
119 }
120
IsProxyMethod()121 bool ArtMethod::IsProxyMethod() {
122 return GetDeclaringClass()->IsProxyClass();
123 }
124
FindOverriddenMethod()125 ArtMethod* ArtMethod::FindOverriddenMethod() {
126 if (IsStatic()) {
127 return NULL;
128 }
129 Class* declaring_class = GetDeclaringClass();
130 Class* super_class = declaring_class->GetSuperClass();
131 uint16_t method_index = GetMethodIndex();
132 ArtMethod* result = NULL;
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);
137 } else {
138 // Method didn't override superclass method so search interfaces
139 if (IsProxyMethod()) {
140 result = GetDexCacheResolvedMethods()->Get(GetDexMethodIndex());
141 CHECK_EQ(result,
142 Runtime::Current()->GetClassLinker()->FindMethodForProxy(GetDeclaringClass(), this));
143 } else {
144 StackHandleScope<2> hs(Thread::Current());
145 MethodHelper mh(hs.NewHandle(this));
146 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
147 IfTable* iftable = GetDeclaringClass()->GetIfTable();
148 for (size_t i = 0; i < iftable->Count() && result == NULL; i++) {
149 Class* interface = iftable->GetInterface(i);
150 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
151 interface_mh.ChangeMethod(interface->GetVirtualMethod(j));
152 if (mh.HasSameNameAndSignature(&interface_mh)) {
153 result = interface_mh.GetMethod();
154 break;
155 }
156 }
157 }
158 }
159 }
160 if (kIsDebugBuild) {
161 StackHandleScope<2> hs(Thread::Current());
162 MethodHelper result_mh(hs.NewHandle(result));
163 MethodHelper this_mh(hs.NewHandle(this));
164 DCHECK(result == nullptr || this_mh.HasSameNameAndSignature(&result_mh));
165 }
166 return result;
167 }
168
ToDexPc(const uintptr_t pc,bool abort_on_failure)169 uint32_t ArtMethod::ToDexPc(const uintptr_t pc, bool abort_on_failure) {
170 if (IsPortableCompiled()) {
171 // Portable doesn't use the machine pc, we just use dex pc instead.
172 return static_cast<uint32_t>(pc);
173 }
174 const void* entry_point = GetQuickOatEntryPoint();
175 MappingTable table(
176 entry_point != nullptr ? GetMappingTable(EntryPointToCodePointer(entry_point)) : nullptr);
177 if (table.TotalSize() == 0) {
178 // NOTE: Special methods (see Mir2Lir::GenSpecialCase()) have an empty mapping
179 // but they have no suspend checks and, consequently, we never call ToDexPc() for them.
180 DCHECK(IsNative() || IsCalleeSaveMethod() || IsProxyMethod()) << PrettyMethod(this);
181 return DexFile::kDexNoIndex; // Special no mapping case
182 }
183 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(entry_point);
184 // Assume the caller wants a pc-to-dex mapping so check here first.
185 typedef MappingTable::PcToDexIterator It;
186 for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
187 if (cur.NativePcOffset() == sought_offset) {
188 return cur.DexPc();
189 }
190 }
191 // Now check dex-to-pc mappings.
192 typedef MappingTable::DexToPcIterator It2;
193 for (It2 cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
194 if (cur.NativePcOffset() == sought_offset) {
195 return cur.DexPc();
196 }
197 }
198 if (abort_on_failure) {
199 LOG(FATAL) << "Failed to find Dex offset for PC offset " << reinterpret_cast<void*>(sought_offset)
200 << "(PC " << reinterpret_cast<void*>(pc) << ", entry_point=" << entry_point
201 << ") in " << PrettyMethod(this);
202 }
203 return DexFile::kDexNoIndex;
204 }
205
ToNativePc(const uint32_t dex_pc)206 uintptr_t ArtMethod::ToNativePc(const uint32_t dex_pc) {
207 const void* entry_point = GetQuickOatEntryPoint();
208 MappingTable table(
209 entry_point != nullptr ? GetMappingTable(EntryPointToCodePointer(entry_point)) : nullptr);
210 if (table.TotalSize() == 0) {
211 DCHECK_EQ(dex_pc, 0U);
212 return 0; // Special no mapping/pc == 0 case
213 }
214 // Assume the caller wants a dex-to-pc mapping so check here first.
215 typedef MappingTable::DexToPcIterator It;
216 for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
217 if (cur.DexPc() == dex_pc) {
218 return reinterpret_cast<uintptr_t>(entry_point) + cur.NativePcOffset();
219 }
220 }
221 // Now check pc-to-dex mappings.
222 typedef MappingTable::PcToDexIterator It2;
223 for (It2 cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
224 if (cur.DexPc() == dex_pc) {
225 return reinterpret_cast<uintptr_t>(entry_point) + cur.NativePcOffset();
226 }
227 }
228 LOG(FATAL) << "Failed to find native offset for dex pc 0x" << std::hex << dex_pc
229 << " in " << PrettyMethod(this);
230 return 0;
231 }
232
FindCatchBlock(Handle<ArtMethod> h_this,Handle<Class> exception_type,uint32_t dex_pc,bool * has_no_move_exception)233 uint32_t ArtMethod::FindCatchBlock(Handle<ArtMethod> h_this, Handle<Class> exception_type,
234 uint32_t dex_pc, bool* has_no_move_exception) {
235 MethodHelper mh(h_this);
236 const DexFile::CodeItem* code_item = h_this->GetCodeItem();
237 // Set aside the exception while we resolve its type.
238 Thread* self = Thread::Current();
239 ThrowLocation throw_location;
240 StackHandleScope<1> hs(self);
241 Handle<mirror::Throwable> exception(hs.NewHandle(self->GetException(&throw_location)));
242 bool is_exception_reported = self->IsExceptionReportedToInstrumentation();
243 self->ClearException();
244 // Default to handler not found.
245 uint32_t found_dex_pc = DexFile::kDexNoIndex;
246 // Iterate over the catch handlers associated with dex_pc.
247 for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) {
248 uint16_t iter_type_idx = it.GetHandlerTypeIndex();
249 // Catch all case
250 if (iter_type_idx == DexFile::kDexNoIndex16) {
251 found_dex_pc = it.GetHandlerAddress();
252 break;
253 }
254 // Does this catch exception type apply?
255 Class* iter_exception_type = mh.GetClassFromTypeIdx(iter_type_idx);
256 if (UNLIKELY(iter_exception_type == nullptr)) {
257 // Now have a NoClassDefFoundError as exception. Ignore in case the exception class was
258 // removed by a pro-guard like tool.
259 // Note: this is not RI behavior. RI would have failed when loading the class.
260 self->ClearException();
261 // Delete any long jump context as this routine is called during a stack walk which will
262 // release its in use context at the end.
263 delete self->GetLongJumpContext();
264 LOG(WARNING) << "Unresolved exception class when finding catch block: "
265 << DescriptorToDot(h_this->GetTypeDescriptorFromTypeIdx(iter_type_idx));
266 } else if (iter_exception_type->IsAssignableFrom(exception_type.Get())) {
267 found_dex_pc = it.GetHandlerAddress();
268 break;
269 }
270 }
271 if (found_dex_pc != DexFile::kDexNoIndex) {
272 const Instruction* first_catch_instr =
273 Instruction::At(&code_item->insns_[found_dex_pc]);
274 *has_no_move_exception = (first_catch_instr->Opcode() != Instruction::MOVE_EXCEPTION);
275 }
276 // Put the exception back.
277 if (exception.Get() != nullptr) {
278 self->SetException(throw_location, exception.Get());
279 self->SetExceptionReportedToInstrumentation(is_exception_reported);
280 }
281 return found_dex_pc;
282 }
283
Invoke(Thread * self,uint32_t * args,uint32_t args_size,JValue * result,const char * shorty)284 void ArtMethod::Invoke(Thread* self, uint32_t* args, uint32_t args_size, JValue* result,
285 const char* shorty) {
286 if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEnd())) {
287 ThrowStackOverflowError(self);
288 return;
289 }
290
291 if (kIsDebugBuild) {
292 self->AssertThreadSuspensionIsAllowable();
293 CHECK_EQ(kRunnable, self->GetState());
294 CHECK_STREQ(GetShorty(), shorty);
295 }
296
297 // Push a transition back into managed code onto the linked list in thread.
298 ManagedStack fragment;
299 self->PushManagedStackFragment(&fragment);
300
301 Runtime* runtime = Runtime::Current();
302 // Call the invoke stub, passing everything as arguments.
303 if (UNLIKELY(!runtime->IsStarted())) {
304 if (IsStatic()) {
305 art::interpreter::EnterInterpreterFromInvoke(self, this, nullptr, args, result);
306 } else {
307 Object* receiver = reinterpret_cast<StackReference<Object>*>(&args[0])->AsMirrorPtr();
308 art::interpreter::EnterInterpreterFromInvoke(self, this, receiver, args + 1, result);
309 }
310 } else {
311 const bool kLogInvocationStartAndReturn = false;
312 bool have_quick_code = GetEntryPointFromQuickCompiledCode() != nullptr;
313 #if defined(ART_USE_PORTABLE_COMPILER)
314 bool have_portable_code = GetEntryPointFromPortableCompiledCode() != nullptr;
315 #else
316 bool have_portable_code = false;
317 #endif
318 if (LIKELY(have_quick_code || have_portable_code)) {
319 if (kLogInvocationStartAndReturn) {
320 LOG(INFO) << StringPrintf("Invoking '%s' %s code=%p", PrettyMethod(this).c_str(),
321 have_quick_code ? "quick" : "portable",
322 have_quick_code ? GetEntryPointFromQuickCompiledCode()
323 #if defined(ART_USE_PORTABLE_COMPILER)
324 : GetEntryPointFromPortableCompiledCode());
325 #else
326 : nullptr);
327 #endif
328 }
329 if (!IsPortableCompiled()) {
330 #ifdef __LP64__
331 if (!IsStatic()) {
332 (*art_quick_invoke_stub)(this, args, args_size, self, result, shorty);
333 } else {
334 (*art_quick_invoke_static_stub)(this, args, args_size, self, result, shorty);
335 }
336 #else
337 (*art_quick_invoke_stub)(this, args, args_size, self, result, shorty);
338 #endif
339 } else {
340 (*art_portable_invoke_stub)(this, args, args_size, self, result, shorty[0]);
341 }
342 if (UNLIKELY(self->GetException(nullptr) == Thread::GetDeoptimizationException())) {
343 // Unusual case where we were running generated code and an
344 // exception was thrown to force the activations to be removed from the
345 // stack. Continue execution in the interpreter.
346 self->ClearException();
347 ShadowFrame* shadow_frame = self->GetAndClearDeoptimizationShadowFrame(result);
348 self->SetTopOfStack(nullptr, 0);
349 self->SetTopOfShadowStack(shadow_frame);
350 interpreter::EnterInterpreterFromDeoptimize(self, shadow_frame, result);
351 }
352 if (kLogInvocationStartAndReturn) {
353 LOG(INFO) << StringPrintf("Returned '%s' %s code=%p", PrettyMethod(this).c_str(),
354 have_quick_code ? "quick" : "portable",
355 have_quick_code ? GetEntryPointFromQuickCompiledCode()
356 #if defined(ART_USE_PORTABLE_COMPILER)
357 : GetEntryPointFromPortableCompiledCode());
358 #else
359 : nullptr);
360 #endif
361 }
362 } else {
363 LOG(INFO) << "Not invoking '" << PrettyMethod(this) << "' code=null";
364 if (result != NULL) {
365 result->SetJ(0);
366 }
367 }
368 }
369
370 // Pop transition.
371 self->PopManagedStackFragment(fragment);
372 }
373
RegisterNative(Thread * self,const void * native_method,bool is_fast)374 void ArtMethod::RegisterNative(Thread* self, const void* native_method, bool is_fast) {
375 DCHECK(Thread::Current() == self);
376 CHECK(IsNative()) << PrettyMethod(this);
377 CHECK(!IsFastNative()) << PrettyMethod(this);
378 CHECK(native_method != NULL) << PrettyMethod(this);
379 if (is_fast) {
380 SetAccessFlags(GetAccessFlags() | kAccFastNative);
381 }
382 SetNativeMethod(native_method);
383 }
384
UnregisterNative(Thread * self)385 void ArtMethod::UnregisterNative(Thread* self) {
386 CHECK(IsNative() && !IsFastNative()) << PrettyMethod(this);
387 // restore stub to lookup native pointer via dlsym
388 RegisterNative(self, GetJniDlsymLookupStub(), false);
389 }
390
391 } // namespace mirror
392 } // namespace art
393