1 /*
2 * Copyright (C) 2012 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 #ifndef ART_RUNTIME_ENTRYPOINTS_ENTRYPOINT_UTILS_INL_H_
18 #define ART_RUNTIME_ENTRYPOINTS_ENTRYPOINT_UTILS_INL_H_
19
20 #include "entrypoint_utils.h"
21
22 #include "art_field-inl.h"
23 #include "art_method-inl.h"
24 #include "base/enums.h"
25 #include "base/sdk_version.h"
26 #include "class_linker-inl.h"
27 #include "common_throws.h"
28 #include "dex/dex_file.h"
29 #include "dex/invoke_type.h"
30 #include "entrypoints/quick/callee_save_frame.h"
31 #include "handle_scope-inl.h"
32 #include "imt_conflict_table.h"
33 #include "imtable-inl.h"
34 #include "indirect_reference_table.h"
35 #include "jni/jni_internal.h"
36 #include "mirror/array-alloc-inl.h"
37 #include "mirror/class-alloc-inl.h"
38 #include "mirror/class-inl.h"
39 #include "mirror/object-inl.h"
40 #include "mirror/throwable.h"
41 #include "nth_caller_visitor.h"
42 #include "runtime.h"
43 #include "stack_map.h"
44 #include "thread.h"
45 #include "well_known_classes.h"
46
47 namespace art {
48
GetResolvedMethod(ArtMethod * outer_method,const CodeInfo & code_info,const BitTableRange<InlineInfo> & inline_infos)49 inline ArtMethod* GetResolvedMethod(ArtMethod* outer_method,
50 const CodeInfo& code_info,
51 const BitTableRange<InlineInfo>& inline_infos)
52 REQUIRES_SHARED(Locks::mutator_lock_) {
53 DCHECK(!outer_method->IsObsolete());
54
55 // This method is being used by artQuickResolutionTrampoline, before it sets up
56 // the passed parameters in a GC friendly way. Therefore we must never be
57 // suspended while executing it.
58 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
59
60 {
61 InlineInfo inline_info = inline_infos.back();
62
63 if (inline_info.EncodesArtMethod()) {
64 return inline_info.GetArtMethod();
65 }
66
67 uint32_t method_index = code_info.GetMethodIndexOf(inline_info);
68 if (inline_info.GetDexPc() == static_cast<uint32_t>(-1)) {
69 // "charAt" special case. It is the only non-leaf method we inline across dex files.
70 ArtMethod* inlined_method = jni::DecodeArtMethod(WellKnownClasses::java_lang_String_charAt);
71 DCHECK_EQ(inlined_method->GetDexMethodIndex(), method_index);
72 return inlined_method;
73 }
74 }
75
76 // Find which method did the call in the inlining hierarchy.
77 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
78 ArtMethod* method = outer_method;
79 for (InlineInfo inline_info : inline_infos) {
80 DCHECK(!inline_info.EncodesArtMethod());
81 DCHECK_NE(inline_info.GetDexPc(), static_cast<uint32_t>(-1));
82 uint32_t method_index = code_info.GetMethodIndexOf(inline_info);
83 ArtMethod* inlined_method = class_linker->LookupResolvedMethod(method_index,
84 method->GetDexCache(),
85 method->GetClassLoader());
86 if (UNLIKELY(inlined_method == nullptr)) {
87 LOG(FATAL) << "Could not find an inlined method from an .oat file: "
88 << method->GetDexFile()->PrettyMethod(method_index) << " . "
89 << "This must be due to duplicate classes or playing wrongly with class loaders";
90 UNREACHABLE();
91 }
92 DCHECK(!inlined_method->IsRuntimeMethod());
93 if (UNLIKELY(inlined_method->GetDexFile() != method->GetDexFile())) {
94 // TODO: We could permit inlining within a multi-dex oat file and the boot image,
95 // even going back from boot image methods to the same oat file. However, this is
96 // not currently implemented in the compiler. Therefore crossing dex file boundary
97 // indicates that the inlined definition is not the same as the one used at runtime.
98 bool target_sdk_at_least_p =
99 IsSdkVersionSetAndAtLeast(Runtime::Current()->GetTargetSdkVersion(), SdkVersion::kP);
100 LOG(target_sdk_at_least_p ? FATAL : WARNING)
101 << "Inlined method resolution crossed dex file boundary: from "
102 << method->PrettyMethod()
103 << " in " << method->GetDexFile()->GetLocation() << "/"
104 << static_cast<const void*>(method->GetDexFile())
105 << " to " << inlined_method->PrettyMethod()
106 << " in " << inlined_method->GetDexFile()->GetLocation() << "/"
107 << static_cast<const void*>(inlined_method->GetDexFile()) << ". "
108 << "This must be due to duplicate classes or playing wrongly with class loaders. "
109 << "The runtime is in an unsafe state.";
110 }
111 method = inlined_method;
112 }
113
114 return method;
115 }
116
CheckObjectAlloc(ObjPtr<mirror::Class> klass,Thread * self,bool * slow_path)117 ALWAYS_INLINE inline ObjPtr<mirror::Class> CheckObjectAlloc(ObjPtr<mirror::Class> klass,
118 Thread* self,
119 bool* slow_path)
120 REQUIRES_SHARED(Locks::mutator_lock_)
121 REQUIRES(!Roles::uninterruptible_) {
122 if (UNLIKELY(!klass->IsInstantiable())) {
123 self->ThrowNewException("Ljava/lang/InstantiationError;", klass->PrettyDescriptor().c_str());
124 *slow_path = true;
125 return nullptr; // Failure
126 }
127 if (UNLIKELY(klass->IsClassClass())) {
128 ThrowIllegalAccessError(nullptr, "Class %s is inaccessible",
129 klass->PrettyDescriptor().c_str());
130 *slow_path = true;
131 return nullptr; // Failure
132 }
133 if (UNLIKELY(!klass->IsInitialized())) {
134 StackHandleScope<1> hs(self);
135 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
136 // EnsureInitialized (the class initializer) might cause a GC.
137 // may cause us to suspend meaning that another thread may try to
138 // change the allocator while we are stuck in the entrypoints of
139 // an old allocator. Also, the class initialization may fail. To
140 // handle these cases we mark the slow path boolean as true so
141 // that the caller knows to check the allocator type to see if it
142 // has changed and to null-check the return value in case the
143 // initialization fails.
144 *slow_path = true;
145 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_klass, true, true)) {
146 DCHECK(self->IsExceptionPending());
147 return nullptr; // Failure
148 } else {
149 DCHECK(!self->IsExceptionPending());
150 }
151 return h_klass.Get();
152 }
153 return klass;
154 }
155
156 ALWAYS_INLINE
CheckClassInitializedForObjectAlloc(ObjPtr<mirror::Class> klass,Thread * self,bool * slow_path)157 inline ObjPtr<mirror::Class> CheckClassInitializedForObjectAlloc(ObjPtr<mirror::Class> klass,
158 Thread* self,
159 bool* slow_path)
160 REQUIRES_SHARED(Locks::mutator_lock_)
161 REQUIRES(!Roles::uninterruptible_) {
162 if (UNLIKELY(!klass->IsInitialized())) {
163 StackHandleScope<1> hs(self);
164 Handle<mirror::Class> h_class(hs.NewHandle(klass));
165 // EnsureInitialized (the class initializer) might cause a GC.
166 // may cause us to suspend meaning that another thread may try to
167 // change the allocator while we are stuck in the entrypoints of
168 // an old allocator. Also, the class initialization may fail. To
169 // handle these cases we mark the slow path boolean as true so
170 // that the caller knows to check the allocator type to see if it
171 // has changed and to null-check the return value in case the
172 // initialization fails.
173 *slow_path = true;
174 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
175 DCHECK(self->IsExceptionPending());
176 return nullptr; // Failure
177 }
178 return h_class.Get();
179 }
180 return klass;
181 }
182
183 // Allocate an instance of klass. Throws InstantationError if klass is not instantiable,
184 // or IllegalAccessError if klass is j.l.Class. Performs a clinit check too.
185 template <bool kInstrumented>
186 ALWAYS_INLINE
AllocObjectFromCode(ObjPtr<mirror::Class> klass,Thread * self,gc::AllocatorType allocator_type)187 inline ObjPtr<mirror::Object> AllocObjectFromCode(ObjPtr<mirror::Class> klass,
188 Thread* self,
189 gc::AllocatorType allocator_type) {
190 bool slow_path = false;
191 klass = CheckObjectAlloc(klass, self, &slow_path);
192 if (UNLIKELY(slow_path)) {
193 if (klass == nullptr) {
194 return nullptr;
195 }
196 // CheckObjectAlloc can cause thread suspension which means we may now be instrumented.
197 return klass->Alloc</*kInstrumented=*/true>(
198 self,
199 Runtime::Current()->GetHeap()->GetCurrentAllocator());
200 }
201 DCHECK(klass != nullptr);
202 return klass->Alloc<kInstrumented>(self, allocator_type);
203 }
204
205 // Given the context of a calling Method and a resolved class, create an instance.
206 template <bool kInstrumented>
207 ALWAYS_INLINE
AllocObjectFromCodeResolved(ObjPtr<mirror::Class> klass,Thread * self,gc::AllocatorType allocator_type)208 inline ObjPtr<mirror::Object> AllocObjectFromCodeResolved(ObjPtr<mirror::Class> klass,
209 Thread* self,
210 gc::AllocatorType allocator_type) {
211 DCHECK(klass != nullptr);
212 bool slow_path = false;
213 klass = CheckClassInitializedForObjectAlloc(klass, self, &slow_path);
214 if (UNLIKELY(slow_path)) {
215 if (klass == nullptr) {
216 return nullptr;
217 }
218 gc::Heap* heap = Runtime::Current()->GetHeap();
219 // Pass in false since the object cannot be finalizable.
220 // CheckClassInitializedForObjectAlloc can cause thread suspension which means we may now be
221 // instrumented.
222 return klass->Alloc</*kInstrumented=*/true, false>(self, heap->GetCurrentAllocator());
223 }
224 // Pass in false since the object cannot be finalizable.
225 return klass->Alloc<kInstrumented, false>(self, allocator_type);
226 }
227
228 // Given the context of a calling Method and an initialized class, create an instance.
229 template <bool kInstrumented>
230 ALWAYS_INLINE
AllocObjectFromCodeInitialized(ObjPtr<mirror::Class> klass,Thread * self,gc::AllocatorType allocator_type)231 inline ObjPtr<mirror::Object> AllocObjectFromCodeInitialized(ObjPtr<mirror::Class> klass,
232 Thread* self,
233 gc::AllocatorType allocator_type) {
234 DCHECK(klass != nullptr);
235 // Pass in false since the object cannot be finalizable.
236 return klass->Alloc<kInstrumented, false>(self, allocator_type);
237 }
238
239
240 template <bool kAccessCheck>
241 ALWAYS_INLINE
CheckArrayAlloc(dex::TypeIndex type_idx,int32_t component_count,ArtMethod * method,bool * slow_path)242 inline ObjPtr<mirror::Class> CheckArrayAlloc(dex::TypeIndex type_idx,
243 int32_t component_count,
244 ArtMethod* method,
245 bool* slow_path) {
246 if (UNLIKELY(component_count < 0)) {
247 ThrowNegativeArraySizeException(component_count);
248 *slow_path = true;
249 return nullptr; // Failure
250 }
251 ObjPtr<mirror::Class> klass = method->GetDexCache()->GetResolvedType(type_idx);
252 if (UNLIKELY(klass == nullptr)) { // Not in dex cache so try to resolve
253 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
254 klass = class_linker->ResolveType(type_idx, method);
255 *slow_path = true;
256 if (klass == nullptr) { // Error
257 DCHECK(Thread::Current()->IsExceptionPending());
258 return nullptr; // Failure
259 }
260 CHECK(klass->IsArrayClass()) << klass->PrettyClass();
261 }
262 if (kAccessCheck) {
263 ObjPtr<mirror::Class> referrer = method->GetDeclaringClass();
264 if (UNLIKELY(!referrer->CanAccess(klass))) {
265 ThrowIllegalAccessErrorClass(referrer, klass);
266 *slow_path = true;
267 return nullptr; // Failure
268 }
269 }
270 return klass;
271 }
272
273 // Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
274 // it cannot be resolved, throw an error. If it can, use it to create an array.
275 // When verification/compiler hasn't been able to verify access, optionally perform an access
276 // check.
277 template <bool kAccessCheck, bool kInstrumented>
278 ALWAYS_INLINE
AllocArrayFromCode(dex::TypeIndex type_idx,int32_t component_count,ArtMethod * method,Thread * self,gc::AllocatorType allocator_type)279 inline ObjPtr<mirror::Array> AllocArrayFromCode(dex::TypeIndex type_idx,
280 int32_t component_count,
281 ArtMethod* method,
282 Thread* self,
283 gc::AllocatorType allocator_type) {
284 bool slow_path = false;
285 ObjPtr<mirror::Class> klass =
286 CheckArrayAlloc<kAccessCheck>(type_idx, component_count, method, &slow_path);
287 if (UNLIKELY(slow_path)) {
288 if (klass == nullptr) {
289 return nullptr;
290 }
291 gc::Heap* heap = Runtime::Current()->GetHeap();
292 // CheckArrayAlloc can cause thread suspension which means we may now be instrumented.
293 return mirror::Array::Alloc</*kInstrumented=*/true>(self,
294 klass,
295 component_count,
296 klass->GetComponentSizeShift(),
297 heap->GetCurrentAllocator());
298 }
299 return mirror::Array::Alloc<kInstrumented>(self, klass, component_count,
300 klass->GetComponentSizeShift(), allocator_type);
301 }
302
303 template <bool kInstrumented>
304 ALWAYS_INLINE
AllocArrayFromCodeResolved(ObjPtr<mirror::Class> klass,int32_t component_count,Thread * self,gc::AllocatorType allocator_type)305 inline ObjPtr<mirror::Array> AllocArrayFromCodeResolved(ObjPtr<mirror::Class> klass,
306 int32_t component_count,
307 Thread* self,
308 gc::AllocatorType allocator_type) {
309 DCHECK(klass != nullptr);
310 if (UNLIKELY(component_count < 0)) {
311 ThrowNegativeArraySizeException(component_count);
312 return nullptr; // Failure
313 }
314 // No need to retry a slow-path allocation as the above code won't cause a GC or thread
315 // suspension.
316 return mirror::Array::Alloc<kInstrumented>(self, klass, component_count,
317 klass->GetComponentSizeShift(), allocator_type);
318 }
319
320 template<FindFieldType type, bool access_check>
FindFieldFromCode(uint32_t field_idx,ArtMethod * referrer,Thread * self,size_t expected_size)321 inline ArtField* FindFieldFromCode(uint32_t field_idx,
322 ArtMethod* referrer,
323 Thread* self,
324 size_t expected_size) {
325 constexpr bool is_primitive = (type & FindFieldFlags::PrimitiveBit) != 0;
326 constexpr bool is_set = (type & FindFieldFlags::WriteBit) != 0;
327 constexpr bool is_static = (type & FindFieldFlags::StaticBit) != 0;
328 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
329
330 ArtField* resolved_field;
331 if (access_check) {
332 // Slow path: According to JLS 13.4.8, a linkage error may occur if a compile-time
333 // qualifying type of a field and the resolved run-time qualifying type of a field differed
334 // in their static-ness.
335 //
336 // In particular, don't assume the dex instruction already correctly knows if the
337 // real field is static or not. The resolution must not be aware of this.
338 ArtMethod* method = referrer->GetInterfaceMethodIfProxy(kRuntimePointerSize);
339
340 StackHandleScope<2> hs(self);
341 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(method->GetDexCache()));
342 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(method->GetClassLoader()));
343
344 resolved_field = class_linker->ResolveFieldJLS(field_idx,
345 h_dex_cache,
346 h_class_loader);
347 } else {
348 // Fast path: Verifier already would've called ResolveFieldJLS and we wouldn't
349 // be executing here if there was a static/non-static mismatch.
350 resolved_field = class_linker->ResolveField(field_idx, referrer, is_static);
351 }
352
353 if (UNLIKELY(resolved_field == nullptr)) {
354 DCHECK(self->IsExceptionPending()); // Throw exception and unwind.
355 return nullptr; // Failure.
356 }
357 ObjPtr<mirror::Class> fields_class = resolved_field->GetDeclaringClass();
358 if (access_check) {
359 if (UNLIKELY(resolved_field->IsStatic() != is_static)) {
360 ThrowIncompatibleClassChangeErrorField(resolved_field, is_static, referrer);
361 return nullptr;
362 }
363 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
364 if (UNLIKELY(!referring_class->CheckResolvedFieldAccess(fields_class,
365 resolved_field,
366 referrer->GetDexCache(),
367 field_idx))) {
368 DCHECK(self->IsExceptionPending()); // Throw exception and unwind.
369 return nullptr; // Failure.
370 }
371 if (UNLIKELY(is_set && resolved_field->IsFinal() && (fields_class != referring_class))) {
372 ThrowIllegalAccessErrorFinalField(referrer, resolved_field);
373 return nullptr; // Failure.
374 } else {
375 if (UNLIKELY(resolved_field->IsPrimitiveType() != is_primitive ||
376 resolved_field->FieldSize() != expected_size)) {
377 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
378 "Attempted read of %zd-bit %s on field '%s'",
379 expected_size * (32 / sizeof(int32_t)),
380 is_primitive ? "primitive" : "non-primitive",
381 resolved_field->PrettyField(true).c_str());
382 return nullptr; // Failure.
383 }
384 }
385 }
386 if (!is_static) {
387 // instance fields must be being accessed on an initialized class
388 return resolved_field;
389 } else {
390 // If the class is initialized we're done.
391 if (LIKELY(fields_class->IsInitialized())) {
392 return resolved_field;
393 } else {
394 StackHandleScope<1> hs(self);
395 if (LIKELY(class_linker->EnsureInitialized(self, hs.NewHandle(fields_class), true, true))) {
396 // Otherwise let's ensure the class is initialized before resolving the field.
397 return resolved_field;
398 }
399 DCHECK(self->IsExceptionPending()); // Throw exception and unwind
400 return nullptr; // Failure.
401 }
402 }
403 }
404
405 // Explicit template declarations of FindFieldFromCode for all field access types.
406 #define EXPLICIT_FIND_FIELD_FROM_CODE_TEMPLATE_DECL(_type, _access_check) \
407 template REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE \
408 ArtField* FindFieldFromCode<_type, _access_check>(uint32_t field_idx, \
409 ArtMethod* referrer, \
410 Thread* self, size_t expected_size) \
411
412 #define EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(_type) \
413 EXPLICIT_FIND_FIELD_FROM_CODE_TEMPLATE_DECL(_type, false); \
414 EXPLICIT_FIND_FIELD_FROM_CODE_TEMPLATE_DECL(_type, true)
415
416 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(InstanceObjectRead);
417 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(InstanceObjectWrite);
418 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(InstancePrimitiveRead);
419 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(InstancePrimitiveWrite);
420 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(StaticObjectRead);
421 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(StaticObjectWrite);
422 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(StaticPrimitiveRead);
423 EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL(StaticPrimitiveWrite);
424
425 #undef EXPLICIT_FIND_FIELD_FROM_CODE_TYPED_TEMPLATE_DECL
426 #undef EXPLICIT_FIND_FIELD_FROM_CODE_TEMPLATE_DECL
427
428 // Follow virtual/interface indirections if applicable.
429 // Will throw null-pointer exception the if the object is null.
430 template<InvokeType type, bool access_check>
FindMethodToCall(uint32_t method_idx,ArtMethod * resolved_method,ObjPtr<mirror::Object> * this_object,ArtMethod * referrer,Thread * self)431 ALWAYS_INLINE ArtMethod* FindMethodToCall(uint32_t method_idx,
432 ArtMethod* resolved_method,
433 ObjPtr<mirror::Object>* this_object,
434 ArtMethod* referrer,
435 Thread* self)
436 REQUIRES_SHARED(Locks::mutator_lock_) {
437 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
438 // Null pointer check.
439 if (UNLIKELY(*this_object == nullptr && type != kStatic)) {
440 if (UNLIKELY(resolved_method->GetDeclaringClass()->IsStringClass() &&
441 resolved_method->IsConstructor())) {
442 // Hack for String init:
443 //
444 // We assume that the input of String.<init> in verified code is always
445 // an unitialized reference. If it is a null constant, it must have been
446 // optimized out by the compiler. Do not throw NullPointerException.
447 } else {
448 // Maintain interpreter-like semantics where NullPointerException is thrown
449 // after potential NoSuchMethodError from class linker.
450 ThrowNullPointerExceptionForMethodAccess(method_idx, type);
451 return nullptr; // Failure.
452 }
453 }
454 switch (type) {
455 case kStatic:
456 case kDirect:
457 return resolved_method;
458 case kVirtual: {
459 ObjPtr<mirror::Class> klass = (*this_object)->GetClass();
460 uint16_t vtable_index = resolved_method->GetMethodIndex();
461 if (access_check &&
462 (!klass->HasVTable() ||
463 vtable_index >= static_cast<uint32_t>(klass->GetVTableLength()))) {
464 // Behavior to agree with that of the verifier.
465 ThrowNoSuchMethodError(type, resolved_method->GetDeclaringClass(),
466 resolved_method->GetName(), resolved_method->GetSignature());
467 return nullptr; // Failure.
468 }
469 DCHECK(klass->HasVTable()) << klass->PrettyClass();
470 return klass->GetVTableEntry(vtable_index, class_linker->GetImagePointerSize());
471 }
472 case kSuper: {
473 // TODO This lookup is quite slow.
474 // NB This is actually quite tricky to do any other way. We cannot use GetDeclaringClass since
475 // that will actually not be what we want in some cases where there are miranda methods or
476 // defaults. What we actually need is a GetContainingClass that says which classes virtuals
477 // this method is coming from.
478 StackHandleScope<2> hs2(self);
479 HandleWrapperObjPtr<mirror::Object> h_this(hs2.NewHandleWrapper(this_object));
480 Handle<mirror::Class> h_referring_class(hs2.NewHandle(referrer->GetDeclaringClass()));
481 const dex::TypeIndex method_type_idx =
482 referrer->GetDexFile()->GetMethodId(method_idx).class_idx_;
483 ObjPtr<mirror::Class> method_reference_class =
484 class_linker->ResolveType(method_type_idx, referrer);
485 if (UNLIKELY(method_reference_class == nullptr)) {
486 // Bad type idx.
487 CHECK(self->IsExceptionPending());
488 return nullptr;
489 } else if (!method_reference_class->IsInterface()) {
490 // It is not an interface. If the referring class is in the class hierarchy of the
491 // referenced class in the bytecode, we use its super class. Otherwise, we throw
492 // a NoSuchMethodError.
493 ObjPtr<mirror::Class> super_class = nullptr;
494 if (method_reference_class->IsAssignableFrom(h_referring_class.Get())) {
495 super_class = h_referring_class->GetSuperClass();
496 }
497 uint16_t vtable_index = resolved_method->GetMethodIndex();
498 if (access_check) {
499 // Check existence of super class.
500 if (super_class == nullptr ||
501 !super_class->HasVTable() ||
502 vtable_index >= static_cast<uint32_t>(super_class->GetVTableLength())) {
503 // Behavior to agree with that of the verifier.
504 ThrowNoSuchMethodError(type, resolved_method->GetDeclaringClass(),
505 resolved_method->GetName(), resolved_method->GetSignature());
506 return nullptr; // Failure.
507 }
508 }
509 DCHECK(super_class != nullptr);
510 DCHECK(super_class->HasVTable());
511 return super_class->GetVTableEntry(vtable_index, class_linker->GetImagePointerSize());
512 } else {
513 // It is an interface.
514 if (access_check) {
515 if (!method_reference_class->IsAssignableFrom(h_this->GetClass())) {
516 ThrowIncompatibleClassChangeErrorClassForInterfaceSuper(resolved_method,
517 method_reference_class,
518 h_this.Get(),
519 referrer);
520 return nullptr; // Failure.
521 }
522 }
523 // TODO We can do better than this for a (compiled) fastpath.
524 ArtMethod* result = method_reference_class->FindVirtualMethodForInterfaceSuper(
525 resolved_method, class_linker->GetImagePointerSize());
526 // Throw an NSME if nullptr;
527 if (result == nullptr) {
528 ThrowNoSuchMethodError(type, resolved_method->GetDeclaringClass(),
529 resolved_method->GetName(), resolved_method->GetSignature());
530 }
531 return result;
532 }
533 UNREACHABLE();
534 }
535 case kInterface: {
536 size_t imt_index = resolved_method->GetImtIndex();
537 PointerSize pointer_size = class_linker->GetImagePointerSize();
538 ObjPtr<mirror::Class> klass = (*this_object)->GetClass();
539 ArtMethod* imt_method = klass->GetImt(pointer_size)->Get(imt_index, pointer_size);
540 if (!imt_method->IsRuntimeMethod()) {
541 if (kIsDebugBuild) {
542 ArtMethod* method = klass->FindVirtualMethodForInterface(
543 resolved_method, class_linker->GetImagePointerSize());
544 CHECK_EQ(imt_method, method) << ArtMethod::PrettyMethod(resolved_method) << " / "
545 << imt_method->PrettyMethod() << " / "
546 << ArtMethod::PrettyMethod(method) << " / "
547 << klass->PrettyClass();
548 }
549 return imt_method;
550 } else {
551 ArtMethod* interface_method = klass->FindVirtualMethodForInterface(
552 resolved_method, class_linker->GetImagePointerSize());
553 if (UNLIKELY(interface_method == nullptr)) {
554 ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(resolved_method,
555 *this_object, referrer);
556 return nullptr; // Failure.
557 }
558 return interface_method;
559 }
560 }
561 default:
562 LOG(FATAL) << "Unknown invoke type " << type;
563 return nullptr; // Failure.
564 }
565 }
566
567 template<InvokeType type, bool access_check>
FindMethodFromCode(uint32_t method_idx,ObjPtr<mirror::Object> * this_object,ArtMethod * referrer,Thread * self)568 inline ArtMethod* FindMethodFromCode(uint32_t method_idx,
569 ObjPtr<mirror::Object>* this_object,
570 ArtMethod* referrer,
571 Thread* self) {
572 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
573 constexpr ClassLinker::ResolveMode resolve_mode =
574 access_check ? ClassLinker::ResolveMode::kCheckICCEAndIAE
575 : ClassLinker::ResolveMode::kNoChecks;
576 ArtMethod* resolved_method;
577 if (type == kStatic) {
578 resolved_method = class_linker->ResolveMethod<resolve_mode>(self, method_idx, referrer, type);
579 } else {
580 StackHandleScope<1> hs(self);
581 HandleWrapperObjPtr<mirror::Object> h_this(hs.NewHandleWrapper(this_object));
582 resolved_method = class_linker->ResolveMethod<resolve_mode>(self, method_idx, referrer, type);
583 }
584 if (UNLIKELY(resolved_method == nullptr)) {
585 DCHECK(self->IsExceptionPending()); // Throw exception and unwind.
586 return nullptr; // Failure.
587 }
588 return FindMethodToCall<type, access_check>(
589 method_idx, resolved_method, this_object, referrer, self);
590 }
591
592 // Explicit template declarations of FindMethodFromCode for all invoke types.
593 #define EXPLICIT_FIND_METHOD_FROM_CODE_TEMPLATE_DECL(_type, _access_check) \
594 template REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE \
595 ArtMethod* FindMethodFromCode<_type, _access_check>(uint32_t method_idx, \
596 ObjPtr<mirror::Object>* this_object, \
597 ArtMethod* referrer, \
598 Thread* self)
599 #define EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(_type) \
600 EXPLICIT_FIND_METHOD_FROM_CODE_TEMPLATE_DECL(_type, false); \
601 EXPLICIT_FIND_METHOD_FROM_CODE_TEMPLATE_DECL(_type, true)
602
603 EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(kStatic);
604 EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(kDirect);
605 EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(kVirtual);
606 EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(kSuper);
607 EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL(kInterface);
608
609 #undef EXPLICIT_FIND_METHOD_FROM_CODE_TYPED_TEMPLATE_DECL
610 #undef EXPLICIT_FIND_METHOD_FROM_CODE_TEMPLATE_DECL
611
612 // Fast path field resolution that can't initialize classes or throw exceptions.
FindFieldFast(uint32_t field_idx,ArtMethod * referrer,FindFieldType type,size_t expected_size)613 inline ArtField* FindFieldFast(uint32_t field_idx, ArtMethod* referrer, FindFieldType type,
614 size_t expected_size) {
615 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
616 ArtField* resolved_field =
617 referrer->GetDexCache()->GetResolvedField(field_idx, kRuntimePointerSize);
618 if (UNLIKELY(resolved_field == nullptr)) {
619 return nullptr;
620 }
621 // Check for incompatible class change.
622 const bool is_primitive = (type & FindFieldFlags::PrimitiveBit) != 0;
623 const bool is_set = (type & FindFieldFlags::WriteBit) != 0;
624 const bool is_static = (type & FindFieldFlags::StaticBit) != 0;
625 if (UNLIKELY(resolved_field->IsStatic() != is_static)) {
626 // Incompatible class change.
627 return nullptr;
628 }
629 ObjPtr<mirror::Class> fields_class = resolved_field->GetDeclaringClass();
630 if (is_static) {
631 // Check class is initialized else fail so that we can contend to initialize the class with
632 // other threads that may be racing to do this.
633 if (UNLIKELY(!fields_class->IsInitialized())) {
634 return nullptr;
635 }
636 }
637 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
638 if (UNLIKELY(!referring_class->CanAccess(fields_class) ||
639 !referring_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) ||
640 (is_set && resolved_field->IsFinal() && (fields_class != referring_class)))) {
641 // Illegal access.
642 return nullptr;
643 }
644 if (UNLIKELY(resolved_field->IsPrimitiveType() != is_primitive ||
645 resolved_field->FieldSize() != expected_size)) {
646 return nullptr;
647 }
648 return resolved_field;
649 }
650
651 // Fast path method resolution that can't throw exceptions.
652 template <InvokeType type, bool access_check>
FindMethodFast(uint32_t method_idx,ObjPtr<mirror::Object> this_object,ArtMethod * referrer)653 inline ArtMethod* FindMethodFast(uint32_t method_idx,
654 ObjPtr<mirror::Object> this_object,
655 ArtMethod* referrer) {
656 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
657 if (UNLIKELY(this_object == nullptr && type != kStatic)) {
658 return nullptr;
659 }
660 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
661 ObjPtr<mirror::DexCache> dex_cache = referrer->GetDexCache();
662 constexpr ClassLinker::ResolveMode resolve_mode = access_check
663 ? ClassLinker::ResolveMode::kCheckICCEAndIAE
664 : ClassLinker::ResolveMode::kNoChecks;
665 ClassLinker* linker = Runtime::Current()->GetClassLinker();
666 ArtMethod* resolved_method = linker->GetResolvedMethod<type, resolve_mode>(method_idx, referrer);
667 if (UNLIKELY(resolved_method == nullptr)) {
668 return nullptr;
669 }
670 if (type == kInterface) { // Most common form of slow path dispatch.
671 return this_object->GetClass()->FindVirtualMethodForInterface(resolved_method,
672 kRuntimePointerSize);
673 } else if (type == kStatic || type == kDirect) {
674 return resolved_method;
675 } else if (type == kSuper) {
676 // TODO This lookup is rather slow.
677 dex::TypeIndex method_type_idx = dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
678 ObjPtr<mirror::Class> method_reference_class = linker->LookupResolvedType(
679 method_type_idx, dex_cache, referrer->GetClassLoader());
680 if (method_reference_class == nullptr) {
681 // Need to do full type resolution...
682 return nullptr;
683 } else if (!method_reference_class->IsInterface()) {
684 // It is not an interface. If the referring class is in the class hierarchy of the
685 // referenced class in the bytecode, we use its super class. Otherwise, we cannot
686 // resolve the method.
687 if (!method_reference_class->IsAssignableFrom(referring_class)) {
688 return nullptr;
689 }
690 ObjPtr<mirror::Class> super_class = referring_class->GetSuperClass();
691 if (resolved_method->GetMethodIndex() >= super_class->GetVTableLength()) {
692 // The super class does not have the method.
693 return nullptr;
694 }
695 return super_class->GetVTableEntry(resolved_method->GetMethodIndex(), kRuntimePointerSize);
696 } else {
697 return method_reference_class->FindVirtualMethodForInterfaceSuper(
698 resolved_method, kRuntimePointerSize);
699 }
700 } else {
701 DCHECK(type == kVirtual);
702 return this_object->GetClass()->GetVTableEntry(
703 resolved_method->GetMethodIndex(), kRuntimePointerSize);
704 }
705 }
706
ResolveVerifyAndClinit(dex::TypeIndex type_idx,ArtMethod * referrer,Thread * self,bool can_run_clinit,bool verify_access)707 inline ObjPtr<mirror::Class> ResolveVerifyAndClinit(dex::TypeIndex type_idx,
708 ArtMethod* referrer,
709 Thread* self,
710 bool can_run_clinit,
711 bool verify_access) {
712 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
713 ObjPtr<mirror::Class> klass = class_linker->ResolveType(type_idx, referrer);
714 if (UNLIKELY(klass == nullptr)) {
715 CHECK(self->IsExceptionPending());
716 return nullptr; // Failure - Indicate to caller to deliver exception
717 }
718 // Perform access check if necessary.
719 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
720 if (verify_access && UNLIKELY(!referring_class->CanAccess(klass))) {
721 ThrowIllegalAccessErrorClass(referring_class, klass);
722 return nullptr; // Failure - Indicate to caller to deliver exception
723 }
724 // If we're just implementing const-class, we shouldn't call <clinit>.
725 if (!can_run_clinit) {
726 return klass;
727 }
728 // If we are the <clinit> of this class, just return our storage.
729 //
730 // Do not set the DexCache InitializedStaticStorage, since that implies <clinit> has finished
731 // running.
732 if (klass == referring_class && referrer->IsConstructor() && referrer->IsStatic()) {
733 return klass;
734 }
735 StackHandleScope<1> hs(self);
736 Handle<mirror::Class> h_class(hs.NewHandle(klass));
737 if (!class_linker->EnsureInitialized(self, h_class, true, true)) {
738 CHECK(self->IsExceptionPending());
739 return nullptr; // Failure - Indicate to caller to deliver exception
740 }
741 return h_class.Get();
742 }
743
UnlockJniSynchronizedMethod(jobject locked,Thread * self)744 inline void UnlockJniSynchronizedMethod(jobject locked, Thread* self) {
745 // Save any pending exception over monitor exit call.
746 ObjPtr<mirror::Throwable> saved_exception = nullptr;
747 if (UNLIKELY(self->IsExceptionPending())) {
748 saved_exception = self->GetException();
749 self->ClearException();
750 }
751 // Decode locked object and unlock, before popping local references.
752 self->DecodeJObject(locked)->MonitorExit(self);
753 if (UNLIKELY(self->IsExceptionPending())) {
754 LOG(FATAL) << "Synchronized JNI code returning with an exception:\n"
755 << saved_exception->Dump()
756 << "\nEncountered second exception during implicit MonitorExit:\n"
757 << self->GetException()->Dump();
758 }
759 // Restore pending exception.
760 if (saved_exception != nullptr) {
761 self->SetException(saved_exception);
762 }
763 }
764
765 template <typename INT_TYPE, typename FLOAT_TYPE>
art_float_to_integral(FLOAT_TYPE f)766 inline INT_TYPE art_float_to_integral(FLOAT_TYPE f) {
767 const INT_TYPE kMaxInt = static_cast<INT_TYPE>(std::numeric_limits<INT_TYPE>::max());
768 const INT_TYPE kMinInt = static_cast<INT_TYPE>(std::numeric_limits<INT_TYPE>::min());
769 const FLOAT_TYPE kMaxIntAsFloat = static_cast<FLOAT_TYPE>(kMaxInt);
770 const FLOAT_TYPE kMinIntAsFloat = static_cast<FLOAT_TYPE>(kMinInt);
771 if (LIKELY(f > kMinIntAsFloat)) {
772 if (LIKELY(f < kMaxIntAsFloat)) {
773 return static_cast<INT_TYPE>(f);
774 } else {
775 return kMaxInt;
776 }
777 } else {
778 return (f != f) ? 0 : kMinInt; // f != f implies NaN
779 }
780 }
781
782 } // namespace art
783
784 #endif // ART_RUNTIME_ENTRYPOINTS_ENTRYPOINT_UTILS_INL_H_
785