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