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 "class_linker.h"
18
19 #include <algorithm>
20 #include <deque>
21 #include <iostream>
22 #include <memory>
23 #include <queue>
24 #include <string>
25 #include <tuple>
26 #include <unistd.h>
27 #include <unordered_map>
28 #include <utility>
29 #include <vector>
30
31 #include "art_field-inl.h"
32 #include "art_method-inl.h"
33 #include "base/arena_allocator.h"
34 #include "base/casts.h"
35 #include "base/logging.h"
36 #include "base/scoped_arena_containers.h"
37 #include "base/scoped_flock.h"
38 #include "base/stl_util.h"
39 #include "base/systrace.h"
40 #include "base/time_utils.h"
41 #include "base/unix_file/fd_file.h"
42 #include "base/value_object.h"
43 #include "class_linker-inl.h"
44 #include "class_table-inl.h"
45 #include "compiler_callbacks.h"
46 #include "debugger.h"
47 #include "dex_file-inl.h"
48 #include "entrypoints/entrypoint_utils.h"
49 #include "entrypoints/runtime_asm_entrypoints.h"
50 #include "experimental_flags.h"
51 #include "gc_root-inl.h"
52 #include "gc/accounting/card_table-inl.h"
53 #include "gc/accounting/heap_bitmap-inl.h"
54 #include "gc/heap.h"
55 #include "gc/scoped_gc_critical_section.h"
56 #include "gc/space/image_space.h"
57 #include "handle_scope-inl.h"
58 #include "image-inl.h"
59 #include "intern_table.h"
60 #include "interpreter/interpreter.h"
61 #include "jit/jit.h"
62 #include "jit/jit_code_cache.h"
63 #include "jit/offline_profiling_info.h"
64 #include "leb128.h"
65 #include "linear_alloc.h"
66 #include "mirror/class.h"
67 #include "mirror/class-inl.h"
68 #include "mirror/class_loader.h"
69 #include "mirror/dex_cache-inl.h"
70 #include "mirror/field.h"
71 #include "mirror/iftable-inl.h"
72 #include "mirror/method.h"
73 #include "mirror/object-inl.h"
74 #include "mirror/object_array-inl.h"
75 #include "mirror/proxy.h"
76 #include "mirror/reference-inl.h"
77 #include "mirror/stack_trace_element.h"
78 #include "mirror/string-inl.h"
79 #include "native/dalvik_system_DexFile.h"
80 #include "oat.h"
81 #include "oat_file.h"
82 #include "oat_file-inl.h"
83 #include "oat_file_assistant.h"
84 #include "oat_file_manager.h"
85 #include "object_lock.h"
86 #include "os.h"
87 #include "runtime.h"
88 #include "ScopedLocalRef.h"
89 #include "scoped_thread_state_change.h"
90 #include "thread-inl.h"
91 #include "trace.h"
92 #include "utils.h"
93 #include "utils/dex_cache_arrays_layout-inl.h"
94 #include "verifier/method_verifier.h"
95 #include "well_known_classes.h"
96
97 namespace art {
98
99 static constexpr bool kSanityCheckObjects = kIsDebugBuild;
100 static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
101
102 static void ThrowNoClassDefFoundError(const char* fmt, ...)
103 __attribute__((__format__(__printf__, 1, 2)))
104 SHARED_REQUIRES(Locks::mutator_lock_);
ThrowNoClassDefFoundError(const char * fmt,...)105 static void ThrowNoClassDefFoundError(const char* fmt, ...) {
106 va_list args;
107 va_start(args, fmt);
108 Thread* self = Thread::Current();
109 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
110 va_end(args);
111 }
112
HasInitWithString(Thread * self,ClassLinker * class_linker,const char * descriptor)113 static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
114 SHARED_REQUIRES(Locks::mutator_lock_) {
115 ArtMethod* method = self->GetCurrentMethod(nullptr);
116 StackHandleScope<1> hs(self);
117 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
118 method->GetDeclaringClass()->GetClassLoader() : nullptr));
119 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
120
121 if (exception_class == nullptr) {
122 // No exc class ~ no <init>-with-string.
123 CHECK(self->IsExceptionPending());
124 self->ClearException();
125 return false;
126 }
127
128 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
129 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
130 return exception_init_method != nullptr;
131 }
132
133 // Helper for ThrowEarlierClassFailure. Throws the stored error.
HandleEarlierVerifyError(Thread * self,ClassLinker * class_linker,mirror::Class * c)134 static void HandleEarlierVerifyError(Thread* self, ClassLinker* class_linker, mirror::Class* c)
135 SHARED_REQUIRES(Locks::mutator_lock_) {
136 mirror::Object* obj = c->GetVerifyError();
137 DCHECK(obj != nullptr);
138 self->AssertNoPendingException();
139 if (obj->IsClass()) {
140 // Previous error has been stored as class. Create a new exception of that type.
141
142 // It's possible the exception doesn't have a <init>(String).
143 std::string temp;
144 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
145
146 if (HasInitWithString(self, class_linker, descriptor)) {
147 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
148 } else {
149 self->ThrowNewException(descriptor, nullptr);
150 }
151 } else {
152 // Previous error has been stored as an instance. Just rethrow.
153 mirror::Class* throwable_class =
154 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
155 mirror::Class* error_class = obj->GetClass();
156 CHECK(throwable_class->IsAssignableFrom(error_class));
157 self->SetException(obj->AsThrowable());
158 }
159 self->AssertPendingException();
160 }
161
ThrowEarlierClassFailure(mirror::Class * c,bool wrap_in_no_class_def)162 void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c, bool wrap_in_no_class_def) {
163 // The class failed to initialize on a previous attempt, so we want to throw
164 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
165 // failed in verification, in which case v2 5.4.1 says we need to re-throw
166 // the previous error.
167 Runtime* const runtime = Runtime::Current();
168 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
169 std::string extra;
170 if (c->GetVerifyError() != nullptr) {
171 mirror::Object* verify_error = c->GetVerifyError();
172 if (verify_error->IsClass()) {
173 extra = PrettyDescriptor(verify_error->AsClass());
174 } else {
175 extra = verify_error->AsThrowable()->Dump();
176 }
177 }
178 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra;
179 }
180
181 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
182 Thread* self = Thread::Current();
183 if (runtime->IsAotCompiler()) {
184 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
185 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
186 self->SetException(pre_allocated);
187 } else {
188 if (c->GetVerifyError() != nullptr) {
189 // Rethrow stored error.
190 HandleEarlierVerifyError(self, this, c);
191 }
192 if (c->GetVerifyError() == nullptr || wrap_in_no_class_def) {
193 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
194 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
195 // exception will be a cause.
196 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
197 PrettyDescriptor(c).c_str());
198 }
199 }
200 }
201
VlogClassInitializationFailure(Handle<mirror::Class> klass)202 static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
203 SHARED_REQUIRES(Locks::mutator_lock_) {
204 if (VLOG_IS_ON(class_linker)) {
205 std::string temp;
206 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
207 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
208 }
209 }
210
WrapExceptionInInitializer(Handle<mirror::Class> klass)211 static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
212 SHARED_REQUIRES(Locks::mutator_lock_) {
213 Thread* self = Thread::Current();
214 JNIEnv* env = self->GetJniEnv();
215
216 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
217 CHECK(cause.get() != nullptr);
218
219 env->ExceptionClear();
220 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
221 env->Throw(cause.get());
222
223 // We only wrap non-Error exceptions; an Error can just be used as-is.
224 if (!is_error) {
225 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
226 }
227 VlogClassInitializationFailure(klass);
228 }
229
230 // Gap between two fields in object layout.
231 struct FieldGap {
232 uint32_t start_offset; // The offset from the start of the object.
233 uint32_t size; // The gap size of 1, 2, or 4 bytes.
234 };
235 struct FieldGapsComparator {
FieldGapsComparatorart::FieldGapsComparator236 explicit FieldGapsComparator() {
237 }
operator ()art::FieldGapsComparator238 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
239 NO_THREAD_SAFETY_ANALYSIS {
240 // Sort by gap size, largest first. Secondary sort by starting offset.
241 // Note that the priority queue returns the largest element, so operator()
242 // should return true if lhs is less than rhs.
243 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
244 }
245 };
246 typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
247
248 // Adds largest aligned gaps to queue of gaps.
AddFieldGap(uint32_t gap_start,uint32_t gap_end,FieldGaps * gaps)249 static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
250 DCHECK(gaps != nullptr);
251
252 uint32_t current_offset = gap_start;
253 while (current_offset != gap_end) {
254 size_t remaining = gap_end - current_offset;
255 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
256 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
257 current_offset += sizeof(uint32_t);
258 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
259 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
260 current_offset += sizeof(uint16_t);
261 } else {
262 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
263 current_offset += sizeof(uint8_t);
264 }
265 DCHECK_LE(current_offset, gap_end) << "Overran gap";
266 }
267 }
268 // Shuffle fields forward, making use of gaps whenever possible.
269 template<int n>
ShuffleForward(size_t * current_field_idx,MemberOffset * field_offset,std::deque<ArtField * > * grouped_and_sorted_fields,FieldGaps * gaps)270 static void ShuffleForward(size_t* current_field_idx,
271 MemberOffset* field_offset,
272 std::deque<ArtField*>* grouped_and_sorted_fields,
273 FieldGaps* gaps)
274 SHARED_REQUIRES(Locks::mutator_lock_) {
275 DCHECK(current_field_idx != nullptr);
276 DCHECK(grouped_and_sorted_fields != nullptr);
277 DCHECK(gaps != nullptr);
278 DCHECK(field_offset != nullptr);
279
280 DCHECK(IsPowerOfTwo(n));
281 while (!grouped_and_sorted_fields->empty()) {
282 ArtField* field = grouped_and_sorted_fields->front();
283 Primitive::Type type = field->GetTypeAsPrimitiveType();
284 if (Primitive::ComponentSize(type) < n) {
285 break;
286 }
287 if (!IsAligned<n>(field_offset->Uint32Value())) {
288 MemberOffset old_offset = *field_offset;
289 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
290 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
291 }
292 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
293 grouped_and_sorted_fields->pop_front();
294 if (!gaps->empty() && gaps->top().size >= n) {
295 FieldGap gap = gaps->top();
296 gaps->pop();
297 DCHECK_ALIGNED(gap.start_offset, n);
298 field->SetOffset(MemberOffset(gap.start_offset));
299 if (gap.size > n) {
300 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
301 }
302 } else {
303 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
304 field->SetOffset(*field_offset);
305 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
306 }
307 ++(*current_field_idx);
308 }
309 }
310
ClassLinker(InternTable * intern_table)311 ClassLinker::ClassLinker(InternTable* intern_table)
312 // dex_lock_ is recursive as it may be used in stack dumping.
313 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
314 dex_cache_boot_image_class_lookup_required_(false),
315 failed_dex_cache_class_lookups_(0),
316 class_roots_(nullptr),
317 array_iftable_(nullptr),
318 find_array_class_cache_next_victim_(0),
319 init_done_(false),
320 log_new_class_table_roots_(false),
321 intern_table_(intern_table),
322 quick_resolution_trampoline_(nullptr),
323 quick_imt_conflict_trampoline_(nullptr),
324 quick_generic_jni_trampoline_(nullptr),
325 quick_to_interpreter_bridge_trampoline_(nullptr),
326 image_pointer_size_(sizeof(void*)) {
327 CHECK(intern_table_ != nullptr);
328 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
329 "Array cache size wrong.");
330 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
331 }
332
CheckSystemClass(Thread * self,Handle<mirror::Class> c1,const char * descriptor)333 void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
334 mirror::Class* c2 = FindSystemClass(self, descriptor);
335 if (c2 == nullptr) {
336 LOG(FATAL) << "Could not find class " << descriptor;
337 UNREACHABLE();
338 }
339 if (c1.Get() != c2) {
340 std::ostringstream os1, os2;
341 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
342 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
343 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
344 << ". This is most likely the result of a broken build. Make sure that "
345 << "libcore and art projects match.\n\n"
346 << os1.str() << "\n\n" << os2.str();
347 UNREACHABLE();
348 }
349 }
350
InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,std::string * error_msg)351 bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
352 std::string* error_msg) {
353 VLOG(startup) << "ClassLinker::Init";
354
355 Thread* const self = Thread::Current();
356 Runtime* const runtime = Runtime::Current();
357 gc::Heap* const heap = runtime->GetHeap();
358
359 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
360 CHECK(!init_done_);
361
362 // Use the pointer size from the runtime since we are probably creating the image.
363 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
364 if (!ValidPointerSize(image_pointer_size_)) {
365 *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_);
366 return false;
367 }
368
369 // java_lang_Class comes first, it's needed for AllocClass
370 // The GC can't handle an object with a null class since we can't get the size of this object.
371 heap->IncrementDisableMovingGC(self);
372 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
373 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
374 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
375 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
376 CHECK(java_lang_Class.Get() != nullptr);
377 mirror::Class::SetClassClass(java_lang_Class.Get());
378 java_lang_Class->SetClass(java_lang_Class.Get());
379 if (kUseBakerOrBrooksReadBarrier) {
380 java_lang_Class->AssertReadBarrierPointer();
381 }
382 java_lang_Class->SetClassSize(class_class_size);
383 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
384 heap->DecrementDisableMovingGC(self);
385 // AllocClass(mirror::Class*) can now be used
386
387 // Class[] is used for reflection support.
388 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
389 Handle<mirror::Class> class_array_class(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
391 class_array_class->SetComponentType(java_lang_Class.Get());
392
393 // java_lang_Object comes next so that object_array_class can be created.
394 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
395 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
396 CHECK(java_lang_Object.Get() != nullptr);
397 // backfill Object as the super class of Class.
398 java_lang_Class->SetSuperClass(java_lang_Object.Get());
399 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
400
401 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
402 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
403 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
404 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
405 java_lang_Object.Get(),
406 java_lang_Object->GetObjectSize(),
407 VoidFunctor()));
408
409 // Object[] next to hold class roots.
410 Handle<mirror::Class> object_array_class(hs.NewHandle(
411 AllocClass(self, java_lang_Class.Get(),
412 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
413 object_array_class->SetComponentType(java_lang_Object.Get());
414
415 // Setup the char (primitive) class to be used for char[].
416 Handle<mirror::Class> char_class(hs.NewHandle(
417 AllocClass(self, java_lang_Class.Get(),
418 mirror::Class::PrimitiveClassSize(image_pointer_size_))));
419 // The primitive char class won't be initialized by
420 // InitializePrimitiveClass until line 459, but strings (and
421 // internal char arrays) will be allocated before that and the
422 // component size, which is computed from the primitive type, needs
423 // to be set here.
424 char_class->SetPrimitiveType(Primitive::kPrimChar);
425
426 // Setup the char[] class to be used for String.
427 Handle<mirror::Class> char_array_class(hs.NewHandle(
428 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
429 char_array_class->SetComponentType(char_class.Get());
430 mirror::CharArray::SetArrayClass(char_array_class.Get());
431
432 // Setup String.
433 Handle<mirror::Class> java_lang_String(hs.NewHandle(
434 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
435 java_lang_String->SetStringClass();
436 mirror::String::SetClass(java_lang_String.Get());
437 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
438
439 // Setup java.lang.ref.Reference.
440 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
441 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
442 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
443 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
444 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
445
446 // Create storage for root classes, save away our work so far (requires descriptors).
447 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
448 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
449 kClassRootsMax));
450 CHECK(!class_roots_.IsNull());
451 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
452 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
453 SetClassRoot(kClassArrayClass, class_array_class.Get());
454 SetClassRoot(kObjectArrayClass, object_array_class.Get());
455 SetClassRoot(kCharArrayClass, char_array_class.Get());
456 SetClassRoot(kJavaLangString, java_lang_String.Get());
457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
458
459 // Setup the primitive type classes.
460 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
461 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
462 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
463 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
464 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
465 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
466 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
467 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
468
469 // Create array interface entries to populate once we can load system classes.
470 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
471
472 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
473 Handle<mirror::Class> int_array_class(hs.NewHandle(
474 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
475 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
476 mirror::IntArray::SetArrayClass(int_array_class.Get());
477 SetClassRoot(kIntArrayClass, int_array_class.Get());
478
479 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
480 Handle<mirror::Class> long_array_class(hs.NewHandle(
481 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
482 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
483 mirror::LongArray::SetArrayClass(long_array_class.Get());
484 SetClassRoot(kLongArrayClass, long_array_class.Get());
485
486 // now that these are registered, we can use AllocClass() and AllocObjectArray
487
488 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
489 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
490 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
491 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
492 java_lang_DexCache->SetDexCacheClass();
493 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
494 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
495
496 // Set up array classes for string, field, method
497 Handle<mirror::Class> object_array_string(hs.NewHandle(
498 AllocClass(self, java_lang_Class.Get(),
499 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
500 object_array_string->SetComponentType(java_lang_String.Get());
501 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
502
503 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
504 // Create runtime resolution and imt conflict methods.
505 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
506 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
507 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
508
509 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
510 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
511 // these roots.
512 if (boot_class_path.empty()) {
513 *error_msg = "Boot classpath is empty.";
514 return false;
515 }
516 for (auto& dex_file : boot_class_path) {
517 if (dex_file.get() == nullptr) {
518 *error_msg = "Null dex file.";
519 return false;
520 }
521 AppendToBootClassPath(self, *dex_file);
522 boot_dex_files_.push_back(std::move(dex_file));
523 }
524
525 // now we can use FindSystemClass
526
527 // run char class through InitializePrimitiveClass to finish init
528 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
529 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
530
531 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
532 // we do not need friend classes or a publicly exposed setter.
533 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
534 if (!runtime->IsAotCompiler()) {
535 // We need to set up the generic trampolines since we don't have an image.
536 quick_resolution_trampoline_ = GetQuickResolutionStub();
537 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
538 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
539 }
540
541 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
542 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
543 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
544 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
545 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
546 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
547 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
548 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
549 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
550
551 // Setup the primitive array type classes - can't be done until Object has a vtable.
552 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
553 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
554
555 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
556 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
557
558 CheckSystemClass(self, char_array_class, "[C");
559
560 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
561 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
562
563 CheckSystemClass(self, int_array_class, "[I");
564 CheckSystemClass(self, long_array_class, "[J");
565
566 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
567 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
568
569 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
570 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
571
572 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
573 // in class_table_.
574 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
575
576 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
577 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
578
579 // Setup the single, global copy of "iftable".
580 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
581 CHECK(java_lang_Cloneable.Get() != nullptr);
582 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
583 CHECK(java_io_Serializable.Get() != nullptr);
584 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
585 // crawl up and explicitly list all of the supers as well.
586 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
587 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
588
589 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
590 // suspension.
591 CHECK_EQ(java_lang_Cloneable.Get(),
592 mirror::Class::GetDirectInterface(self, class_array_class, 0));
593 CHECK_EQ(java_io_Serializable.Get(),
594 mirror::Class::GetDirectInterface(self, class_array_class, 1));
595 CHECK_EQ(java_lang_Cloneable.Get(),
596 mirror::Class::GetDirectInterface(self, object_array_class, 0));
597 CHECK_EQ(java_io_Serializable.Get(),
598 mirror::Class::GetDirectInterface(self, object_array_class, 1));
599
600 CHECK_EQ(object_array_string.Get(),
601 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
602
603 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
604
605 // Create java.lang.reflect.Proxy root.
606 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
607
608 // Create java.lang.reflect.Field.class root.
609 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
610 CHECK(class_root != nullptr);
611 SetClassRoot(kJavaLangReflectField, class_root);
612 mirror::Field::SetClass(class_root);
613
614 // Create java.lang.reflect.Field array root.
615 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
616 CHECK(class_root != nullptr);
617 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
618 mirror::Field::SetArrayClass(class_root);
619
620 // Create java.lang.reflect.Constructor.class root and array root.
621 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
622 CHECK(class_root != nullptr);
623 SetClassRoot(kJavaLangReflectConstructor, class_root);
624 mirror::Constructor::SetClass(class_root);
625 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
626 CHECK(class_root != nullptr);
627 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
628 mirror::Constructor::SetArrayClass(class_root);
629
630 // Create java.lang.reflect.Method.class root and array root.
631 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
632 CHECK(class_root != nullptr);
633 SetClassRoot(kJavaLangReflectMethod, class_root);
634 mirror::Method::SetClass(class_root);
635 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
636 CHECK(class_root != nullptr);
637 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
638 mirror::Method::SetArrayClass(class_root);
639
640 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
641 // finish initializing Reference class
642 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
643 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
644 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
645 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
646 mirror::Reference::ClassSize(image_pointer_size_));
647 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
648 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
649 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
650 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
651 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
652 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
653 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
654 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
655 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
656 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
657 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
658 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
659
660 // Setup the ClassLoader, verifying the object_size_.
661 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
662 class_root->SetClassLoaderClass();
663 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
664 SetClassRoot(kJavaLangClassLoader, class_root);
665
666 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
667 // java.lang.StackTraceElement as a convenience.
668 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
669 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
670 SetClassRoot(kJavaLangClassNotFoundException,
671 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
672 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
673 SetClassRoot(kJavaLangStackTraceElementArrayClass,
674 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
675 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
676
677 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
678 // initialized.
679 {
680 const DexFile& dex_file = java_lang_Object->GetDexFile();
681 const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V");
682 CHECK(void_type_id != nullptr);
683 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
684 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
685 // as referrer so the used dex cache is core's one.
686 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
687 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
688 self->AssertNoPendingException();
689 }
690
691 // Create conflict tables that depend on the class linker.
692 runtime->FixupConflictTables();
693
694 FinishInit(self);
695
696 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
697
698 return true;
699 }
700
FinishInit(Thread * self)701 void ClassLinker::FinishInit(Thread* self) {
702 VLOG(startup) << "ClassLinker::FinishInit entering";
703
704 // Let the heap know some key offsets into java.lang.ref instances
705 // Note: we hard code the field indexes here rather than using FindInstanceField
706 // as the types of the field can't be resolved prior to the runtime being
707 // fully initialized
708 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
709 mirror::Class* java_lang_ref_FinalizerReference =
710 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
711
712 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
713 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
714 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
715
716 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
717 CHECK_STREQ(queue->GetName(), "queue");
718 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
719
720 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
721 CHECK_STREQ(queueNext->GetName(), "queueNext");
722 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
723
724 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
725 CHECK_STREQ(referent->GetName(), "referent");
726 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
727
728 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
729 CHECK_STREQ(zombie->GetName(), "zombie");
730 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
731
732 // ensure all class_roots_ are initialized
733 for (size_t i = 0; i < kClassRootsMax; i++) {
734 ClassRoot class_root = static_cast<ClassRoot>(i);
735 mirror::Class* klass = GetClassRoot(class_root);
736 CHECK(klass != nullptr);
737 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
738 // note SetClassRoot does additional validation.
739 // if possible add new checks there to catch errors early
740 }
741
742 CHECK(!array_iftable_.IsNull());
743
744 // disable the slow paths in FindClass and CreatePrimitiveClass now
745 // that Object, Class, and Object[] are setup
746 init_done_ = true;
747
748 VLOG(startup) << "ClassLinker::FinishInit exiting";
749 }
750
RunRootClinits()751 void ClassLinker::RunRootClinits() {
752 Thread* self = Thread::Current();
753 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
754 mirror::Class* c = GetClassRoot(ClassRoot(i));
755 if (!c->IsArrayClass() && !c->IsPrimitive()) {
756 StackHandleScope<1> hs(self);
757 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
758 EnsureInitialized(self, h_class, true, true);
759 self->AssertNoPendingException();
760 }
761 }
762 }
763
SanityCheckArtMethod(ArtMethod * m,mirror::Class * expected_class,const std::vector<gc::space::ImageSpace * > & spaces)764 static void SanityCheckArtMethod(ArtMethod* m,
765 mirror::Class* expected_class,
766 const std::vector<gc::space::ImageSpace*>& spaces)
767 SHARED_REQUIRES(Locks::mutator_lock_) {
768 if (m->IsRuntimeMethod()) {
769 mirror::Class* declaring_class = m->GetDeclaringClassUnchecked();
770 CHECK(declaring_class == nullptr) << declaring_class << " " << PrettyMethod(m);
771 } else if (m->IsCopied()) {
772 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m);
773 } else if (expected_class != nullptr) {
774 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m);
775 }
776 if (!spaces.empty()) {
777 bool contains = false;
778 for (gc::space::ImageSpace* space : spaces) {
779 auto& header = space->GetImageHeader();
780 size_t offset = reinterpret_cast<uint8_t*>(m) - space->Begin();
781
782 const ImageSection& methods = header.GetMethodsSection();
783 contains = contains || methods.Contains(offset);
784
785 const ImageSection& runtime_methods = header.GetRuntimeMethodsSection();
786 contains = contains || runtime_methods.Contains(offset);
787 }
788 CHECK(contains) << m << " not found";
789 }
790 }
791
SanityCheckArtMethodPointerArray(mirror::PointerArray * arr,mirror::Class * expected_class,size_t pointer_size,const std::vector<gc::space::ImageSpace * > & spaces)792 static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
793 mirror::Class* expected_class,
794 size_t pointer_size,
795 const std::vector<gc::space::ImageSpace*>& spaces)
796 SHARED_REQUIRES(Locks::mutator_lock_) {
797 CHECK(arr != nullptr);
798 for (int32_t j = 0; j < arr->GetLength(); ++j) {
799 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
800 // expected_class == null means we are a dex cache.
801 if (expected_class != nullptr) {
802 CHECK(method != nullptr);
803 }
804 if (method != nullptr) {
805 SanityCheckArtMethod(method, expected_class, spaces);
806 }
807 }
808 }
809
SanityCheckArtMethodPointerArray(ArtMethod ** arr,size_t size,size_t pointer_size,const std::vector<gc::space::ImageSpace * > & spaces)810 static void SanityCheckArtMethodPointerArray(ArtMethod** arr,
811 size_t size,
812 size_t pointer_size,
813 const std::vector<gc::space::ImageSpace*>& spaces)
814 SHARED_REQUIRES(Locks::mutator_lock_) {
815 CHECK_EQ(arr != nullptr, size != 0u);
816 if (arr != nullptr) {
817 bool contains = false;
818 for (auto space : spaces) {
819 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
820 if (space->GetImageHeader().GetImageSection(
821 ImageHeader::kSectionDexCacheArrays).Contains(offset)) {
822 contains = true;
823 break;
824 }
825 }
826 CHECK(contains);
827 }
828 for (size_t j = 0; j < size; ++j) {
829 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size);
830 // expected_class == null means we are a dex cache.
831 if (method != nullptr) {
832 SanityCheckArtMethod(method, nullptr, spaces);
833 }
834 }
835 }
836
SanityCheckObjectsCallback(mirror::Object * obj,void * arg ATTRIBUTE_UNUSED)837 static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
838 SHARED_REQUIRES(Locks::mutator_lock_) {
839 DCHECK(obj != nullptr);
840 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
841 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
842 if (obj->IsClass()) {
843 auto klass = obj->AsClass();
844 for (ArtField& field : klass->GetIFields()) {
845 CHECK_EQ(field.GetDeclaringClass(), klass);
846 }
847 for (ArtField& field : klass->GetSFields()) {
848 CHECK_EQ(field.GetDeclaringClass(), klass);
849 }
850 auto* runtime = Runtime::Current();
851 auto image_spaces = runtime->GetHeap()->GetBootImageSpaces();
852 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
853 for (auto& m : klass->GetMethods(pointer_size)) {
854 SanityCheckArtMethod(&m, klass, image_spaces);
855 }
856 auto* vtable = klass->GetVTable();
857 if (vtable != nullptr) {
858 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_spaces);
859 }
860 if (klass->ShouldHaveImt()) {
861 ImTable* imt = klass->GetImt(pointer_size);
862 for (size_t i = 0; i < ImTable::kSize; ++i) {
863 SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr, image_spaces);
864 }
865 }
866 if (klass->ShouldHaveEmbeddedVTable()) {
867 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
868 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_spaces);
869 }
870 }
871 auto* iftable = klass->GetIfTable();
872 if (iftable != nullptr) {
873 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
874 if (iftable->GetMethodArrayCount(i) > 0) {
875 SanityCheckArtMethodPointerArray(
876 iftable->GetMethodArray(i), nullptr, pointer_size, image_spaces);
877 }
878 }
879 }
880 }
881 }
882
883 // Set image methods' entry point to interpreter.
884 class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
885 public:
SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)886 explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)
887 : image_pointer_size_(image_pointer_size) {}
888
Visit(ArtMethod * method)889 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
890 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
891 CHECK(method->GetDeclaringClass() != nullptr);
892 }
893 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
894 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
895 image_pointer_size_);
896 }
897 }
898
899 private:
900 const size_t image_pointer_size_;
901
902 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
903 };
904
905 struct TrampolineCheckData {
906 const void* quick_resolution_trampoline;
907 const void* quick_imt_conflict_trampoline;
908 const void* quick_generic_jni_trampoline;
909 const void* quick_to_interpreter_bridge_trampoline;
910 size_t pointer_size;
911 ArtMethod* m;
912 bool error;
913 };
914
CheckTrampolines(mirror::Object * obj,void * arg)915 static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS {
916 if (obj->IsClass()) {
917 mirror::Class* klass = obj->AsClass();
918 TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg);
919 for (ArtMethod& m : klass->GetMethods(d->pointer_size)) {
920 const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size);
921 if (entrypoint == d->quick_resolution_trampoline ||
922 entrypoint == d->quick_imt_conflict_trampoline ||
923 entrypoint == d->quick_generic_jni_trampoline ||
924 entrypoint == d->quick_to_interpreter_bridge_trampoline) {
925 d->m = &m;
926 d->error = true;
927 return;
928 }
929 }
930 }
931 }
932
InitFromBootImage(std::string * error_msg)933 bool ClassLinker::InitFromBootImage(std::string* error_msg) {
934 VLOG(startup) << __FUNCTION__ << " entering";
935 CHECK(!init_done_);
936
937 Runtime* const runtime = Runtime::Current();
938 Thread* const self = Thread::Current();
939 gc::Heap* const heap = runtime->GetHeap();
940 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
941 CHECK(!spaces.empty());
942 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
943 if (!ValidPointerSize(image_pointer_size_)) {
944 *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_);
945 return false;
946 }
947 if (!runtime->IsAotCompiler()) {
948 // Only the Aot compiler supports having an image with a different pointer size than the
949 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
950 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
951 if (image_pointer_size_ != sizeof(void*)) {
952 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
953 image_pointer_size_,
954 sizeof(void*));
955 return false;
956 }
957 }
958 dex_cache_boot_image_class_lookup_required_ = true;
959 std::vector<const OatFile*> oat_files =
960 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
961 DCHECK(!oat_files.empty());
962 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
963 CHECK_EQ(default_oat_header.GetImageFileLocationOatChecksum(), 0U);
964 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
965 const char* image_file_location = oat_files[0]->GetOatHeader().
966 GetStoreValueByKey(OatHeader::kImageLocationKey);
967 CHECK(image_file_location == nullptr || *image_file_location == 0);
968 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
969 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
970 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
971 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
972 if (kIsDebugBuild) {
973 // Check that the other images use the same trampoline.
974 for (size_t i = 1; i < oat_files.size(); ++i) {
975 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
976 const void* ith_quick_resolution_trampoline =
977 ith_oat_header.GetQuickResolutionTrampoline();
978 const void* ith_quick_imt_conflict_trampoline =
979 ith_oat_header.GetQuickImtConflictTrampoline();
980 const void* ith_quick_generic_jni_trampoline =
981 ith_oat_header.GetQuickGenericJniTrampoline();
982 const void* ith_quick_to_interpreter_bridge_trampoline =
983 ith_oat_header.GetQuickToInterpreterBridge();
984 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
985 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
986 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
987 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
988 // Make sure that all methods in this image do not contain those trampolines as
989 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
990 TrampolineCheckData data;
991 data.error = false;
992 data.pointer_size = GetImagePointerSize();
993 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
994 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
995 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
996 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
997 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
998 spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data);
999 if (data.error) {
1000 ArtMethod* m = data.m;
1001 LOG(ERROR) << "Found a broken ArtMethod: " << PrettyMethod(m);
1002 *error_msg = "Found an ArtMethod with a bad entrypoint";
1003 return false;
1004 }
1005 }
1006 }
1007 }
1008
1009 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1010 down_cast<mirror::ObjectArray<mirror::Class>*>(
1011 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1012 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
1013
1014 // Special case of setting up the String class early so that we can test arbitrary objects
1015 // as being Strings or not
1016 mirror::String::SetClass(GetClassRoot(kJavaLangString));
1017
1018 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
1019 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
1020 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1021 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
1022 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1023 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
1024
1025 // reinit array_iftable_ from any array class instance, they should be ==
1026 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1027 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
1028 // String class root was set above
1029 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1030 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
1031 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1032 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1033 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1034 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
1035 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
1036 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1037 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1038 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1039 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1040 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1041 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1042 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1043 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1044 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1045 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
1046
1047 for (gc::space::ImageSpace* image_space : spaces) {
1048 // Boot class loader, use a null handle.
1049 std::vector<std::unique_ptr<const DexFile>> dex_files;
1050 if (!AddImageSpace(image_space,
1051 ScopedNullHandle<mirror::ClassLoader>(),
1052 /*dex_elements*/nullptr,
1053 /*dex_location*/nullptr,
1054 /*out*/&dex_files,
1055 error_msg)) {
1056 return false;
1057 }
1058 // Append opened dex files at the end.
1059 boot_dex_files_.insert(boot_dex_files_.end(),
1060 std::make_move_iterator(dex_files.begin()),
1061 std::make_move_iterator(dex_files.end()));
1062 }
1063 FinishInit(self);
1064
1065 VLOG(startup) << __FUNCTION__ << " exiting";
1066 return true;
1067 }
1068
IsBootClassLoader(ScopedObjectAccessAlreadyRunnable & soa,mirror::ClassLoader * class_loader)1069 bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1070 mirror::ClassLoader* class_loader) {
1071 return class_loader == nullptr ||
1072 class_loader->GetClass() ==
1073 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1074 }
1075
GetDexPathListElementName(ScopedObjectAccessUnchecked & soa,mirror::Object * element)1076 static mirror::String* GetDexPathListElementName(ScopedObjectAccessUnchecked& soa,
1077 mirror::Object* element)
1078 SHARED_REQUIRES(Locks::mutator_lock_) {
1079 ArtField* const dex_file_field =
1080 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1081 ArtField* const dex_file_name_field =
1082 soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
1083 DCHECK(dex_file_field != nullptr);
1084 DCHECK(dex_file_name_field != nullptr);
1085 DCHECK(element != nullptr);
1086 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << PrettyTypeOf(element);
1087 mirror::Object* dex_file = dex_file_field->GetObject(element);
1088 if (dex_file == nullptr) {
1089 return nullptr;
1090 }
1091 mirror::Object* const name_object = dex_file_name_field->GetObject(dex_file);
1092 if (name_object != nullptr) {
1093 return name_object->AsString();
1094 }
1095 return nullptr;
1096 }
1097
FlattenPathClassLoader(mirror::ClassLoader * class_loader,std::list<mirror::String * > * out_dex_file_names,std::string * error_msg)1098 static bool FlattenPathClassLoader(mirror::ClassLoader* class_loader,
1099 std::list<mirror::String*>* out_dex_file_names,
1100 std::string* error_msg)
1101 SHARED_REQUIRES(Locks::mutator_lock_) {
1102 DCHECK(out_dex_file_names != nullptr);
1103 DCHECK(error_msg != nullptr);
1104 ScopedObjectAccessUnchecked soa(Thread::Current());
1105 ArtField* const dex_path_list_field =
1106 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
1107 ArtField* const dex_elements_field =
1108 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
1109 CHECK(dex_path_list_field != nullptr);
1110 CHECK(dex_elements_field != nullptr);
1111 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
1112 if (class_loader->GetClass() !=
1113 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1114 *error_msg = StringPrintf("Unknown class loader type %s", PrettyTypeOf(class_loader).c_str());
1115 // Unsupported class loader.
1116 return false;
1117 }
1118 mirror::Object* dex_path_list = dex_path_list_field->GetObject(class_loader);
1119 if (dex_path_list != nullptr) {
1120 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1121 mirror::Object* dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
1122 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1123 // at the mCookie which is a DexFile vector.
1124 if (dex_elements_obj != nullptr) {
1125 mirror::ObjectArray<mirror::Object>* dex_elements =
1126 dex_elements_obj->AsObjectArray<mirror::Object>();
1127 // Reverse order since we insert the parent at the front.
1128 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
1129 mirror::Object* const element = dex_elements->GetWithoutChecks(i);
1130 if (element == nullptr) {
1131 *error_msg = StringPrintf("Null dex element at index %d", i);
1132 return false;
1133 }
1134 mirror::String* const name = GetDexPathListElementName(soa, element);
1135 if (name == nullptr) {
1136 *error_msg = StringPrintf("Null name for dex element at index %d", i);
1137 return false;
1138 }
1139 out_dex_file_names->push_front(name);
1140 }
1141 }
1142 }
1143 class_loader = class_loader->GetParent();
1144 }
1145 return true;
1146 }
1147
1148 class FixupArtMethodArrayVisitor : public ArtMethodVisitor {
1149 public:
FixupArtMethodArrayVisitor(const ImageHeader & header)1150 explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {}
1151
Visit(ArtMethod * method)1152 virtual void Visit(ArtMethod* method) SHARED_REQUIRES(Locks::mutator_lock_) {
1153 GcRoot<mirror::Class>* resolved_types = method->GetDexCacheResolvedTypes(sizeof(void*));
1154 const bool is_copied = method->IsCopied();
1155 if (resolved_types != nullptr) {
1156 bool in_image_space = false;
1157 if (kIsDebugBuild || is_copied) {
1158 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1159 reinterpret_cast<const uint8_t*>(resolved_types) - header_.GetImageBegin());
1160 }
1161 // Must be in image space for non-miranda method.
1162 DCHECK(is_copied || in_image_space)
1163 << resolved_types << " is not in image starting at "
1164 << reinterpret_cast<void*>(header_.GetImageBegin());
1165 if (!is_copied || in_image_space) {
1166 // Go through the array so that we don't need to do a slow map lookup.
1167 method->SetDexCacheResolvedTypes(*reinterpret_cast<GcRoot<mirror::Class>**>(resolved_types),
1168 sizeof(void*));
1169 }
1170 }
1171 ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(sizeof(void*));
1172 if (resolved_methods != nullptr) {
1173 bool in_image_space = false;
1174 if (kIsDebugBuild || is_copied) {
1175 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1176 reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin());
1177 }
1178 // Must be in image space for non-miranda method.
1179 DCHECK(is_copied || in_image_space)
1180 << resolved_methods << " is not in image starting at "
1181 << reinterpret_cast<void*>(header_.GetImageBegin());
1182 if (!is_copied || in_image_space) {
1183 // Go through the array so that we don't need to do a slow map lookup.
1184 method->SetDexCacheResolvedMethods(*reinterpret_cast<ArtMethod***>(resolved_methods),
1185 sizeof(void*));
1186 }
1187 }
1188 }
1189
1190 private:
1191 const ImageHeader& header_;
1192 };
1193
1194 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1195 public:
VerifyClassInTableArtMethodVisitor(ClassTable * table)1196 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1197
Visit(ArtMethod * method)1198 virtual void Visit(ArtMethod* method)
1199 SHARED_REQUIRES(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1200 mirror::Class* klass = method->GetDeclaringClass();
1201 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1202 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << PrettyClass(klass);
1203 }
1204 }
1205
1206 private:
1207 ClassTable* const table_;
1208 };
1209
1210 class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1211 public:
SHARED_REQUIRES(Locks::mutator_lock_,Locks::heap_bitmap_lock_)1212 VerifyDeclaringClassVisitor() SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1213 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1214
Visit(ArtMethod * method)1215 virtual void Visit(ArtMethod* method)
1216 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1217 mirror::Class* klass = method->GetDeclaringClassUnchecked();
1218 if (klass != nullptr) {
1219 CHECK(live_bitmap_->Test(klass)) << "Image method has unmarked declaring class";
1220 }
1221 }
1222
1223 private:
1224 gc::accounting::HeapBitmap* const live_bitmap_;
1225 };
1226
UpdateAppImageClassLoadersAndDexCaches(gc::space::ImageSpace * space,Handle<mirror::ClassLoader> class_loader,Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,ClassTable::ClassSet * new_class_set,bool * out_forward_dex_cache_array,std::string * out_error_msg)1227 bool ClassLinker::UpdateAppImageClassLoadersAndDexCaches(
1228 gc::space::ImageSpace* space,
1229 Handle<mirror::ClassLoader> class_loader,
1230 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
1231 ClassTable::ClassSet* new_class_set,
1232 bool* out_forward_dex_cache_array,
1233 std::string* out_error_msg) {
1234 DCHECK(out_forward_dex_cache_array != nullptr);
1235 DCHECK(out_error_msg != nullptr);
1236 Thread* const self = Thread::Current();
1237 gc::Heap* const heap = Runtime::Current()->GetHeap();
1238 const ImageHeader& header = space->GetImageHeader();
1239 {
1240 // Add image classes into the class table for the class loader, and fixup the dex caches and
1241 // class loader fields.
1242 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1243 ClassTable* table = InsertClassTableForClassLoader(class_loader.Get());
1244 // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we
1245 // rely on clobering the dex cache arrays in the image to forward to bss.
1246 size_t num_dex_caches_with_bss_arrays = 0;
1247 const size_t num_dex_caches = dex_caches->GetLength();
1248 for (size_t i = 0; i < num_dex_caches; i++) {
1249 mirror::DexCache* const dex_cache = dex_caches->Get(i);
1250 const DexFile* const dex_file = dex_cache->GetDexFile();
1251 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1252 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1253 ++num_dex_caches_with_bss_arrays;
1254 }
1255 }
1256 *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0;
1257 if (*out_forward_dex_cache_array) {
1258 if (num_dex_caches_with_bss_arrays != num_dex_caches) {
1259 // Reject application image since we cannot forward only some of the dex cache arrays.
1260 // TODO: We could get around this by having a dedicated forwarding slot. It should be an
1261 // uncommon case.
1262 *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu",
1263 num_dex_caches_with_bss_arrays,
1264 num_dex_caches);
1265 return false;
1266 }
1267 }
1268 // Only add the classes to the class loader after the points where we can return false.
1269 for (size_t i = 0; i < num_dex_caches; i++) {
1270 mirror::DexCache* const dex_cache = dex_caches->Get(i);
1271 const DexFile* const dex_file = dex_cache->GetDexFile();
1272 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1273 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1274 // If the oat file expects the dex cache arrays to be in the BSS, then allocate there and
1275 // copy over the arrays.
1276 DCHECK(dex_file != nullptr);
1277 const size_t num_strings = dex_file->NumStringIds();
1278 const size_t num_types = dex_file->NumTypeIds();
1279 const size_t num_methods = dex_file->NumMethodIds();
1280 const size_t num_fields = dex_file->NumFieldIds();
1281 CHECK_EQ(num_strings, dex_cache->NumStrings());
1282 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
1283 CHECK_EQ(num_methods, dex_cache->NumResolvedMethods());
1284 CHECK_EQ(num_fields, dex_cache->NumResolvedFields());
1285 DexCacheArraysLayout layout(image_pointer_size_, dex_file);
1286 uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays();
1287 // The space is not yet visible to the GC, we can avoid the read barriers and use
1288 // std::copy_n.
1289 if (num_strings != 0u) {
1290 GcRoot<mirror::String>* const image_resolved_strings = dex_cache->GetStrings();
1291 GcRoot<mirror::String>* const strings =
1292 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
1293 for (size_t j = 0; kIsDebugBuild && j < num_strings; ++j) {
1294 DCHECK(strings[j].IsNull());
1295 }
1296 std::copy_n(image_resolved_strings, num_strings, strings);
1297 dex_cache->SetStrings(strings);
1298 }
1299 if (num_types != 0u) {
1300 GcRoot<mirror::Class>* const image_resolved_types = dex_cache->GetResolvedTypes();
1301 GcRoot<mirror::Class>* const types =
1302 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1303 for (size_t j = 0; kIsDebugBuild && j < num_types; ++j) {
1304 DCHECK(types[j].IsNull());
1305 }
1306 std::copy_n(image_resolved_types, num_types, types);
1307 // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1308 // This leaves random garbage at the start of the dex cache array, but nobody should ever
1309 // read from it again.
1310 *reinterpret_cast<GcRoot<mirror::Class>**>(image_resolved_types) = types;
1311 dex_cache->SetResolvedTypes(types);
1312 }
1313 if (num_methods != 0u) {
1314 ArtMethod** const methods = reinterpret_cast<ArtMethod**>(
1315 raw_arrays + layout.MethodsOffset());
1316 ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods();
1317 for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) {
1318 DCHECK(methods[j] == nullptr);
1319 }
1320 std::copy_n(image_resolved_methods, num_methods, methods);
1321 // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1322 *reinterpret_cast<ArtMethod***>(image_resolved_methods) = methods;
1323 dex_cache->SetResolvedMethods(methods);
1324 }
1325 if (num_fields != 0u) {
1326 ArtField** const fields =
1327 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1328 for (size_t j = 0; kIsDebugBuild && j < num_fields; ++j) {
1329 DCHECK(fields[j] == nullptr);
1330 }
1331 std::copy_n(dex_cache->GetResolvedFields(), num_fields, fields);
1332 dex_cache->SetResolvedFields(fields);
1333 }
1334 }
1335 {
1336 WriterMutexLock mu2(self, dex_lock_);
1337 // Make sure to do this after we update the arrays since we store the resolved types array
1338 // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the
1339 // BSS.
1340 mirror::DexCache* existing_dex_cache = FindDexCacheLocked(self,
1341 *dex_file,
1342 /*allow_failure*/true);
1343 CHECK(existing_dex_cache == nullptr);
1344 StackHandleScope<1> hs3(self);
1345 RegisterDexFileLocked(*dex_file, hs3.NewHandle(dex_cache));
1346 }
1347 GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes();
1348 const size_t num_types = dex_cache->NumResolvedTypes();
1349 if (new_class_set == nullptr) {
1350 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
1351 // The image space is not yet added to the heap, avoid read barriers.
1352 mirror::Class* klass = types[j].Read();
1353 // There may also be boot image classes,
1354 if (space->HasAddress(klass)) {
1355 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1356 // Update the class loader from the one in the image class loader to the one that loaded
1357 // the app image.
1358 klass->SetClassLoader(class_loader.Get());
1359 // The resolved type could be from another dex cache, go through the dex cache just in
1360 // case. May be null for array classes.
1361 if (klass->GetDexCacheStrings() != nullptr) {
1362 DCHECK(!klass->IsArrayClass());
1363 klass->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1364 }
1365 // If there are multiple dex caches, there may be the same class multiple times
1366 // in different dex caches. Check for this since inserting will add duplicates
1367 // otherwise.
1368 if (num_dex_caches > 1) {
1369 mirror::Class* existing = table->LookupByDescriptor(klass);
1370 if (existing != nullptr) {
1371 DCHECK_EQ(existing, klass) << PrettyClass(klass);
1372 } else {
1373 table->Insert(klass);
1374 }
1375 } else {
1376 table->Insert(klass);
1377 }
1378 // Double checked VLOG to avoid overhead.
1379 if (VLOG_IS_ON(image)) {
1380 VLOG(image) << PrettyClass(klass) << " " << klass->GetStatus();
1381 if (!klass->IsArrayClass()) {
1382 VLOG(image) << "From " << klass->GetDexCache()->GetDexFile()->GetBaseLocation();
1383 }
1384 VLOG(image) << "Direct methods";
1385 for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) {
1386 VLOG(image) << PrettyMethod(&m);
1387 }
1388 VLOG(image) << "Virtual methods";
1389 for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) {
1390 VLOG(image) << PrettyMethod(&m);
1391 }
1392 }
1393 } else {
1394 DCHECK(klass == nullptr || heap->ObjectIsInBootImageSpace(klass))
1395 << klass << " " << PrettyClass(klass);
1396 }
1397 }
1398 }
1399 if (kIsDebugBuild) {
1400 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
1401 // The image space is not yet added to the heap, avoid read barriers.
1402 mirror::Class* klass = types[j].Read();
1403 if (space->HasAddress(klass)) {
1404 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1405 if (kIsDebugBuild) {
1406 if (new_class_set != nullptr) {
1407 auto it = new_class_set->Find(GcRoot<mirror::Class>(klass));
1408 DCHECK(it != new_class_set->end());
1409 DCHECK_EQ(it->Read(), klass);
1410 mirror::Class* super_class = klass->GetSuperClass();
1411 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
1412 auto it2 = new_class_set->Find(GcRoot<mirror::Class>(super_class));
1413 DCHECK(it2 != new_class_set->end());
1414 DCHECK_EQ(it2->Read(), super_class);
1415 }
1416 } else {
1417 DCHECK_EQ(table->LookupByDescriptor(klass), klass);
1418 mirror::Class* super_class = klass->GetSuperClass();
1419 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
1420 CHECK_EQ(table->LookupByDescriptor(super_class), super_class);
1421 }
1422 }
1423 }
1424 if (kIsDebugBuild) {
1425 for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) {
1426 const void* code = m.GetEntryPointFromQuickCompiledCode();
1427 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1428 if (!IsQuickResolutionStub(code) &&
1429 !IsQuickGenericJniStub(code) &&
1430 !IsQuickToInterpreterBridge(code) &&
1431 !m.IsNative()) {
1432 DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
1433 }
1434 }
1435 for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) {
1436 const void* code = m.GetEntryPointFromQuickCompiledCode();
1437 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1438 if (!IsQuickResolutionStub(code) &&
1439 !IsQuickGenericJniStub(code) &&
1440 !IsQuickToInterpreterBridge(code) &&
1441 !m.IsNative()) {
1442 DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
1443 }
1444 }
1445 }
1446 }
1447 }
1448 }
1449 }
1450 }
1451 if (*out_forward_dex_cache_array) {
1452 ScopedTrace timing("Fixup ArtMethod dex cache arrays");
1453 FixupArtMethodArrayVisitor visitor(header);
1454 header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*));
1455 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
1456 }
1457 if (kVerifyArtMethodDeclaringClasses) {
1458 ScopedTrace timing("Verify declaring classes");
1459 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1460 VerifyDeclaringClassVisitor visitor;
1461 header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*));
1462 }
1463 return true;
1464 }
1465
1466 // Update the class loader and resolved string dex cache array of classes. Should only be used on
1467 // classes in the image space.
1468 class UpdateClassLoaderAndResolvedStringsVisitor {
1469 public:
UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace * space,mirror::ClassLoader * class_loader,bool forward_strings)1470 UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace* space,
1471 mirror::ClassLoader* class_loader,
1472 bool forward_strings)
1473 : space_(space),
1474 class_loader_(class_loader),
1475 forward_strings_(forward_strings) {}
1476
operator ()(mirror::Class * klass) const1477 bool operator()(mirror::Class* klass) const SHARED_REQUIRES(Locks::mutator_lock_) {
1478 if (forward_strings_) {
1479 GcRoot<mirror::String>* strings = klass->GetDexCacheStrings();
1480 if (strings != nullptr) {
1481 DCHECK(
1482 space_->GetImageHeader().GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1483 reinterpret_cast<uint8_t*>(strings) - space_->Begin()))
1484 << "String dex cache array for " << PrettyClass(klass) << " is not in app image";
1485 // Dex caches have already been updated, so take the strings pointer from there.
1486 GcRoot<mirror::String>* new_strings = klass->GetDexCache()->GetStrings();
1487 DCHECK_NE(strings, new_strings);
1488 klass->SetDexCacheStrings(new_strings);
1489 }
1490 }
1491 // Finally, update class loader.
1492 klass->SetClassLoader(class_loader_);
1493 return true;
1494 }
1495
1496 gc::space::ImageSpace* const space_;
1497 mirror::ClassLoader* const class_loader_;
1498 const bool forward_strings_;
1499 };
1500
OpenOatDexFile(const OatFile * oat_file,const char * location,std::string * error_msg)1501 static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1502 const char* location,
1503 std::string* error_msg)
1504 SHARED_REQUIRES(Locks::mutator_lock_) {
1505 DCHECK(error_msg != nullptr);
1506 std::unique_ptr<const DexFile> dex_file;
1507 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr);
1508 if (oat_dex_file == nullptr) {
1509 *error_msg = StringPrintf("Failed finding oat dex file for %s %s",
1510 oat_file->GetLocation().c_str(),
1511 location);
1512 return std::unique_ptr<const DexFile>();
1513 }
1514 std::string inner_error_msg;
1515 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1516 if (dex_file == nullptr) {
1517 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1518 location,
1519 oat_file->GetLocation().c_str(),
1520 inner_error_msg.c_str());
1521 return std::unique_ptr<const DexFile>();
1522 }
1523
1524 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1525 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1526 location,
1527 dex_file->GetLocationChecksum(),
1528 oat_dex_file->GetDexFileLocationChecksum());
1529 return std::unique_ptr<const DexFile>();
1530 }
1531 return dex_file;
1532 }
1533
OpenImageDexFiles(gc::space::ImageSpace * space,std::vector<std::unique_ptr<const DexFile>> * out_dex_files,std::string * error_msg)1534 bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1535 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1536 std::string* error_msg) {
1537 ScopedAssertNoThreadSuspension nts(Thread::Current(), __FUNCTION__);
1538 const ImageHeader& header = space->GetImageHeader();
1539 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1540 DCHECK(dex_caches_object != nullptr);
1541 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1542 dex_caches_object->AsObjectArray<mirror::DexCache>();
1543 const OatFile* oat_file = space->GetOatFile();
1544 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1545 mirror::DexCache* dex_cache = dex_caches->Get(i);
1546 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1547 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1548 dex_file_location.c_str(),
1549 error_msg);
1550 if (dex_file == nullptr) {
1551 return false;
1552 }
1553 dex_cache->SetDexFile(dex_file.get());
1554 out_dex_files->push_back(std::move(dex_file));
1555 }
1556 return true;
1557 }
1558
AddImageSpace(gc::space::ImageSpace * space,Handle<mirror::ClassLoader> class_loader,jobjectArray dex_elements,const char * dex_location,std::vector<std::unique_ptr<const DexFile>> * out_dex_files,std::string * error_msg)1559 bool ClassLinker::AddImageSpace(
1560 gc::space::ImageSpace* space,
1561 Handle<mirror::ClassLoader> class_loader,
1562 jobjectArray dex_elements,
1563 const char* dex_location,
1564 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1565 std::string* error_msg) {
1566 DCHECK(out_dex_files != nullptr);
1567 DCHECK(error_msg != nullptr);
1568 const uint64_t start_time = NanoTime();
1569 const bool app_image = class_loader.Get() != nullptr;
1570 const ImageHeader& header = space->GetImageHeader();
1571 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1572 DCHECK(dex_caches_object != nullptr);
1573 Runtime* const runtime = Runtime::Current();
1574 gc::Heap* const heap = runtime->GetHeap();
1575 Thread* const self = Thread::Current();
1576 StackHandleScope<2> hs(self);
1577 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1578 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1579 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1580 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1581 const OatFile* oat_file = space->GetOatFile();
1582 std::unordered_set<mirror::ClassLoader*> image_class_loaders;
1583 // Check that the image is what we are expecting.
1584 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1585 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1586 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1587 image_pointer_size_);
1588 return false;
1589 }
1590 DCHECK(class_roots.Get() != nullptr);
1591 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1592 *error_msg = StringPrintf("Expected %d class roots but got %d",
1593 class_roots->GetLength(),
1594 static_cast<int32_t>(kClassRootsMax));
1595 return false;
1596 }
1597 // Check against existing class roots to make sure they match the ones in the boot image.
1598 for (size_t i = 0; i < kClassRootsMax; i++) {
1599 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1600 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1601 return false;
1602 }
1603 }
1604 if (oat_file->GetOatHeader().GetDexFileCount() !=
1605 static_cast<uint32_t>(dex_caches->GetLength())) {
1606 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1607 "image";
1608 return false;
1609 }
1610
1611 StackHandleScope<1> hs2(self);
1612 MutableHandle<mirror::DexCache> h_dex_cache(hs2.NewHandle<mirror::DexCache>(nullptr));
1613 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1614 h_dex_cache.Assign(dex_caches->Get(i));
1615 std::string dex_file_location(h_dex_cache->GetLocation()->ToModifiedUtf8());
1616 // TODO: Only store qualified paths.
1617 // If non qualified, qualify it.
1618 if (dex_file_location.find('/') == std::string::npos) {
1619 std::string dex_location_path = dex_location;
1620 const size_t pos = dex_location_path.find_last_of('/');
1621 CHECK_NE(pos, std::string::npos);
1622 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/'
1623 dex_file_location = dex_location_path + dex_file_location;
1624 }
1625 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1626 dex_file_location.c_str(),
1627 error_msg);
1628 if (dex_file == nullptr) {
1629 return false;
1630 }
1631
1632 if (app_image) {
1633 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1634 // loop below.
1635 h_dex_cache->SetDexFile(dex_file.get());
1636 // Check that each class loader resolved the same way.
1637 // TODO: Store image class loaders as image roots.
1638 GcRoot<mirror::Class>* const types = h_dex_cache->GetResolvedTypes();
1639 for (int32_t j = 0, num_types = h_dex_cache->NumResolvedTypes(); j < num_types; j++) {
1640 mirror::Class* klass = types[j].Read();
1641 if (klass != nullptr) {
1642 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1643 mirror::ClassLoader* image_class_loader = klass->GetClassLoader();
1644 image_class_loaders.insert(image_class_loader);
1645 }
1646 }
1647 } else {
1648 if (kSanityCheckObjects) {
1649 SanityCheckArtMethodPointerArray(h_dex_cache->GetResolvedMethods(),
1650 h_dex_cache->NumResolvedMethods(),
1651 image_pointer_size_,
1652 heap->GetBootImageSpaces());
1653 }
1654 // Register dex files, keep track of existing ones that are conflicts.
1655 AppendToBootClassPath(*dex_file.get(), h_dex_cache);
1656 }
1657 out_dex_files->push_back(std::move(dex_file));
1658 }
1659
1660 if (app_image) {
1661 ScopedObjectAccessUnchecked soa(Thread::Current());
1662 // Check that the class loader resolves the same way as the ones in the image.
1663 // Image class loader [A][B][C][image dex files]
1664 // Class loader = [???][dex_elements][image dex files]
1665 // Need to ensure that [???][dex_elements] == [A][B][C].
1666 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1667 // for PathClassLoader does this by looping through the array of dex files. To ensure they
1668 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1669 // and check that the dex file names are the same.
1670 for (mirror::ClassLoader* image_class_loader : image_class_loaders) {
1671 if (IsBootClassLoader(soa, image_class_loader)) {
1672 // The dex cache can reference types from the boot class loader.
1673 continue;
1674 }
1675 std::list<mirror::String*> image_dex_file_names;
1676 std::string temp_error_msg;
1677 if (!FlattenPathClassLoader(image_class_loader, &image_dex_file_names, &temp_error_msg)) {
1678 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1679 temp_error_msg.c_str());
1680 return false;
1681 }
1682 std::list<mirror::String*> loader_dex_file_names;
1683 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1684 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1685 temp_error_msg.c_str());
1686 return false;
1687 }
1688 // Add the temporary dex path list elements at the end.
1689 auto* elements = soa.Decode<mirror::ObjectArray<mirror::Object>*>(dex_elements);
1690 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1691 mirror::Object* element = elements->GetWithoutChecks(i);
1692 if (element != nullptr) {
1693 // If we are somewhere in the middle of the array, there may be nulls at the end.
1694 loader_dex_file_names.push_back(GetDexPathListElementName(soa, element));
1695 }
1696 }
1697 // Ignore the number of image dex files since we are adding those to the class loader anyways.
1698 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1699 static_cast<size_t>(dex_caches->GetLength()));
1700 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1701 // Check that the dex file names match.
1702 bool equal = image_count == loader_dex_file_names.size();
1703 if (equal) {
1704 auto it1 = image_dex_file_names.begin();
1705 auto it2 = loader_dex_file_names.begin();
1706 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1707 equal = equal && (*it1)->Equals(*it2);
1708 }
1709 }
1710 if (!equal) {
1711 VLOG(image) << "Image dex files " << image_dex_file_names.size();
1712 for (mirror::String* name : image_dex_file_names) {
1713 VLOG(image) << name->ToModifiedUtf8();
1714 }
1715 VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1716 for (mirror::String* name : loader_dex_file_names) {
1717 VLOG(image) << name->ToModifiedUtf8();
1718 }
1719 *error_msg = "Rejecting application image due to class loader mismatch";
1720 // Ignore class loader mismatch for now since these would just use possibly incorrect
1721 // oat code anyways. The structural class check should be done in the parent.
1722 }
1723 }
1724 }
1725
1726 if (kSanityCheckObjects) {
1727 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1728 auto* dex_cache = dex_caches->Get(i);
1729 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1730 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1731 if (field != nullptr) {
1732 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1733 }
1734 }
1735 }
1736 if (!app_image) {
1737 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
1738 }
1739 }
1740
1741 // Set entry point to interpreter if in InterpretOnly mode.
1742 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
1743 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
1744 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
1745 }
1746
1747 ClassTable* class_table = nullptr;
1748 {
1749 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1750 class_table = InsertClassTableForClassLoader(class_loader.Get());
1751 }
1752 // If we have a class table section, read it and use it for verification in
1753 // UpdateAppImageClassLoadersAndDexCaches.
1754 ClassTable::ClassSet temp_set;
1755 const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable);
1756 const bool added_class_table = class_table_section.Size() > 0u;
1757 if (added_class_table) {
1758 const uint64_t start_time2 = NanoTime();
1759 size_t read_count = 0;
1760 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1761 /*make copy*/false,
1762 &read_count);
1763 if (!app_image) {
1764 dex_cache_boot_image_class_lookup_required_ = false;
1765 }
1766 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
1767 }
1768 if (app_image) {
1769 bool forward_dex_cache_arrays = false;
1770 if (!UpdateAppImageClassLoadersAndDexCaches(space,
1771 class_loader,
1772 dex_caches,
1773 added_class_table ? &temp_set : nullptr,
1774 /*out*/&forward_dex_cache_arrays,
1775 /*out*/error_msg)) {
1776 return false;
1777 }
1778 // Update class loader and resolved strings. If added_class_table is false, the resolved
1779 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
1780 UpdateClassLoaderAndResolvedStringsVisitor visitor(space,
1781 class_loader.Get(),
1782 forward_dex_cache_arrays);
1783 if (added_class_table) {
1784 for (GcRoot<mirror::Class>& root : temp_set) {
1785 visitor(root.Read());
1786 }
1787 }
1788 // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss.
1789 // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and
1790 // mark as PROT_NONE to catch any invalid accesses.
1791 if (forward_dex_cache_arrays) {
1792 const ImageSection& dex_cache_section = header.GetImageSection(
1793 ImageHeader::kSectionDexCacheArrays);
1794 uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize);
1795 uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize);
1796 if (section_begin < section_end) {
1797 madvise(section_begin, section_end - section_begin, MADV_DONTNEED);
1798 mprotect(section_begin, section_end - section_begin, PROT_NONE);
1799 VLOG(image) << "Released and protected dex cache array image section from "
1800 << reinterpret_cast<const void*>(section_begin) << "-"
1801 << reinterpret_cast<const void*>(section_end);
1802 }
1803 }
1804 }
1805 if (added_class_table) {
1806 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1807 class_table->AddClassSet(std::move(temp_set));
1808 }
1809 if (kIsDebugBuild && app_image) {
1810 // This verification needs to happen after the classes have been added to the class loader.
1811 // Since it ensures classes are in the class table.
1812 VerifyClassInTableArtMethodVisitor visitor2(class_table);
1813 header.VisitPackedArtMethods(&visitor2, space->Begin(), sizeof(void*));
1814 }
1815 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
1816 return true;
1817 }
1818
ClassInClassTable(mirror::Class * klass)1819 bool ClassLinker::ClassInClassTable(mirror::Class* klass) {
1820 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1821 return class_table != nullptr && class_table->Contains(klass);
1822 }
1823
VisitClassRoots(RootVisitor * visitor,VisitRootFlags flags)1824 void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
1825 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1826 // enabling tracing requires the mutator lock, there are no race conditions here.
1827 const bool tracing_enabled = Trace::IsTracingEnabled();
1828 Thread* const self = Thread::Current();
1829 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1830 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1831 visitor, RootInfo(kRootStickyClass));
1832 if ((flags & kVisitRootFlagAllRoots) != 0) {
1833 // Argument for how root visiting deals with ArtField and ArtMethod roots.
1834 // There is 3 GC cases to handle:
1835 // Non moving concurrent:
1836 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
1837 // live by the class and class roots.
1838 //
1839 // Moving non-concurrent:
1840 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1841 // To prevent missing roots, this case needs to ensure that there is no
1842 // suspend points between the point which we allocate ArtMethod arrays and place them in a
1843 // class which is in the class table.
1844 //
1845 // Moving concurrent:
1846 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1847 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
1848 boot_class_table_.VisitRoots(buffered_visitor);
1849
1850 // If tracing is enabled, then mark all the class loaders to prevent unloading.
1851 if (tracing_enabled) {
1852 for (const ClassLoaderData& data : class_loaders_) {
1853 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1854 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1855 }
1856 }
1857 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1858 for (auto& root : new_class_roots_) {
1859 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1860 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1861 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
1862 // Concurrent moving GC marked new roots through the to-space invariant.
1863 CHECK_EQ(new_ref, old_ref);
1864 }
1865 }
1866 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
1867 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1868 new_class_roots_.clear();
1869 }
1870 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1871 log_new_class_table_roots_ = true;
1872 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1873 log_new_class_table_roots_ = false;
1874 }
1875 // We deliberately ignore the class roots in the image since we
1876 // handle image roots by using the MS/CMS rescanning of dirty cards.
1877 }
1878
1879 // Keep in sync with InitCallback. Anything we visit, we need to
1880 // reinit references to when reinitializing a ClassLinker from a
1881 // mapped image.
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)1882 void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1883 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1884 VisitClassRoots(visitor, flags);
1885 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1886 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1887 // unloading if we are marking roots.
1888 DropFindArrayClassCache();
1889 }
1890
1891 class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1892 public:
VisitClassLoaderClassesVisitor(ClassVisitor * visitor)1893 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1894 : visitor_(visitor),
1895 done_(false) {}
1896
Visit(mirror::ClassLoader * class_loader)1897 void Visit(mirror::ClassLoader* class_loader)
1898 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
1899 ClassTable* const class_table = class_loader->GetClassTable();
1900 if (!done_ && class_table != nullptr && !class_table->Visit(*visitor_)) {
1901 // If the visitor ClassTable returns false it means that we don't need to continue.
1902 done_ = true;
1903 }
1904 }
1905
1906 private:
1907 ClassVisitor* const visitor_;
1908 // If done is true then we don't need to do any more visiting.
1909 bool done_;
1910 };
1911
VisitClassesInternal(ClassVisitor * visitor)1912 void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
1913 if (boot_class_table_.Visit(*visitor)) {
1914 VisitClassLoaderClassesVisitor loader_visitor(visitor);
1915 VisitClassLoaders(&loader_visitor);
1916 }
1917 }
1918
VisitClasses(ClassVisitor * visitor)1919 void ClassLinker::VisitClasses(ClassVisitor* visitor) {
1920 if (dex_cache_boot_image_class_lookup_required_) {
1921 AddBootImageClassesToClassTable();
1922 }
1923 Thread* const self = Thread::Current();
1924 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1925 // Not safe to have thread suspension when we are holding a lock.
1926 if (self != nullptr) {
1927 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
1928 VisitClassesInternal(visitor);
1929 } else {
1930 VisitClassesInternal(visitor);
1931 }
1932 }
1933
1934 class GetClassesInToVector : public ClassVisitor {
1935 public:
operator ()(mirror::Class * klass)1936 bool operator()(mirror::Class* klass) OVERRIDE {
1937 classes_.push_back(klass);
1938 return true;
1939 }
1940 std::vector<mirror::Class*> classes_;
1941 };
1942
1943 class GetClassInToObjectArray : public ClassVisitor {
1944 public:
GetClassInToObjectArray(mirror::ObjectArray<mirror::Class> * arr)1945 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1946 : arr_(arr), index_(0) {}
1947
operator ()(mirror::Class * klass)1948 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1949 ++index_;
1950 if (index_ <= arr_->GetLength()) {
1951 arr_->Set(index_ - 1, klass);
1952 return true;
1953 }
1954 return false;
1955 }
1956
Succeeded() const1957 bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) {
1958 return index_ <= arr_->GetLength();
1959 }
1960
1961 private:
1962 mirror::ObjectArray<mirror::Class>* const arr_;
1963 int32_t index_;
1964 };
1965
VisitClassesWithoutClassesLock(ClassVisitor * visitor)1966 void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
1967 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1968 // is avoiding duplicates.
1969 Thread* const self = Thread::Current();
1970 if (!kMovingClasses) {
1971 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
1972 GetClassesInToVector accumulator;
1973 VisitClasses(&accumulator);
1974 for (mirror::Class* klass : accumulator.classes_) {
1975 if (!visitor->operator()(klass)) {
1976 return;
1977 }
1978 }
1979 } else {
1980 StackHandleScope<1> hs(self);
1981 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1982 // We size the array assuming classes won't be added to the class table during the visit.
1983 // If this assumption fails we iterate again.
1984 while (true) {
1985 size_t class_table_size;
1986 {
1987 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1988 // Add 100 in case new classes get loaded when we are filling in the object array.
1989 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
1990 }
1991 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1992 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1993 classes.Assign(
1994 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1995 CHECK(classes.Get() != nullptr); // OOME.
1996 GetClassInToObjectArray accumulator(classes.Get());
1997 VisitClasses(&accumulator);
1998 if (accumulator.Succeeded()) {
1999 break;
2000 }
2001 }
2002 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2003 // If the class table shrank during creation of the clases array we expect null elements. If
2004 // the class table grew then the loop repeats. If classes are created after the loop has
2005 // finished then we don't visit.
2006 mirror::Class* klass = classes->Get(i);
2007 if (klass != nullptr && !visitor->operator()(klass)) {
2008 return;
2009 }
2010 }
2011 }
2012 }
2013
~ClassLinker()2014 ClassLinker::~ClassLinker() {
2015 mirror::Class::ResetClass();
2016 mirror::Constructor::ResetClass();
2017 mirror::Field::ResetClass();
2018 mirror::Method::ResetClass();
2019 mirror::Reference::ResetClass();
2020 mirror::StackTraceElement::ResetClass();
2021 mirror::String::ResetClass();
2022 mirror::Throwable::ResetClass();
2023 mirror::BooleanArray::ResetArrayClass();
2024 mirror::ByteArray::ResetArrayClass();
2025 mirror::CharArray::ResetArrayClass();
2026 mirror::Constructor::ResetArrayClass();
2027 mirror::DoubleArray::ResetArrayClass();
2028 mirror::Field::ResetArrayClass();
2029 mirror::FloatArray::ResetArrayClass();
2030 mirror::Method::ResetArrayClass();
2031 mirror::IntArray::ResetArrayClass();
2032 mirror::LongArray::ResetArrayClass();
2033 mirror::ShortArray::ResetArrayClass();
2034 Thread* const self = Thread::Current();
2035 for (const ClassLoaderData& data : class_loaders_) {
2036 DeleteClassLoader(self, data);
2037 }
2038 class_loaders_.clear();
2039 }
2040
DeleteClassLoader(Thread * self,const ClassLoaderData & data)2041 void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2042 Runtime* const runtime = Runtime::Current();
2043 JavaVMExt* const vm = runtime->GetJavaVM();
2044 vm->DeleteWeakGlobalRef(self, data.weak_root);
2045 // Notify the JIT that we need to remove the methods and/or profiling info.
2046 if (runtime->GetJit() != nullptr) {
2047 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2048 if (code_cache != nullptr) {
2049 code_cache->RemoveMethodsIn(self, *data.allocator);
2050 }
2051 }
2052 delete data.allocator;
2053 delete data.class_table;
2054 }
2055
AllocPointerArray(Thread * self,size_t length)2056 mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2057 return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ?
2058 static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) :
2059 static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
2060 }
2061
AllocDexCache(Thread * self,const DexFile & dex_file,LinearAlloc * linear_alloc)2062 mirror::DexCache* ClassLinker::AllocDexCache(Thread* self,
2063 const DexFile& dex_file,
2064 LinearAlloc* linear_alloc) {
2065 StackHandleScope<6> hs(self);
2066 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>(
2067 GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
2068 if (dex_cache.Get() == nullptr) {
2069 self->AssertPendingOOMException();
2070 return nullptr;
2071 }
2072 auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
2073 if (location.Get() == nullptr) {
2074 self->AssertPendingOOMException();
2075 return nullptr;
2076 }
2077 DexCacheArraysLayout layout(image_pointer_size_, &dex_file);
2078 uint8_t* raw_arrays = nullptr;
2079 if (dex_file.GetOatDexFile() != nullptr &&
2080 dex_file.GetOatDexFile()->GetDexCacheArrays() != nullptr) {
2081 raw_arrays = dex_file.GetOatDexFile()->GetDexCacheArrays();
2082 } else if (dex_file.NumStringIds() != 0u || dex_file.NumTypeIds() != 0u ||
2083 dex_file.NumMethodIds() != 0u || dex_file.NumFieldIds() != 0u) {
2084 // NOTE: We "leak" the raw_arrays because we never destroy the dex cache.
2085 DCHECK(image_pointer_size_ == 4u || image_pointer_size_ == 8u);
2086 // Zero-initialized.
2087 raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size()));
2088 }
2089 GcRoot<mirror::String>* strings = (dex_file.NumStringIds() == 0u) ? nullptr :
2090 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
2091 GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr :
2092 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
2093 ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr :
2094 reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset());
2095 ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr :
2096 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
2097 if (kIsDebugBuild) {
2098 // Sanity check to make sure all the dex cache arrays are empty. b/28992179
2099 for (size_t i = 0; i < dex_file.NumStringIds(); ++i) {
2100 CHECK(strings[i].Read<kWithoutReadBarrier>() == nullptr);
2101 }
2102 for (size_t i = 0; i < dex_file.NumTypeIds(); ++i) {
2103 CHECK(types[i].Read<kWithoutReadBarrier>() == nullptr);
2104 }
2105 for (size_t i = 0; i < dex_file.NumMethodIds(); ++i) {
2106 CHECK(mirror::DexCache::GetElementPtrSize(methods, i, image_pointer_size_) == nullptr);
2107 }
2108 for (size_t i = 0; i < dex_file.NumFieldIds(); ++i) {
2109 CHECK(mirror::DexCache::GetElementPtrSize(fields, i, image_pointer_size_) == nullptr);
2110 }
2111 }
2112 dex_cache->Init(&dex_file,
2113 location.Get(),
2114 strings,
2115 dex_file.NumStringIds(),
2116 types,
2117 dex_file.NumTypeIds(),
2118 methods,
2119 dex_file.NumMethodIds(),
2120 fields,
2121 dex_file.NumFieldIds(),
2122 image_pointer_size_);
2123 return dex_cache.Get();
2124 }
2125
AllocClass(Thread * self,mirror::Class * java_lang_Class,uint32_t class_size)2126 mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
2127 uint32_t class_size) {
2128 DCHECK_GE(class_size, sizeof(mirror::Class));
2129 gc::Heap* heap = Runtime::Current()->GetHeap();
2130 mirror::Class::InitializeClassVisitor visitor(class_size);
2131 mirror::Object* k = kMovingClasses ?
2132 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2133 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
2134 if (UNLIKELY(k == nullptr)) {
2135 self->AssertPendingOOMException();
2136 return nullptr;
2137 }
2138 return k->AsClass();
2139 }
2140
AllocClass(Thread * self,uint32_t class_size)2141 mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
2142 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
2143 }
2144
AllocStackTraceElementArray(Thread * self,size_t length)2145 mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2146 Thread* self,
2147 size_t length) {
2148 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2149 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
2150 }
2151
EnsureResolved(Thread * self,const char * descriptor,mirror::Class * klass)2152 mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2153 const char* descriptor,
2154 mirror::Class* klass) {
2155 DCHECK(klass != nullptr);
2156
2157 // For temporary classes we must wait for them to be retired.
2158 if (init_done_ && klass->IsTemp()) {
2159 CHECK(!klass->IsResolved());
2160 if (klass->IsErroneous()) {
2161 ThrowEarlierClassFailure(klass);
2162 return nullptr;
2163 }
2164 StackHandleScope<1> hs(self);
2165 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2166 ObjectLock<mirror::Class> lock(self, h_class);
2167 // Loop and wait for the resolving thread to retire this class.
2168 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2169 lock.WaitIgnoringInterrupts();
2170 }
2171 if (h_class->IsErroneous()) {
2172 ThrowEarlierClassFailure(h_class.Get());
2173 return nullptr;
2174 }
2175 CHECK(h_class->IsRetired());
2176 // Get the updated class from class table.
2177 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2178 h_class.Get()->GetClassLoader());
2179 }
2180
2181 // Wait for the class if it has not already been linked.
2182 if (!klass->IsResolved() && !klass->IsErroneous()) {
2183 StackHandleScope<1> hs(self);
2184 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2185 ObjectLock<mirror::Class> lock(self, h_class);
2186 // Check for circular dependencies between classes.
2187 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2188 ThrowClassCircularityError(h_class.Get());
2189 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
2190 return nullptr;
2191 }
2192 // Wait for the pending initialization to complete.
2193 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
2194 lock.WaitIgnoringInterrupts();
2195 }
2196 }
2197
2198 if (klass->IsErroneous()) {
2199 ThrowEarlierClassFailure(klass);
2200 return nullptr;
2201 }
2202 // Return the loaded class. No exceptions should be pending.
2203 CHECK(klass->IsResolved()) << PrettyClass(klass);
2204 self->AssertNoPendingException();
2205 return klass;
2206 }
2207
2208 typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2209
2210 // Search a collection of DexFiles for a descriptor
FindInClassPath(const char * descriptor,size_t hash,const std::vector<const DexFile * > & class_path)2211 ClassPathEntry FindInClassPath(const char* descriptor,
2212 size_t hash, const std::vector<const DexFile*>& class_path) {
2213 for (const DexFile* dex_file : class_path) {
2214 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
2215 if (dex_class_def != nullptr) {
2216 return ClassPathEntry(dex_file, dex_class_def);
2217 }
2218 }
2219 return ClassPathEntry(nullptr, nullptr);
2220 }
2221
FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable & soa,Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader,mirror::Class ** result)2222 bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2223 Thread* self,
2224 const char* descriptor,
2225 size_t hash,
2226 Handle<mirror::ClassLoader> class_loader,
2227 mirror::Class** result) {
2228 // Termination case: boot class-loader.
2229 if (IsBootClassLoader(soa, class_loader.Get())) {
2230 // The boot class loader, search the boot class path.
2231 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2232 if (pair.second != nullptr) {
2233 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
2234 if (klass != nullptr) {
2235 *result = EnsureResolved(self, descriptor, klass);
2236 } else {
2237 *result = DefineClass(self,
2238 descriptor,
2239 hash,
2240 ScopedNullHandle<mirror::ClassLoader>(),
2241 *pair.first,
2242 *pair.second);
2243 }
2244 if (*result == nullptr) {
2245 CHECK(self->IsExceptionPending()) << descriptor;
2246 self->ClearException();
2247 }
2248 } else {
2249 *result = nullptr;
2250 }
2251 return true;
2252 }
2253
2254 // Unsupported class-loader?
2255 if (class_loader->GetClass() !=
2256 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
2257 *result = nullptr;
2258 return false;
2259 }
2260
2261 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2262 StackHandleScope<4> hs(self);
2263 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2264 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
2265
2266 if (!recursive_result) {
2267 // Something wrong up the chain.
2268 return false;
2269 }
2270
2271 if (*result != nullptr) {
2272 // Found the class up the chain.
2273 return true;
2274 }
2275
2276 // Handle this step.
2277 // Handle as if this is the child PathClassLoader.
2278 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2279 // We need to get the DexPathList and loop through it.
2280 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
2281 ArtField* const dex_file_field =
2282 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
2283 mirror::Object* dex_path_list =
2284 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2285 GetObject(class_loader.Get());
2286 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2287 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2288 mirror::Object* dex_elements_obj =
2289 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2290 GetObject(dex_path_list);
2291 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2292 // at the mCookie which is a DexFile vector.
2293 if (dex_elements_obj != nullptr) {
2294 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2295 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2296 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2297 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2298 if (element == nullptr) {
2299 // Should never happen, fall back to java code to throw a NPE.
2300 break;
2301 }
2302 mirror::Object* dex_file = dex_file_field->GetObject(element);
2303 if (dex_file != nullptr) {
2304 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
2305 if (long_array == nullptr) {
2306 // This should never happen so log a warning.
2307 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2308 break;
2309 }
2310 int32_t long_array_size = long_array->GetLength();
2311 // First element is the oat file.
2312 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
2313 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2314 long_array->GetWithoutChecks(j)));
2315 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
2316 if (dex_class_def != nullptr) {
2317 mirror::Class* klass = DefineClass(self,
2318 descriptor,
2319 hash,
2320 class_loader,
2321 *cp_dex_file,
2322 *dex_class_def);
2323 if (klass == nullptr) {
2324 CHECK(self->IsExceptionPending()) << descriptor;
2325 self->ClearException();
2326 // TODO: Is it really right to break here, and not check the other dex files?
2327 return true;
2328 }
2329 *result = klass;
2330 return true;
2331 }
2332 }
2333 }
2334 }
2335 }
2336 self->AssertNoPendingException();
2337 }
2338
2339 // Result is still null from the parent call, no need to set it again...
2340 return true;
2341 }
2342
FindClass(Thread * self,const char * descriptor,Handle<mirror::ClassLoader> class_loader)2343 mirror::Class* ClassLinker::FindClass(Thread* self,
2344 const char* descriptor,
2345 Handle<mirror::ClassLoader> class_loader) {
2346 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
2347 DCHECK(self != nullptr);
2348 self->AssertNoPendingException();
2349 if (descriptor[1] == '\0') {
2350 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2351 // for primitive classes that aren't backed by dex files.
2352 return FindPrimitiveClass(descriptor[0]);
2353 }
2354 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
2355 // Find the class in the loaded classes table.
2356 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
2357 if (klass != nullptr) {
2358 return EnsureResolved(self, descriptor, klass);
2359 }
2360 // Class is not yet loaded.
2361 if (descriptor[0] == '[') {
2362 return CreateArrayClass(self, descriptor, hash, class_loader);
2363 } else if (class_loader.Get() == nullptr) {
2364 // The boot class loader, search the boot class path.
2365 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2366 if (pair.second != nullptr) {
2367 return DefineClass(self,
2368 descriptor,
2369 hash,
2370 ScopedNullHandle<mirror::ClassLoader>(),
2371 *pair.first,
2372 *pair.second);
2373 } else {
2374 // The boot class loader is searched ahead of the application class loader, failures are
2375 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2376 // trigger the chaining with a proper stack trace.
2377 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2378 self->SetException(pre_allocated);
2379 return nullptr;
2380 }
2381 } else {
2382 ScopedObjectAccessUnchecked soa(self);
2383 mirror::Class* cp_klass;
2384 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
2385 // The chain was understood. So the value in cp_klass is either the class we were looking
2386 // for, or not found.
2387 if (cp_klass != nullptr) {
2388 return cp_klass;
2389 }
2390 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
2391 // and the branch above. TODO: throw the right exception here.
2392
2393 // We'll let the Java-side rediscover all this and throw the exception with the right stack
2394 // trace.
2395 }
2396
2397 if (Runtime::Current()->IsAotCompiler()) {
2398 // Oops, compile-time, can't run actual class-loader code.
2399 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2400 self->SetException(pre_allocated);
2401 return nullptr;
2402 }
2403
2404 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
2405 soa.AddLocalReference<jobject>(class_loader.Get()));
2406 std::string class_name_string(DescriptorToDot(descriptor));
2407 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2408 {
2409 ScopedThreadStateChange tsc(self, kNative);
2410 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2411 soa.Env()->NewStringUTF(class_name_string.c_str()));
2412 if (class_name_object.get() == nullptr) {
2413 DCHECK(self->IsExceptionPending()); // OOME.
2414 return nullptr;
2415 }
2416 CHECK(class_loader_object.get() != nullptr);
2417 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2418 WellKnownClasses::java_lang_ClassLoader_loadClass,
2419 class_name_object.get()));
2420 }
2421 if (self->IsExceptionPending()) {
2422 // If the ClassLoader threw, pass that exception up.
2423 return nullptr;
2424 } else if (result.get() == nullptr) {
2425 // broken loader - throw NPE to be compatible with Dalvik
2426 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2427 class_name_string.c_str()).c_str());
2428 return nullptr;
2429 } else {
2430 // success, return mirror::Class*
2431 return soa.Decode<mirror::Class*>(result.get());
2432 }
2433 }
2434 UNREACHABLE();
2435 }
2436
DefineClass(Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2437 mirror::Class* ClassLinker::DefineClass(Thread* self,
2438 const char* descriptor,
2439 size_t hash,
2440 Handle<mirror::ClassLoader> class_loader,
2441 const DexFile& dex_file,
2442 const DexFile::ClassDef& dex_class_def) {
2443 StackHandleScope<3> hs(self);
2444 auto klass = hs.NewHandle<mirror::Class>(nullptr);
2445
2446 // Load the class from the dex file.
2447 if (UNLIKELY(!init_done_)) {
2448 // finish up init of hand crafted class_roots_
2449 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
2450 klass.Assign(GetClassRoot(kJavaLangObject));
2451 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
2452 klass.Assign(GetClassRoot(kJavaLangClass));
2453 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2454 klass.Assign(GetClassRoot(kJavaLangString));
2455 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2456 klass.Assign(GetClassRoot(kJavaLangRefReference));
2457 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
2458 klass.Assign(GetClassRoot(kJavaLangDexCache));
2459 }
2460 }
2461
2462 if (klass.Get() == nullptr) {
2463 // Allocate a class with the status of not ready.
2464 // Interface object should get the right size here. Regular class will
2465 // figure out the right size later and be replaced with one of the right
2466 // size when the class becomes resolved.
2467 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
2468 }
2469 if (UNLIKELY(klass.Get() == nullptr)) {
2470 self->AssertPendingOOMException();
2471 return nullptr;
2472 }
2473 mirror::DexCache* dex_cache = RegisterDexFile(dex_file, class_loader.Get());
2474 if (dex_cache == nullptr) {
2475 self->AssertPendingOOMException();
2476 return nullptr;
2477 }
2478 klass->SetDexCache(dex_cache);
2479 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
2480
2481 // Mark the string class by setting its access flag.
2482 if (UNLIKELY(!init_done_)) {
2483 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2484 klass->SetStringClass();
2485 }
2486 }
2487
2488 ObjectLock<mirror::Class> lock(self, klass);
2489 klass->SetClinitThreadId(self->GetTid());
2490
2491 // Add the newly loaded class to the loaded classes table.
2492 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
2493 if (existing != nullptr) {
2494 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2495 // this thread to block.
2496 return EnsureResolved(self, descriptor, existing);
2497 }
2498
2499 // Load the fields and other things after we are inserted in the table. This is so that we don't
2500 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2501 // other reason is that the field roots are only visited from the class table. So we need to be
2502 // inserted before we allocate / fill in these fields.
2503 LoadClass(self, dex_file, dex_class_def, klass);
2504 if (self->IsExceptionPending()) {
2505 VLOG(class_linker) << self->GetException()->Dump();
2506 // An exception occured during load, set status to erroneous while holding klass' lock in case
2507 // notification is necessary.
2508 if (!klass->IsErroneous()) {
2509 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2510 }
2511 return nullptr;
2512 }
2513
2514 // Finish loading (if necessary) by finding parents
2515 CHECK(!klass->IsLoaded());
2516 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2517 // Loading failed.
2518 if (!klass->IsErroneous()) {
2519 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2520 }
2521 return nullptr;
2522 }
2523 CHECK(klass->IsLoaded());
2524 // Link the class (if necessary)
2525 CHECK(!klass->IsResolved());
2526 // TODO: Use fast jobjects?
2527 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
2528
2529 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
2530 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
2531 // Linking failed.
2532 if (!klass->IsErroneous()) {
2533 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2534 }
2535 return nullptr;
2536 }
2537 self->AssertNoPendingException();
2538 CHECK(h_new_class.Get() != nullptr) << descriptor;
2539 CHECK(h_new_class->IsResolved()) << descriptor;
2540
2541 // Instrumentation may have updated entrypoints for all methods of all
2542 // classes. However it could not update methods of this class while we
2543 // were loading it. Now the class is resolved, we can update entrypoints
2544 // as required by instrumentation.
2545 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2546 // We must be in the kRunnable state to prevent instrumentation from
2547 // suspending all threads to update entrypoints while we are doing it
2548 // for this class.
2549 DCHECK_EQ(self->GetState(), kRunnable);
2550 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
2551 }
2552
2553 /*
2554 * We send CLASS_PREPARE events to the debugger from here. The
2555 * definition of "preparation" is creating the static fields for a
2556 * class and initializing them to the standard default values, but not
2557 * executing any code (that comes later, during "initialization").
2558 *
2559 * We did the static preparation in LinkClass.
2560 *
2561 * The class has been prepared and resolved but possibly not yet verified
2562 * at this point.
2563 */
2564 Dbg::PostClassPrepare(h_new_class.Get());
2565
2566 // Notify native debugger of the new class and its layout.
2567 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2568
2569 return h_new_class.Get();
2570 }
2571
SizeOfClassWithoutEmbeddedTables(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2572 uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2573 const DexFile::ClassDef& dex_class_def) {
2574 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2575 size_t num_ref = 0;
2576 size_t num_8 = 0;
2577 size_t num_16 = 0;
2578 size_t num_32 = 0;
2579 size_t num_64 = 0;
2580 if (class_data != nullptr) {
2581 // We allow duplicate definitions of the same field in a class_data_item
2582 // but ignore the repeated indexes here, b/21868015.
2583 uint32_t last_field_idx = DexFile::kDexNoIndex;
2584 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2585 uint32_t field_idx = it.GetMemberIndex();
2586 // Ordering enforced by DexFileVerifier.
2587 DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx);
2588 if (UNLIKELY(field_idx == last_field_idx)) {
2589 continue;
2590 }
2591 last_field_idx = field_idx;
2592 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2593 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
2594 char c = descriptor[0];
2595 switch (c) {
2596 case 'L':
2597 case '[':
2598 num_ref++;
2599 break;
2600 case 'J':
2601 case 'D':
2602 num_64++;
2603 break;
2604 case 'I':
2605 case 'F':
2606 num_32++;
2607 break;
2608 case 'S':
2609 case 'C':
2610 num_16++;
2611 break;
2612 case 'B':
2613 case 'Z':
2614 num_8++;
2615 break;
2616 default:
2617 LOG(FATAL) << "Unknown descriptor: " << c;
2618 UNREACHABLE();
2619 }
2620 }
2621 }
2622 return mirror::Class::ComputeClassSize(false,
2623 0,
2624 num_8,
2625 num_16,
2626 num_32,
2627 num_64,
2628 num_ref,
2629 image_pointer_size_);
2630 }
2631
FindOatClass(const DexFile & dex_file,uint16_t class_def_idx,bool * found)2632 OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file,
2633 uint16_t class_def_idx,
2634 bool* found) {
2635 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
2636 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
2637 if (oat_dex_file == nullptr) {
2638 *found = false;
2639 return OatFile::OatClass::Invalid();
2640 }
2641 *found = true;
2642 return oat_dex_file->GetOatClass(class_def_idx);
2643 }
2644
GetOatMethodIndexFromMethodIndex(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)2645 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
2646 uint16_t class_def_idx,
2647 uint32_t method_idx) {
2648 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2649 const uint8_t* class_data = dex_file.GetClassData(class_def);
2650 CHECK(class_data != nullptr);
2651 ClassDataItemIterator it(dex_file, class_data);
2652 // Skip fields
2653 while (it.HasNextStaticField()) {
2654 it.Next();
2655 }
2656 while (it.HasNextInstanceField()) {
2657 it.Next();
2658 }
2659 // Process methods
2660 size_t class_def_method_index = 0;
2661 while (it.HasNextDirectMethod()) {
2662 if (it.GetMemberIndex() == method_idx) {
2663 return class_def_method_index;
2664 }
2665 class_def_method_index++;
2666 it.Next();
2667 }
2668 while (it.HasNextVirtualMethod()) {
2669 if (it.GetMemberIndex() == method_idx) {
2670 return class_def_method_index;
2671 }
2672 class_def_method_index++;
2673 it.Next();
2674 }
2675 DCHECK(!it.HasNext());
2676 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2677 UNREACHABLE();
2678 }
2679
FindOatMethodFor(ArtMethod * method,bool * found)2680 const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) {
2681 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
2682 // method for direct methods (or virtual methods made direct).
2683 mirror::Class* declaring_class = method->GetDeclaringClass();
2684 size_t oat_method_index;
2685 if (method->IsStatic() || method->IsDirect()) {
2686 // Simple case where the oat method index was stashed at load time.
2687 oat_method_index = method->GetMethodIndex();
2688 } else {
2689 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2690 // by search for its position in the declared virtual methods.
2691 oat_method_index = declaring_class->NumDirectMethods();
2692 bool found_virtual = false;
2693 for (ArtMethod& art_method : declaring_class->GetVirtualMethods(image_pointer_size_)) {
2694 // Check method index instead of identity in case of duplicate method definitions.
2695 if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) {
2696 found_virtual = true;
2697 break;
2698 }
2699 oat_method_index++;
2700 }
2701 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2702 << PrettyMethod(method);
2703 }
2704 DCHECK_EQ(oat_method_index,
2705 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
2706 method->GetDeclaringClass()->GetDexClassDefIndex(),
2707 method->GetDexMethodIndex()));
2708 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2709 declaring_class->GetDexClassDefIndex(),
2710 found);
2711 if (!(*found)) {
2712 return OatFile::OatMethod::Invalid();
2713 }
2714 return oat_class.GetOatMethod(oat_method_index);
2715 }
2716
2717 // Special case to get oat code without overwriting a trampoline.
GetQuickOatCodeFor(ArtMethod * method)2718 const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
2719 CHECK(method->IsInvokable()) << PrettyMethod(method);
2720 if (method->IsProxyMethod()) {
2721 return GetQuickProxyInvokeHandler();
2722 }
2723 bool found;
2724 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2725 if (found) {
2726 auto* code = oat_method.GetQuickCode();
2727 if (code != nullptr) {
2728 return code;
2729 }
2730 }
2731 if (method->IsNative()) {
2732 // No code and native? Use generic trampoline.
2733 return GetQuickGenericJniStub();
2734 }
2735 return GetQuickToInterpreterBridge();
2736 }
2737
GetOatMethodQuickCodeFor(ArtMethod * method)2738 const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) {
2739 if (method->IsNative() || !method->IsInvokable() || method->IsProxyMethod()) {
2740 return nullptr;
2741 }
2742 bool found;
2743 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2744 if (found) {
2745 return oat_method.GetQuickCode();
2746 }
2747 return nullptr;
2748 }
2749
ShouldUseInterpreterEntrypoint(ArtMethod * method,const void * quick_code)2750 bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2751 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2752 return false;
2753 }
2754
2755 if (quick_code == nullptr) {
2756 return true;
2757 }
2758
2759 Runtime* runtime = Runtime::Current();
2760 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2761 if (instr->InterpretOnly()) {
2762 return true;
2763 }
2764
2765 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2766 // Doing this check avoids doing compiled/interpreter transitions.
2767 return true;
2768 }
2769
2770 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2771 // Force the use of interpreter when it is required by the debugger.
2772 return true;
2773 }
2774
2775 if (runtime->IsNativeDebuggable()) {
2776 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
2777 // If we are doing native debugging, ignore application's AOT code,
2778 // since we want to JIT it with extra stackmaps for native debugging.
2779 // On the other hand, keep all AOT code from the boot image, since the
2780 // blocking JIT would results in non-negligible performance impact.
2781 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
2782 }
2783
2784 if (Dbg::IsDebuggerActive()) {
2785 // Boot image classes may be AOT-compiled as non-debuggable.
2786 // This is not suitable for the Java debugger, so ignore the AOT code.
2787 return runtime->GetHeap()->IsInBootImageOatFile(quick_code);
2788 }
2789
2790 return false;
2791 }
2792
FixupStaticTrampolines(mirror::Class * klass)2793 void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
2794 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
2795 if (klass->NumDirectMethods() == 0) {
2796 return; // No direct methods => no static methods.
2797 }
2798 Runtime* runtime = Runtime::Current();
2799 if (!runtime->IsStarted()) {
2800 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2801 return; // OAT file unavailable.
2802 }
2803 }
2804
2805 const DexFile& dex_file = klass->GetDexFile();
2806 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
2807 CHECK(dex_class_def != nullptr);
2808 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
2809 // There should always be class data if there were direct methods.
2810 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
2811 ClassDataItemIterator it(dex_file, class_data);
2812 // Skip fields
2813 while (it.HasNextStaticField()) {
2814 it.Next();
2815 }
2816 while (it.HasNextInstanceField()) {
2817 it.Next();
2818 }
2819 bool has_oat_class;
2820 OatFile::OatClass oat_class = FindOatClass(dex_file,
2821 klass->GetDexClassDefIndex(),
2822 &has_oat_class);
2823 // Link the code of methods skipped by LinkCode.
2824 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
2825 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
2826 if (!method->IsStatic()) {
2827 // Only update static methods.
2828 continue;
2829 }
2830 const void* quick_code = nullptr;
2831 if (has_oat_class) {
2832 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2833 quick_code = oat_method.GetQuickCode();
2834 }
2835 // Check whether the method is native, in which case it's generic JNI.
2836 if (quick_code == nullptr && method->IsNative()) {
2837 quick_code = GetQuickGenericJniStub();
2838 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
2839 // Use interpreter entry point.
2840 quick_code = GetQuickToInterpreterBridge();
2841 }
2842 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
2843 }
2844 // Ignore virtual methods on the iterator.
2845 }
2846
EnsureThrowsInvocationError(ArtMethod * method)2847 void ClassLinker::EnsureThrowsInvocationError(ArtMethod* method) {
2848 DCHECK(method != nullptr);
2849 DCHECK(!method->IsInvokable());
2850 method->SetEntryPointFromQuickCompiledCodePtrSize(quick_to_interpreter_bridge_trampoline_,
2851 image_pointer_size_);
2852 }
2853
LinkCode(ArtMethod * method,const OatFile::OatClass * oat_class,uint32_t class_def_method_index)2854 void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
2855 uint32_t class_def_method_index) {
2856 Runtime* const runtime = Runtime::Current();
2857 if (runtime->IsAotCompiler()) {
2858 // The following code only applies to a non-compiler runtime.
2859 return;
2860 }
2861 // Method shouldn't have already been linked.
2862 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2863 if (oat_class != nullptr) {
2864 // Every kind of method should at least get an invoke stub from the oat_method.
2865 // non-abstract methods also get their code pointers.
2866 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
2867 oat_method.LinkMethod(method);
2868 }
2869
2870 // Install entry point from interpreter.
2871 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
2872 bool enter_interpreter = ShouldUseInterpreterEntrypoint(method, quick_code);
2873
2874 if (!method->IsInvokable()) {
2875 EnsureThrowsInvocationError(method);
2876 return;
2877 }
2878
2879 if (method->IsStatic() && !method->IsConstructor()) {
2880 // For static methods excluding the class initializer, install the trampoline.
2881 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2882 // after initializing class (see ClassLinker::InitializeClass method).
2883 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2884 } else if (quick_code == nullptr && method->IsNative()) {
2885 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
2886 } else if (enter_interpreter) {
2887 // Set entry point from compiled code if there's no code or in interpreter only mode.
2888 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2889 }
2890
2891 if (method->IsNative()) {
2892 // Unregistering restores the dlsym lookup stub.
2893 method->UnregisterNative();
2894
2895 if (enter_interpreter || quick_code == nullptr) {
2896 // We have a native method here without code. Then it should have either the generic JNI
2897 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2898 // TODO: this doesn't handle all the cases where trampolines may be installed.
2899 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2900 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
2901 }
2902 }
2903 }
2904
SetupClass(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,Handle<mirror::Class> klass,mirror::ClassLoader * class_loader)2905 void ClassLinker::SetupClass(const DexFile& dex_file,
2906 const DexFile::ClassDef& dex_class_def,
2907 Handle<mirror::Class> klass,
2908 mirror::ClassLoader* class_loader) {
2909 CHECK(klass.Get() != nullptr);
2910 CHECK(klass->GetDexCache() != nullptr);
2911 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
2912 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
2913 CHECK(descriptor != nullptr);
2914
2915 klass->SetClass(GetClassRoot(kJavaLangClass));
2916 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
2917 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
2918 klass->SetAccessFlags(access_flags);
2919 klass->SetClassLoader(class_loader);
2920 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
2921 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
2922
2923 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
2924 klass->SetDexTypeIndex(dex_class_def.class_idx_);
2925 CHECK(klass->GetDexCacheStrings() != nullptr);
2926 }
2927
LoadClass(Thread * self,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,Handle<mirror::Class> klass)2928 void ClassLinker::LoadClass(Thread* self,
2929 const DexFile& dex_file,
2930 const DexFile::ClassDef& dex_class_def,
2931 Handle<mirror::Class> klass) {
2932 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2933 if (class_data == nullptr) {
2934 return; // no fields or methods - for example a marker interface
2935 }
2936 bool has_oat_class = false;
2937 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
2938 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2939 &has_oat_class);
2940 if (has_oat_class) {
2941 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
2942 }
2943 }
2944 if (!has_oat_class) {
2945 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
2946 }
2947 }
2948
AllocArtFieldArray(Thread * self,LinearAlloc * allocator,size_t length)2949 LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
2950 LinearAlloc* allocator,
2951 size_t length) {
2952 if (length == 0) {
2953 return nullptr;
2954 }
2955 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
2956 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
2957 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
2958 void* array_storage = allocator->Alloc(self, storage_size);
2959 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
2960 CHECK(ret != nullptr);
2961 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
2962 return ret;
2963 }
2964
AllocArtMethodArray(Thread * self,LinearAlloc * allocator,size_t length)2965 LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
2966 LinearAlloc* allocator,
2967 size_t length) {
2968 if (length == 0) {
2969 return nullptr;
2970 }
2971 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
2972 const size_t method_size = ArtMethod::Size(image_pointer_size_);
2973 const size_t storage_size =
2974 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
2975 void* array_storage = allocator->Alloc(self, storage_size);
2976 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
2977 CHECK(ret != nullptr);
2978 for (size_t i = 0; i < length; ++i) {
2979 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
2980 }
2981 return ret;
2982 }
2983
GetAllocatorForClassLoader(mirror::ClassLoader * class_loader)2984 LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2985 if (class_loader == nullptr) {
2986 return Runtime::Current()->GetLinearAlloc();
2987 }
2988 LinearAlloc* allocator = class_loader->GetAllocator();
2989 DCHECK(allocator != nullptr);
2990 return allocator;
2991 }
2992
GetOrCreateAllocatorForClassLoader(mirror::ClassLoader * class_loader)2993 LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2994 if (class_loader == nullptr) {
2995 return Runtime::Current()->GetLinearAlloc();
2996 }
2997 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2998 LinearAlloc* allocator = class_loader->GetAllocator();
2999 if (allocator == nullptr) {
3000 RegisterClassLoader(class_loader);
3001 allocator = class_loader->GetAllocator();
3002 CHECK(allocator != nullptr);
3003 }
3004 return allocator;
3005 }
3006
LoadClassMembers(Thread * self,const DexFile & dex_file,const uint8_t * class_data,Handle<mirror::Class> klass,const OatFile::OatClass * oat_class)3007 void ClassLinker::LoadClassMembers(Thread* self,
3008 const DexFile& dex_file,
3009 const uint8_t* class_data,
3010 Handle<mirror::Class> klass,
3011 const OatFile::OatClass* oat_class) {
3012 {
3013 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3014 // Class::VisitFieldRoots may miss some fields or methods.
3015 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
3016 // Load static fields.
3017 // We allow duplicate definitions of the same field in a class_data_item
3018 // but ignore the repeated indexes here, b/21868015.
3019 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
3020 ClassDataItemIterator it(dex_file, class_data);
3021 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3022 allocator,
3023 it.NumStaticFields());
3024 size_t num_sfields = 0;
3025 uint32_t last_field_idx = 0u;
3026 for (; it.HasNextStaticField(); it.Next()) {
3027 uint32_t field_idx = it.GetMemberIndex();
3028 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3029 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3030 DCHECK_LT(num_sfields, it.NumStaticFields());
3031 LoadField(it, klass, &sfields->At(num_sfields));
3032 ++num_sfields;
3033 last_field_idx = field_idx;
3034 }
3035 }
3036 // Load instance fields.
3037 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3038 allocator,
3039 it.NumInstanceFields());
3040 size_t num_ifields = 0u;
3041 last_field_idx = 0u;
3042 for (; it.HasNextInstanceField(); it.Next()) {
3043 uint32_t field_idx = it.GetMemberIndex();
3044 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier.
3045 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3046 DCHECK_LT(num_ifields, it.NumInstanceFields());
3047 LoadField(it, klass, &ifields->At(num_ifields));
3048 ++num_ifields;
3049 last_field_idx = field_idx;
3050 }
3051 }
3052 if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3053 UNLIKELY(num_ifields != it.NumInstanceFields())) {
3054 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get())
3055 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3056 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
3057 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3058 if (sfields != nullptr) {
3059 sfields->SetSize(num_sfields);
3060 }
3061 if (ifields != nullptr) {
3062 ifields->SetSize(num_ifields);
3063 }
3064 }
3065 // Set the field arrays.
3066 klass->SetSFieldsPtr(sfields);
3067 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
3068 klass->SetIFieldsPtr(ifields);
3069 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3070 // Load methods.
3071 klass->SetMethodsPtr(
3072 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3073 it.NumDirectMethods(),
3074 it.NumVirtualMethods());
3075 size_t class_def_method_index = 0;
3076 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
3077 size_t last_class_def_method_index = 0;
3078 // TODO These should really use the iterators.
3079 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3080 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
3081 LoadMethod(self, dex_file, it, klass, method);
3082 LinkCode(method, oat_class, class_def_method_index);
3083 uint32_t it_method_index = it.GetMemberIndex();
3084 if (last_dex_method_index == it_method_index) {
3085 // duplicate case
3086 method->SetMethodIndex(last_class_def_method_index);
3087 } else {
3088 method->SetMethodIndex(class_def_method_index);
3089 last_dex_method_index = it_method_index;
3090 last_class_def_method_index = class_def_method_index;
3091 }
3092 class_def_method_index++;
3093 }
3094 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3095 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3096 LoadMethod(self, dex_file, it, klass, method);
3097 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
3098 LinkCode(method, oat_class, class_def_method_index);
3099 class_def_method_index++;
3100 }
3101 DCHECK(!it.HasNext());
3102 }
3103 // Ensure that the card is marked so that remembered sets pick up native roots.
3104 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
3105 self->AllowThreadSuspension();
3106 }
3107
LoadField(const ClassDataItemIterator & it,Handle<mirror::Class> klass,ArtField * dst)3108 void ClassLinker::LoadField(const ClassDataItemIterator& it,
3109 Handle<mirror::Class> klass,
3110 ArtField* dst) {
3111 const uint32_t field_idx = it.GetMemberIndex();
3112 dst->SetDexFieldIndex(field_idx);
3113 dst->SetDeclaringClass(klass.Get());
3114 dst->SetAccessFlags(it.GetFieldAccessFlags());
3115 }
3116
LoadMethod(Thread * self,const DexFile & dex_file,const ClassDataItemIterator & it,Handle<mirror::Class> klass,ArtMethod * dst)3117 void ClassLinker::LoadMethod(Thread* self,
3118 const DexFile& dex_file,
3119 const ClassDataItemIterator& it,
3120 Handle<mirror::Class> klass,
3121 ArtMethod* dst) {
3122 uint32_t dex_method_idx = it.GetMemberIndex();
3123 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
3124 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
3125
3126 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
3127 dst->SetDexMethodIndex(dex_method_idx);
3128 dst->SetDeclaringClass(klass.Get());
3129 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
3130
3131 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
3132 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_);
3133
3134 uint32_t access_flags = it.GetMethodAccessFlags();
3135
3136 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
3137 // Set finalizable flag on declaring class.
3138 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3139 // Void return type.
3140 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
3141 klass->SetFinalizable();
3142 } else {
3143 std::string temp;
3144 const char* klass_descriptor = klass->GetDescriptor(&temp);
3145 // The Enum class declares a "final" finalize() method to prevent subclasses from
3146 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3147 // subclasses, so we exclude it here.
3148 // We also want to avoid setting the flag on Object, where we know that finalize() is
3149 // empty.
3150 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3151 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
3152 klass->SetFinalizable();
3153 }
3154 }
3155 }
3156 } else if (method_name[0] == '<') {
3157 // Fix broken access flags for initializers. Bug 11157540.
3158 bool is_init = (strcmp("<init>", method_name) == 0);
3159 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
3160 if (UNLIKELY(!is_init && !is_clinit)) {
3161 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3162 } else {
3163 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3164 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
3165 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
3166 access_flags |= kAccConstructor;
3167 }
3168 }
3169 }
3170 dst->SetAccessFlags(access_flags);
3171 }
3172
AppendToBootClassPath(Thread * self,const DexFile & dex_file)3173 void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
3174 StackHandleScope<1> hs(self);
3175 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(
3176 self,
3177 dex_file,
3178 Runtime::Current()->GetLinearAlloc())));
3179 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3180 << dex_file.GetLocation();
3181 AppendToBootClassPath(dex_file, dex_cache);
3182 }
3183
AppendToBootClassPath(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3184 void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
3185 Handle<mirror::DexCache> dex_cache) {
3186 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
3187 boot_class_path_.push_back(&dex_file);
3188 RegisterDexFile(dex_file, dex_cache);
3189 }
3190
RegisterDexFileLocked(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3191 void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
3192 Handle<mirror::DexCache> dex_cache) {
3193 Thread* const self = Thread::Current();
3194 dex_lock_.AssertExclusiveHeld(self);
3195 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
3196 // For app images, the dex cache location may be a suffix of the dex file location since the
3197 // dex file location is an absolute path.
3198 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3199 const size_t dex_cache_length = dex_cache_location.length();
3200 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3201 std::string dex_file_location = dex_file.GetLocation();
3202 CHECK_GE(dex_file_location.length(), dex_cache_length)
3203 << dex_cache_location << " " << dex_file.GetLocation();
3204 // Take suffix.
3205 const std::string dex_file_suffix = dex_file_location.substr(
3206 dex_file_location.length() - dex_cache_length,
3207 dex_cache_length);
3208 // Example dex_cache location is SettingsProvider.apk and
3209 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3210 CHECK_EQ(dex_cache_location, dex_file_suffix);
3211 // Clean up pass to remove null dex caches.
3212 // Null dex caches can occur due to class unloading and we are lazily removing null entries.
3213 JavaVMExt* const vm = self->GetJniEnv()->vm;
3214 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3215 DexCacheData data = *it;
3216 if (self->IsJWeakCleared(data.weak_root)) {
3217 vm->DeleteWeakGlobalRef(self, data.weak_root);
3218 it = dex_caches_.erase(it);
3219 } else {
3220 ++it;
3221 }
3222 }
3223 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache.Get());
3224 dex_cache->SetDexFile(&dex_file);
3225 DexCacheData data;
3226 data.weak_root = dex_cache_jweak;
3227 data.dex_file = dex_cache->GetDexFile();
3228 data.resolved_types = dex_cache->GetResolvedTypes();
3229 dex_caches_.push_back(data);
3230 }
3231
RegisterDexFile(const DexFile & dex_file,mirror::ClassLoader * class_loader)3232 mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file,
3233 mirror::ClassLoader* class_loader) {
3234 Thread* self = Thread::Current();
3235 {
3236 ReaderMutexLock mu(self, dex_lock_);
3237 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3238 if (dex_cache != nullptr) {
3239 return dex_cache;
3240 }
3241 }
3242 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3243 DCHECK(linear_alloc != nullptr);
3244 ClassTable* table;
3245 {
3246 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3247 table = InsertClassTableForClassLoader(class_loader);
3248 }
3249 // Don't alloc while holding the lock, since allocation may need to
3250 // suspend all threads and another thread may need the dex_lock_ to
3251 // get to a suspend point.
3252 StackHandleScope<1> hs(self);
3253 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file, linear_alloc)));
3254 {
3255 WriterMutexLock mu(self, dex_lock_);
3256 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3257 if (dex_cache != nullptr) {
3258 return dex_cache;
3259 }
3260 if (h_dex_cache.Get() == nullptr) {
3261 self->AssertPendingOOMException();
3262 return nullptr;
3263 }
3264 RegisterDexFileLocked(dex_file, h_dex_cache);
3265 }
3266 table->InsertStrongRoot(h_dex_cache.Get());
3267 return h_dex_cache.Get();
3268 }
3269
RegisterDexFile(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3270 void ClassLinker::RegisterDexFile(const DexFile& dex_file,
3271 Handle<mirror::DexCache> dex_cache) {
3272 WriterMutexLock mu(Thread::Current(), dex_lock_);
3273 RegisterDexFileLocked(dex_file, dex_cache);
3274 }
3275
FindDexCache(Thread * self,const DexFile & dex_file,bool allow_failure)3276 mirror::DexCache* ClassLinker::FindDexCache(Thread* self,
3277 const DexFile& dex_file,
3278 bool allow_failure) {
3279 ReaderMutexLock mu(self, dex_lock_);
3280 return FindDexCacheLocked(self, dex_file, allow_failure);
3281 }
3282
FindDexCacheLocked(Thread * self,const DexFile & dex_file,bool allow_failure)3283 mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self,
3284 const DexFile& dex_file,
3285 bool allow_failure) {
3286 // Search assuming unique-ness of dex file.
3287 for (const DexCacheData& data : dex_caches_) {
3288 // Avoid decoding (and read barriers) other unrelated dex caches.
3289 if (data.dex_file == &dex_file) {
3290 mirror::DexCache* dex_cache =
3291 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
3292 if (dex_cache != nullptr) {
3293 return dex_cache;
3294 } else {
3295 break;
3296 }
3297 }
3298 }
3299 if (allow_failure) {
3300 return nullptr;
3301 }
3302 std::string location(dex_file.GetLocation());
3303 // Failure, dump diagnostic and abort.
3304 for (const DexCacheData& data : dex_caches_) {
3305 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
3306 if (dex_cache != nullptr) {
3307 LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation();
3308 }
3309 }
3310 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
3311 UNREACHABLE();
3312 }
3313
FixupDexCaches(ArtMethod * resolution_method)3314 void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
3315 Thread* const self = Thread::Current();
3316 ReaderMutexLock mu(self, dex_lock_);
3317 for (const DexCacheData& data : dex_caches_) {
3318 if (!self->IsJWeakCleared(data.weak_root)) {
3319 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(
3320 self->DecodeJObject(data.weak_root));
3321 if (dex_cache != nullptr) {
3322 dex_cache->Fixup(resolution_method, image_pointer_size_);
3323 }
3324 }
3325 }
3326 }
3327
CreatePrimitiveClass(Thread * self,Primitive::Type type)3328 mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
3329 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
3330 if (UNLIKELY(klass == nullptr)) {
3331 self->AssertPendingOOMException();
3332 return nullptr;
3333 }
3334 return InitializePrimitiveClass(klass, type);
3335 }
3336
InitializePrimitiveClass(mirror::Class * primitive_class,Primitive::Type type)3337 mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3338 Primitive::Type type) {
3339 CHECK(primitive_class != nullptr);
3340 // Must hold lock on object when initializing.
3341 Thread* self = Thread::Current();
3342 StackHandleScope<1> hs(self);
3343 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
3344 ObjectLock<mirror::Class> lock(self, h_class);
3345 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3346 h_class->SetPrimitiveType(type);
3347 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
3348 const char* descriptor = Primitive::Descriptor(type);
3349 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
3350 ComputeModifiedUtf8Hash(descriptor));
3351 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
3352 return h_class.Get();
3353 }
3354
3355 // Create an array class (i.e. the class object for the array, not the
3356 // array itself). "descriptor" looks like "[C" or "[[[[B" or
3357 // "[Ljava/lang/String;".
3358 //
3359 // If "descriptor" refers to an array of primitives, look up the
3360 // primitive type's internally-generated class object.
3361 //
3362 // "class_loader" is the class loader of the class that's referring to
3363 // us. It's used to ensure that we're looking for the element type in
3364 // the right context. It does NOT become the class loader for the
3365 // array class; that always comes from the base element class.
3366 //
3367 // Returns null with an exception raised on failure.
CreateArrayClass(Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader)3368 mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
3369 Handle<mirror::ClassLoader> class_loader) {
3370 // Identify the underlying component type
3371 CHECK_EQ('[', descriptor[0]);
3372 StackHandleScope<2> hs(self);
3373 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3374 class_loader)));
3375 if (component_type.Get() == nullptr) {
3376 DCHECK(self->IsExceptionPending());
3377 // We need to accept erroneous classes as component types.
3378 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3379 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
3380 if (component_type.Get() == nullptr) {
3381 DCHECK(self->IsExceptionPending());
3382 return nullptr;
3383 } else {
3384 self->ClearException();
3385 }
3386 }
3387 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3388 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3389 return nullptr;
3390 }
3391 // See if the component type is already loaded. Array classes are
3392 // always associated with the class loader of their underlying
3393 // element type -- an array of Strings goes with the loader for
3394 // java/lang/String -- so we need to look for it there. (The
3395 // caller should have checked for the existence of the class
3396 // before calling here, but they did so with *their* class loader,
3397 // not the component type's loader.)
3398 //
3399 // If we find it, the caller adds "loader" to the class' initiating
3400 // loader list, which should prevent us from going through this again.
3401 //
3402 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
3403 // are the same, because our caller (FindClass) just did the
3404 // lookup. (Even if we get this wrong we still have correct behavior,
3405 // because we effectively do this lookup again when we add the new
3406 // class to the hash table --- necessary because of possible races with
3407 // other threads.)
3408 if (class_loader.Get() != component_type->GetClassLoader()) {
3409 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
3410 if (new_class != nullptr) {
3411 return new_class;
3412 }
3413 }
3414
3415 // Fill out the fields in the Class.
3416 //
3417 // It is possible to execute some methods against arrays, because
3418 // all arrays are subclasses of java_lang_Object_, so we need to set
3419 // up a vtable. We can just point at the one in java_lang_Object_.
3420 //
3421 // Array classes are simple enough that we don't need to do a full
3422 // link step.
3423 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
3424 if (UNLIKELY(!init_done_)) {
3425 // Classes that were hand created, ie not by FindSystemClass
3426 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
3427 new_class.Assign(GetClassRoot(kClassArrayClass));
3428 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
3429 new_class.Assign(GetClassRoot(kObjectArrayClass));
3430 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
3431 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
3432 } else if (strcmp(descriptor, "[C") == 0) {
3433 new_class.Assign(GetClassRoot(kCharArrayClass));
3434 } else if (strcmp(descriptor, "[I") == 0) {
3435 new_class.Assign(GetClassRoot(kIntArrayClass));
3436 } else if (strcmp(descriptor, "[J") == 0) {
3437 new_class.Assign(GetClassRoot(kLongArrayClass));
3438 }
3439 }
3440 if (new_class.Get() == nullptr) {
3441 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
3442 if (new_class.Get() == nullptr) {
3443 self->AssertPendingOOMException();
3444 return nullptr;
3445 }
3446 new_class->SetComponentType(component_type.Get());
3447 }
3448 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
3449 DCHECK(new_class->GetComponentType() != nullptr);
3450 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
3451 new_class->SetSuperClass(java_lang_Object);
3452 new_class->SetVTable(java_lang_Object->GetVTable());
3453 new_class->SetPrimitiveType(Primitive::kPrimNot);
3454 new_class->SetClassLoader(component_type->GetClassLoader());
3455 if (component_type->IsPrimitive()) {
3456 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3457 } else {
3458 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3459 }
3460 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
3461 new_class->PopulateEmbeddedVTable(image_pointer_size_);
3462 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
3463 new_class->SetImt(object_imt, image_pointer_size_);
3464 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
3465 // don't need to set new_class->SetObjectSize(..)
3466 // because Object::SizeOf delegates to Array::SizeOf
3467
3468 // All arrays have java/lang/Cloneable and java/io/Serializable as
3469 // interfaces. We need to set that up here, so that stuff like
3470 // "instanceof" works right.
3471 //
3472 // Note: The GC could run during the call to FindSystemClass,
3473 // so we need to make sure the class object is GC-valid while we're in
3474 // there. Do this by clearing the interface list so the GC will just
3475 // think that the entries are null.
3476
3477
3478 // Use the single, global copies of "interfaces" and "iftable"
3479 // (remember not to free them for arrays).
3480 {
3481 mirror::IfTable* array_iftable = array_iftable_.Read();
3482 CHECK(array_iftable != nullptr);
3483 new_class->SetIfTable(array_iftable);
3484 }
3485
3486 // Inherit access flags from the component type.
3487 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3488 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3489 access_flags &= kAccJavaFlagsMask;
3490 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
3491 // and remove "interface".
3492 access_flags |= kAccAbstract | kAccFinal;
3493 access_flags &= ~kAccInterface;
3494
3495 new_class->SetAccessFlags(access_flags);
3496
3497 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
3498 if (existing == nullptr) {
3499 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
3500 return new_class.Get();
3501 }
3502 // Another thread must have loaded the class after we
3503 // started but before we finished. Abandon what we've
3504 // done.
3505 //
3506 // (Yes, this happens.)
3507
3508 return existing;
3509 }
3510
FindPrimitiveClass(char type)3511 mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
3512 switch (type) {
3513 case 'B':
3514 return GetClassRoot(kPrimitiveByte);
3515 case 'C':
3516 return GetClassRoot(kPrimitiveChar);
3517 case 'D':
3518 return GetClassRoot(kPrimitiveDouble);
3519 case 'F':
3520 return GetClassRoot(kPrimitiveFloat);
3521 case 'I':
3522 return GetClassRoot(kPrimitiveInt);
3523 case 'J':
3524 return GetClassRoot(kPrimitiveLong);
3525 case 'S':
3526 return GetClassRoot(kPrimitiveShort);
3527 case 'Z':
3528 return GetClassRoot(kPrimitiveBoolean);
3529 case 'V':
3530 return GetClassRoot(kPrimitiveVoid);
3531 default:
3532 break;
3533 }
3534 std::string printable_type(PrintableChar(type));
3535 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
3536 return nullptr;
3537 }
3538
InsertClass(const char * descriptor,mirror::Class * klass,size_t hash)3539 mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) {
3540 if (VLOG_IS_ON(class_linker)) {
3541 mirror::DexCache* dex_cache = klass->GetDexCache();
3542 std::string source;
3543 if (dex_cache != nullptr) {
3544 source += " from ";
3545 source += dex_cache->GetLocation()->ToModifiedUtf8();
3546 }
3547 LOG(INFO) << "Loaded class " << descriptor << source;
3548 }
3549 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3550 mirror::ClassLoader* const class_loader = klass->GetClassLoader();
3551 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
3552 mirror::Class* existing = class_table->Lookup(descriptor, hash);
3553 if (existing != nullptr) {
3554 return existing;
3555 }
3556 if (kIsDebugBuild &&
3557 !klass->IsTemp() &&
3558 class_loader == nullptr &&
3559 dex_cache_boot_image_class_lookup_required_) {
3560 // Check a class loaded with the system class loader matches one in the image if the class
3561 // is in the image.
3562 existing = LookupClassFromBootImage(descriptor);
3563 if (existing != nullptr) {
3564 CHECK_EQ(klass, existing);
3565 }
3566 }
3567 VerifyObject(klass);
3568 class_table->InsertWithHash(klass, hash);
3569 if (class_loader != nullptr) {
3570 // This is necessary because we need to have the card dirtied for remembered sets.
3571 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3572 }
3573 if (log_new_class_table_roots_) {
3574 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3575 }
3576 return nullptr;
3577 }
3578
3579 // TODO This should really be in mirror::Class.
UpdateClassMethods(mirror::Class * klass,LengthPrefixedArray<ArtMethod> * new_methods)3580 void ClassLinker::UpdateClassMethods(mirror::Class* klass,
3581 LengthPrefixedArray<ArtMethod>* new_methods) {
3582 klass->SetMethodsPtrUnchecked(new_methods,
3583 klass->NumDirectMethods(),
3584 klass->NumDeclaredVirtualMethods());
3585 // Need to mark the card so that the remembered sets and mod union tables get updated.
3586 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
3587 }
3588
RemoveClass(const char * descriptor,mirror::ClassLoader * class_loader)3589 bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
3590 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3591 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3592 return class_table != nullptr && class_table->Remove(descriptor);
3593 }
3594
LookupClass(Thread * self,const char * descriptor,size_t hash,mirror::ClassLoader * class_loader)3595 mirror::Class* ClassLinker::LookupClass(Thread* self,
3596 const char* descriptor,
3597 size_t hash,
3598 mirror::ClassLoader* class_loader) {
3599 {
3600 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3601 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3602 if (class_table != nullptr) {
3603 mirror::Class* result = class_table->Lookup(descriptor, hash);
3604 if (result != nullptr) {
3605 return result;
3606 }
3607 }
3608 }
3609 if (class_loader != nullptr || !dex_cache_boot_image_class_lookup_required_) {
3610 return nullptr;
3611 }
3612 // Lookup failed but need to search dex_caches_.
3613 mirror::Class* result = LookupClassFromBootImage(descriptor);
3614 if (result != nullptr) {
3615 result = InsertClass(descriptor, result, hash);
3616 } else {
3617 // Searching the image dex files/caches failed, we don't want to get into this situation
3618 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3619 // classes into the class table.
3620 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
3621 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3622 AddBootImageClassesToClassTable();
3623 }
3624 }
3625 return result;
3626 }
3627
GetImageDexCaches(std::vector<gc::space::ImageSpace * > image_spaces)3628 static std::vector<mirror::ObjectArray<mirror::DexCache>*> GetImageDexCaches(
3629 std::vector<gc::space::ImageSpace*> image_spaces) SHARED_REQUIRES(Locks::mutator_lock_) {
3630 CHECK(!image_spaces.empty());
3631 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector;
3632 for (gc::space::ImageSpace* image_space : image_spaces) {
3633 mirror::Object* root = image_space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3634 DCHECK(root != nullptr);
3635 dex_caches_vector.push_back(root->AsObjectArray<mirror::DexCache>());
3636 }
3637 return dex_caches_vector;
3638 }
3639
AddBootImageClassesToClassTable()3640 void ClassLinker::AddBootImageClassesToClassTable() {
3641 if (dex_cache_boot_image_class_lookup_required_) {
3642 AddImageClassesToClassTable(Runtime::Current()->GetHeap()->GetBootImageSpaces(),
3643 /*class_loader*/nullptr);
3644 dex_cache_boot_image_class_lookup_required_ = false;
3645 }
3646 }
3647
AddImageClassesToClassTable(std::vector<gc::space::ImageSpace * > image_spaces,mirror::ClassLoader * class_loader)3648 void ClassLinker::AddImageClassesToClassTable(std::vector<gc::space::ImageSpace*> image_spaces,
3649 mirror::ClassLoader* class_loader) {
3650 Thread* self = Thread::Current();
3651 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3652 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
3653
3654 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
3655
3656 std::string temp;
3657 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector =
3658 GetImageDexCaches(image_spaces);
3659 for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) {
3660 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3661 mirror::DexCache* dex_cache = dex_caches->Get(i);
3662 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
3663 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
3664 mirror::Class* klass = types[j].Read();
3665 if (klass != nullptr) {
3666 DCHECK_EQ(klass->GetClassLoader(), class_loader);
3667 const char* descriptor = klass->GetDescriptor(&temp);
3668 size_t hash = ComputeModifiedUtf8Hash(descriptor);
3669 mirror::Class* existing = class_table->Lookup(descriptor, hash);
3670 if (existing != nullptr) {
3671 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
3672 << PrettyClassAndClassLoader(klass);
3673 } else {
3674 class_table->Insert(klass);
3675 if (log_new_class_table_roots_) {
3676 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3677 }
3678 }
3679 }
3680 }
3681 }
3682 }
3683 }
3684
3685 class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3686 public:
MoveClassTableToPreZygoteVisitor()3687 explicit MoveClassTableToPreZygoteVisitor() {}
3688
Visit(mirror::ClassLoader * class_loader)3689 void Visit(mirror::ClassLoader* class_loader)
3690 REQUIRES(Locks::classlinker_classes_lock_)
3691 SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE {
3692 ClassTable* const class_table = class_loader->GetClassTable();
3693 if (class_table != nullptr) {
3694 class_table->FreezeSnapshot();
3695 }
3696 }
3697 };
3698
MoveClassTableToPreZygote()3699 void ClassLinker::MoveClassTableToPreZygote() {
3700 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3701 boot_class_table_.FreezeSnapshot();
3702 MoveClassTableToPreZygoteVisitor visitor;
3703 VisitClassLoaders(&visitor);
3704 }
3705
LookupClassFromBootImage(const char * descriptor)3706 mirror::Class* ClassLinker::LookupClassFromBootImage(const char* descriptor) {
3707 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
3708 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector =
3709 GetImageDexCaches(Runtime::Current()->GetHeap()->GetBootImageSpaces());
3710 for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) {
3711 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3712 mirror::DexCache* dex_cache = dex_caches->Get(i);
3713 const DexFile* dex_file = dex_cache->GetDexFile();
3714 // Try binary searching the type index by descriptor.
3715 const DexFile::TypeId* type_id = dex_file->FindTypeId(descriptor);
3716 if (type_id != nullptr) {
3717 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3718 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3719 if (klass != nullptr) {
3720 return klass;
3721 }
3722 }
3723 }
3724 }
3725 return nullptr;
3726 }
3727
3728 // Look up classes by hash and descriptor and put all matching ones in the result array.
3729 class LookupClassesVisitor : public ClassLoaderVisitor {
3730 public:
LookupClassesVisitor(const char * descriptor,size_t hash,std::vector<mirror::Class * > * result)3731 LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result)
3732 : descriptor_(descriptor),
3733 hash_(hash),
3734 result_(result) {}
3735
Visit(mirror::ClassLoader * class_loader)3736 void Visit(mirror::ClassLoader* class_loader)
3737 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
3738 ClassTable* const class_table = class_loader->GetClassTable();
3739 mirror::Class* klass = class_table->Lookup(descriptor_, hash_);
3740 if (klass != nullptr) {
3741 result_->push_back(klass);
3742 }
3743 }
3744
3745 private:
3746 const char* const descriptor_;
3747 const size_t hash_;
3748 std::vector<mirror::Class*>* const result_;
3749 };
3750
LookupClasses(const char * descriptor,std::vector<mirror::Class * > & result)3751 void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3752 result.clear();
3753 if (dex_cache_boot_image_class_lookup_required_) {
3754 AddBootImageClassesToClassTable();
3755 }
3756 Thread* const self = Thread::Current();
3757 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3758 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
3759 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash);
3760 if (klass != nullptr) {
3761 result.push_back(klass);
3762 }
3763 LookupClassesVisitor visitor(descriptor, hash, &result);
3764 VisitClassLoaders(&visitor);
3765 }
3766
AttemptSupertypeVerification(Thread * self,Handle<mirror::Class> klass,Handle<mirror::Class> supertype)3767 bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3768 Handle<mirror::Class> klass,
3769 Handle<mirror::Class> supertype) {
3770 DCHECK(self != nullptr);
3771 DCHECK(klass.Get() != nullptr);
3772 DCHECK(supertype.Get() != nullptr);
3773
3774 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3775 VerifyClass(self, supertype);
3776 }
3777 if (supertype->IsCompileTimeVerified()) {
3778 // Either we are verified or we soft failed and need to retry at runtime.
3779 return true;
3780 }
3781 // If we got this far then we have a hard failure.
3782 std::string error_msg =
3783 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
3784 PrettyDescriptor(klass.Get()).c_str(),
3785 PrettyDescriptor(supertype.Get()).c_str());
3786 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3787 StackHandleScope<1> hs(self);
3788 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
3789 if (cause.Get() != nullptr) {
3790 // Set during VerifyClass call (if at all).
3791 self->ClearException();
3792 }
3793 // Change into a verify error.
3794 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3795 if (cause.Get() != nullptr) {
3796 self->GetException()->SetCause(cause.Get());
3797 }
3798 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3799 if (Runtime::Current()->IsAotCompiler()) {
3800 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3801 }
3802 // Need to grab the lock to change status.
3803 ObjectLock<mirror::Class> super_lock(self, klass);
3804 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3805 return false;
3806 }
3807
VerifyClass(Thread * self,Handle<mirror::Class> klass,LogSeverity log_level)3808 void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass, LogSeverity log_level) {
3809 {
3810 // TODO: assert that the monitor on the Class is held
3811 ObjectLock<mirror::Class> lock(self, klass);
3812
3813 // Is somebody verifying this now?
3814 mirror::Class::Status old_status = klass->GetStatus();
3815 while (old_status == mirror::Class::kStatusVerifying ||
3816 old_status == mirror::Class::kStatusVerifyingAtRuntime) {
3817 lock.WaitIgnoringInterrupts();
3818 CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status))
3819 << "Class '" << PrettyClass(klass.Get()) << "' performed an illegal verification state "
3820 << "transition from " << old_status << " to " << klass->GetStatus();
3821 old_status = klass->GetStatus();
3822 }
3823
3824 // The class might already be erroneous, for example at compile time if we attempted to verify
3825 // this class as a parent to another.
3826 if (klass->IsErroneous()) {
3827 ThrowEarlierClassFailure(klass.Get());
3828 return;
3829 }
3830
3831 // Don't attempt to re-verify if already sufficiently verified.
3832 if (klass->IsVerified()) {
3833 EnsureSkipAccessChecksMethods(klass);
3834 return;
3835 }
3836 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
3837 return;
3838 }
3839
3840 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3841 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
3842 } else {
3843 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
3844 << PrettyClass(klass.Get());
3845 CHECK(!Runtime::Current()->IsAotCompiler());
3846 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
3847 }
3848
3849 // Skip verification if disabled.
3850 if (!Runtime::Current()->IsVerificationEnabled()) {
3851 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3852 EnsureSkipAccessChecksMethods(klass);
3853 return;
3854 }
3855 }
3856
3857 // Verify super class.
3858 StackHandleScope<2> hs(self);
3859 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
3860 // If we have a superclass and we get a hard verification failure we can return immediately.
3861 if (supertype.Get() != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
3862 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3863 return;
3864 }
3865
3866 // Verify all default super-interfaces.
3867 //
3868 // (1) Don't bother if the superclass has already had a soft verification failure.
3869 //
3870 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
3871 // recursive initialization by themselves. This is because when an interface is initialized
3872 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
3873 // but choose not to for an optimization. If the interfaces is being verified due to a class
3874 // initialization (which would need all the default interfaces to be verified) the class code
3875 // will trigger the recursive verification anyway.
3876 if ((supertype.Get() == nullptr || supertype->IsVerified()) // See (1)
3877 && !klass->IsInterface()) { // See (2)
3878 int32_t iftable_count = klass->GetIfTableCount();
3879 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
3880 // Loop through all interfaces this class has defined. It doesn't matter the order.
3881 for (int32_t i = 0; i < iftable_count; i++) {
3882 iface.Assign(klass->GetIfTable()->GetInterface(i));
3883 DCHECK(iface.Get() != nullptr);
3884 // We only care if we have default interfaces and can skip if we are already verified...
3885 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
3886 continue;
3887 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
3888 // We had a hard failure while verifying this interface. Just return immediately.
3889 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3890 return;
3891 } else if (UNLIKELY(!iface->IsVerified())) {
3892 // We softly failed to verify the iface. Stop checking and clean up.
3893 // Put the iface into the supertype handle so we know what caused us to fail.
3894 supertype.Assign(iface.Get());
3895 break;
3896 }
3897 }
3898 }
3899
3900 // At this point if verification failed, then supertype is the "first" supertype that failed
3901 // verification (without a specific order). If verification succeeded, then supertype is either
3902 // null or the original superclass of klass and is verified.
3903 DCHECK(supertype.Get() == nullptr ||
3904 supertype.Get() == klass->GetSuperClass() ||
3905 !supertype->IsVerified());
3906
3907 // Try to use verification information from the oat file, otherwise do runtime verification.
3908 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
3909 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
3910 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
3911 // If the oat file says the class had an error, re-run the verifier. That way we will get a
3912 // precise error message. To ensure a rerun, test:
3913 // oat_file_class_status == mirror::Class::kStatusError => !preverified
3914 DCHECK(!(oat_file_class_status == mirror::Class::kStatusError) || !preverified);
3915
3916 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
3917 std::string error_msg;
3918 if (!preverified) {
3919 Runtime* runtime = Runtime::Current();
3920 verifier_failure = verifier::MethodVerifier::VerifyClass(self,
3921 klass.Get(),
3922 runtime->GetCompilerCallbacks(),
3923 runtime->IsAotCompiler(),
3924 log_level,
3925 &error_msg);
3926 }
3927
3928 // Verification is done, grab the lock again.
3929 ObjectLock<mirror::Class> lock(self, klass);
3930
3931 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
3932 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
3933 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
3934 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3935 << " because: " << error_msg;
3936 }
3937 self->AssertNoPendingException();
3938 // Make sure all classes referenced by catch blocks are resolved.
3939 ResolveClassExceptionHandlerTypes(klass);
3940 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
3941 // Even though there were no verifier failures we need to respect whether the super-class and
3942 // super-default-interfaces were verified or requiring runtime reverification.
3943 if (supertype.Get() == nullptr || supertype->IsVerified()) {
3944 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3945 } else {
3946 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
3947 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
3948 // Pretend a soft failure occurred so that we don't consider the class verified below.
3949 verifier_failure = verifier::MethodVerifier::kSoftFailure;
3950 }
3951 } else {
3952 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3953 // Soft failures at compile time should be retried at runtime. Soft
3954 // failures at runtime will be handled by slow paths in the generated
3955 // code. Set status accordingly.
3956 if (Runtime::Current()->IsAotCompiler()) {
3957 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
3958 } else {
3959 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3960 // As this is a fake verified status, make sure the methods are _not_ marked
3961 // kAccSkipAccessChecks later.
3962 klass->SetVerificationAttempted();
3963 }
3964 }
3965 } else {
3966 VLOG(verifier) << "Verification failed on class " << PrettyDescriptor(klass.Get())
3967 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3968 << " because: " << error_msg;
3969 self->AssertNoPendingException();
3970 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3971 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3972 }
3973 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
3974 // Class is verified so we don't need to do any access check on its methods.
3975 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
3976 // method.
3977 // Note: we're going here during compilation and at runtime. When we set the
3978 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
3979 // in the image and is set when loading the image.
3980
3981 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
3982 // Never skip access checks if the verification soft fail is forced.
3983 // Mark the class as having a verification attempt to avoid re-running the verifier.
3984 klass->SetVerificationAttempted();
3985 } else {
3986 EnsureSkipAccessChecksMethods(klass);
3987 }
3988 }
3989 }
3990
EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass)3991 void ClassLinker::EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass) {
3992 if (!klass->WasVerificationAttempted()) {
3993 klass->SetSkipAccessChecksFlagOnAllMethods(image_pointer_size_);
3994 klass->SetVerificationAttempted();
3995 }
3996 }
3997
VerifyClassUsingOatFile(const DexFile & dex_file,mirror::Class * klass,mirror::Class::Status & oat_file_class_status)3998 bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
3999 mirror::Class* klass,
4000 mirror::Class::Status& oat_file_class_status) {
4001 // If we're compiling, we can only verify the class using the oat file if
4002 // we are not compiling the image or if the class we're verifying is not part of
4003 // the app. In other words, we will only check for preverification of bootclasspath
4004 // classes.
4005 if (Runtime::Current()->IsAotCompiler()) {
4006 // Are we compiling the bootclasspath?
4007 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
4008 return false;
4009 }
4010 // We are compiling an app (not the image).
4011
4012 // Is this an app class? (I.e. not a bootclasspath class)
4013 if (klass->GetClassLoader() != nullptr) {
4014 return false;
4015 }
4016 }
4017
4018 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
4019 // In case we run without an image there won't be a backing oat file.
4020 if (oat_dex_file == nullptr) {
4021 return false;
4022 }
4023
4024 // We may be running with a preopted oat file but without image. In this case,
4025 // we don't skip verification of skip_access_checks classes to ensure we initialize
4026 // dex caches with all types resolved during verification.
4027 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
4028 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
4029 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
4030 // already pre-opted, as then the runtime is started.
4031 if (!Runtime::Current()->IsAotCompiler() &&
4032 !Runtime::Current()->GetHeap()->HasBootImageSpace() &&
4033 klass->GetClassLoader() != nullptr) {
4034 return false;
4035 }
4036
4037 uint16_t class_def_index = klass->GetDexClassDefIndex();
4038 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
4039 if (oat_file_class_status == mirror::Class::kStatusVerified ||
4040 oat_file_class_status == mirror::Class::kStatusInitialized) {
4041 return true;
4042 }
4043 // If we only verified a subset of the classes at compile time, we can end up with classes that
4044 // were resolved by the verifier.
4045 if (oat_file_class_status == mirror::Class::kStatusResolved) {
4046 return false;
4047 }
4048 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
4049 // Compile time verification failed with a soft error. Compile time verification can fail
4050 // because we have incomplete type information. Consider the following:
4051 // class ... {
4052 // Foo x;
4053 // .... () {
4054 // if (...) {
4055 // v1 gets assigned a type of resolved class Foo
4056 // } else {
4057 // v1 gets assigned a type of unresolved class Bar
4058 // }
4059 // iput x = v1
4060 // } }
4061 // when we merge v1 following the if-the-else it results in Conflict
4062 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4063 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4064 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4065 // at compile time).
4066 return false;
4067 }
4068 if (oat_file_class_status == mirror::Class::kStatusError) {
4069 // Compile time verification failed with a hard error. This is caused by invalid instructions
4070 // in the class. These errors are unrecoverable.
4071 return false;
4072 }
4073 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
4074 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4075 // not loading the class.
4076 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4077 // isn't a problem and this case shouldn't occur
4078 return false;
4079 }
4080 std::string temp;
4081 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
4082 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
4083 << klass->GetDescriptor(&temp);
4084 UNREACHABLE();
4085 }
4086
ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass)4087 void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
4088 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
4089 ResolveMethodExceptionHandlerTypes(&method);
4090 }
4091 }
4092
ResolveMethodExceptionHandlerTypes(ArtMethod * method)4093 void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
4094 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
4095 const DexFile::CodeItem* code_item =
4096 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
4097 if (code_item == nullptr) {
4098 return; // native or abstract method
4099 }
4100 if (code_item->tries_size_ == 0) {
4101 return; // nothing to process
4102 }
4103 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
4104 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
4105 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4106 CatchHandlerIterator iterator(handlers_ptr);
4107 for (; iterator.HasNext(); iterator.Next()) {
4108 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4109 // unresolved exception types will be ignored by exception delivery
4110 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
4111 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
4112 if (exception_type == nullptr) {
4113 DCHECK(Thread::Current()->IsExceptionPending());
4114 Thread::Current()->ClearException();
4115 }
4116 }
4117 }
4118 handlers_ptr = iterator.EndDataPointer();
4119 }
4120 }
4121
CreateProxyClass(ScopedObjectAccessAlreadyRunnable & soa,jstring name,jobjectArray interfaces,jobject loader,jobjectArray methods,jobjectArray throws)4122 mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4123 jstring name,
4124 jobjectArray interfaces,
4125 jobject loader,
4126 jobjectArray methods,
4127 jobjectArray throws) {
4128 Thread* self = soa.Self();
4129 StackHandleScope<10> hs(self);
4130 MutableHandle<mirror::Class> klass(hs.NewHandle(
4131 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
4132 if (klass.Get() == nullptr) {
4133 CHECK(self->IsExceptionPending()); // OOME.
4134 return nullptr;
4135 }
4136 DCHECK(klass->GetClass() != nullptr);
4137 klass->SetObjectSize(sizeof(mirror::Proxy));
4138 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4139 // the methods.
4140 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4141 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
4142 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
4143 klass->SetName(soa.Decode<mirror::String*>(name));
4144 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
4145 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
4146 std::string descriptor(GetDescriptorForProxy(klass.Get()));
4147 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
4148
4149 // Needs to be before we insert the class so that the allocator field is set.
4150 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
4151
4152 // Insert the class before loading the fields as the field roots
4153 // (ArtField::declaring_class_) are only visited from the class
4154 // table. There can't be any suspend points between inserting the
4155 // class and setting the field arrays below.
4156 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
4157 CHECK(existing == nullptr);
4158
4159 // Instance fields are inherited, but we add a couple of static fields...
4160 const size_t num_fields = 2;
4161 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
4162 klass->SetSFieldsPtr(sfields);
4163
4164 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4165 // our proxy, so Class.getInterfaces doesn't return the flattened set.
4166 ArtField& interfaces_sfield = sfields->At(0);
4167 interfaces_sfield.SetDexFieldIndex(0);
4168 interfaces_sfield.SetDeclaringClass(klass.Get());
4169 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
4170
4171 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
4172 ArtField& throws_sfield = sfields->At(1);
4173 throws_sfield.SetDexFieldIndex(1);
4174 throws_sfield.SetDeclaringClass(klass.Get());
4175 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
4176
4177 // Proxies have 1 direct method, the constructor
4178 const size_t num_direct_methods = 1;
4179
4180 // They have as many virtual methods as the array
4181 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
4182 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
4183 << PrettyClass(h_methods->GetClass());
4184 const size_t num_virtual_methods = h_methods->GetLength();
4185
4186 // Create the methods array.
4187 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4188 self, allocator, num_direct_methods + num_virtual_methods);
4189 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4190 // want to throw OOM in the future.
4191 if (UNLIKELY(proxy_class_methods == nullptr)) {
4192 self->AssertPendingOOMException();
4193 return nullptr;
4194 }
4195 klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
4196
4197 // Create the single direct method.
4198 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
4199
4200 // Create virtual method using specified prototypes.
4201 // TODO These should really use the iterators.
4202 for (size_t i = 0; i < num_virtual_methods; ++i) {
4203 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4204 auto* prototype = h_methods->Get(i)->GetArtMethod();
4205 CreateProxyMethod(klass, prototype, virtual_method);
4206 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4207 DCHECK(prototype->GetDeclaringClass() != nullptr);
4208 }
4209
4210 // The super class is java.lang.reflect.Proxy
4211 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
4212 // Now effectively in the loaded state.
4213 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
4214 self->AssertNoPendingException();
4215
4216 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
4217 {
4218 // Must hold lock on object when resolved.
4219 ObjectLock<mirror::Class> resolution_lock(self, klass);
4220 // Link the fields and virtual methods, creating vtable and iftables.
4221 // The new class will replace the old one in the class table.
4222 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
4223 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
4224 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
4225 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4226 return nullptr;
4227 }
4228 }
4229 CHECK(klass->IsRetired());
4230 CHECK_NE(klass.Get(), new_class.Get());
4231 klass.Assign(new_class.Get());
4232
4233 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
4234 interfaces_sfield.SetObject<false>(klass.Get(),
4235 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
4236 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4237 throws_sfield.SetObject<false>(
4238 klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
4239
4240 {
4241 // Lock on klass is released. Lock new class object.
4242 ObjectLock<mirror::Class> initialization_lock(self, klass);
4243 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
4244 }
4245
4246 // sanity checks
4247 if (kIsDebugBuild) {
4248 CHECK(klass->GetIFieldsPtr() == nullptr);
4249 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4250
4251 for (size_t i = 0; i < num_virtual_methods; ++i) {
4252 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4253 auto* prototype = h_methods->Get(i++)->GetArtMethod();
4254 CheckProxyMethod(virtual_method, prototype);
4255 }
4256
4257 StackHandleScope<1> hs2(self);
4258 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name));
4259 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
4260 decoded_name->ToModifiedUtf8().c_str()));
4261 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
4262
4263 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
4264 decoded_name->ToModifiedUtf8().c_str()));
4265 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
4266
4267 CHECK_EQ(klass.Get()->GetInterfaces(),
4268 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
4269 CHECK_EQ(klass.Get()->GetThrows(),
4270 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
4271 }
4272 return klass.Get();
4273 }
4274
GetDescriptorForProxy(mirror::Class * proxy_class)4275 std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
4276 DCHECK(proxy_class->IsProxyClass());
4277 mirror::String* name = proxy_class->GetName();
4278 DCHECK(name != nullptr);
4279 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4280 }
4281
FindMethodForProxy(mirror::Class * proxy_class,ArtMethod * proxy_method)4282 ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) {
4283 DCHECK(proxy_class->IsProxyClass());
4284 DCHECK(proxy_method->IsProxyMethod());
4285 {
4286 Thread* const self = Thread::Current();
4287 ReaderMutexLock mu(self, dex_lock_);
4288 // Locate the dex cache of the original interface/Object
4289 for (const DexCacheData& data : dex_caches_) {
4290 if (!self->IsJWeakCleared(data.weak_root) &&
4291 proxy_method->HasSameDexCacheResolvedTypes(data.resolved_types,
4292 image_pointer_size_)) {
4293 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(
4294 self->DecodeJObject(data.weak_root));
4295 if (dex_cache != nullptr) {
4296 ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
4297 proxy_method->GetDexMethodIndex(), image_pointer_size_);
4298 CHECK(resolved_method != nullptr);
4299 return resolved_method;
4300 }
4301 }
4302 }
4303 }
4304 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
4305 << PrettyMethod(proxy_method);
4306 UNREACHABLE();
4307 }
4308
CreateProxyConstructor(Handle<mirror::Class> klass,ArtMethod * out)4309 void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4310 // Create constructor for Proxy that must initialize the method.
4311 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 18u);
4312 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
4313 2, image_pointer_size_);
4314 DCHECK_EQ(std::string(proxy_constructor->GetName()), "<init>");
4315 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4316 // constructor method.
4317 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
4318 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
4319 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4320 // code_ too)
4321 DCHECK(out != nullptr);
4322 out->CopyFrom(proxy_constructor, image_pointer_size_);
4323 // Make this constructor public and fix the class to be our Proxy version
4324 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4325 out->SetDeclaringClass(klass.Get());
4326 }
4327
CheckProxyConstructor(ArtMethod * constructor) const4328 void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
4329 CHECK(constructor->IsConstructor());
4330 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4331 CHECK_STREQ(np->GetName(), "<init>");
4332 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
4333 DCHECK(constructor->IsPublic());
4334 }
4335
CreateProxyMethod(Handle<mirror::Class> klass,ArtMethod * prototype,ArtMethod * out)4336 void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
4337 ArtMethod* out) {
4338 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4339 // prototype method
4340 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
4341 // Avoid dirtying the dex cache unless we need to.
4342 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
4343 prototype) {
4344 dex_cache->SetResolvedMethod(
4345 prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
4346 }
4347 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
4348 // as necessary
4349 DCHECK(out != nullptr);
4350 out->CopyFrom(prototype, image_pointer_size_);
4351
4352 // Set class to be the concrete proxy class.
4353 out->SetDeclaringClass(klass.Get());
4354 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4355 // preference to the invocation handler.
4356 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4357 // Make the method final.
4358 const uint32_t kAddFlags = kAccFinal;
4359 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4360
4361 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4362 // method they copy might (if it's a default method).
4363 out->SetCodeItemOffset(0);
4364
4365 // At runtime the method looks like a reference and argument saving method, clone the code
4366 // related parameters from this method.
4367 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4368 }
4369
CheckProxyMethod(ArtMethod * method,ArtMethod * prototype) const4370 void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
4371 // Basic sanity
4372 CHECK(!prototype->IsFinal());
4373 CHECK(method->IsFinal());
4374 CHECK(method->IsInvokable());
4375
4376 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4377 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4378 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
4379 CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_));
4380 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
4381 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
4382 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4383
4384 CHECK_STREQ(np->GetName(), prototype->GetName());
4385 CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
4386 // More complex sanity - via dex cache
4387 CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_),
4388 prototype->GetReturnType(true /* resolve */, image_pointer_size_));
4389 }
4390
CanWeInitializeClass(mirror::Class * klass,bool can_init_statics,bool can_init_parents)4391 bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4392 bool can_init_parents) {
4393 if (can_init_statics && can_init_parents) {
4394 return true;
4395 }
4396 if (!can_init_statics) {
4397 // Check if there's a class initializer.
4398 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4399 if (clinit != nullptr) {
4400 return false;
4401 }
4402 // Check if there are encoded static values needing initialization.
4403 if (klass->NumStaticFields() != 0) {
4404 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4405 DCHECK(dex_class_def != nullptr);
4406 if (dex_class_def->static_values_off_ != 0) {
4407 return false;
4408 }
4409 }
4410 // If we are a class we need to initialize all interfaces with default methods when we are
4411 // initialized. Check all of them.
4412 if (!klass->IsInterface()) {
4413 size_t num_interfaces = klass->GetIfTableCount();
4414 for (size_t i = 0; i < num_interfaces; i++) {
4415 mirror::Class* iface = klass->GetIfTable()->GetInterface(i);
4416 if (iface->HasDefaultMethods() &&
4417 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4418 return false;
4419 }
4420 }
4421 }
4422 }
4423 if (klass->IsInterface() || !klass->HasSuperClass()) {
4424 return true;
4425 }
4426 mirror::Class* super_class = klass->GetSuperClass();
4427 if (!can_init_parents && !super_class->IsInitialized()) {
4428 return false;
4429 }
4430 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
4431 }
4432
InitializeClass(Thread * self,Handle<mirror::Class> klass,bool can_init_statics,bool can_init_parents)4433 bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4434 bool can_init_statics, bool can_init_parents) {
4435 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4436
4437 // Are we already initialized and therefore done?
4438 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4439 // an initialized class will never change its state.
4440 if (klass->IsInitialized()) {
4441 return true;
4442 }
4443
4444 // Fast fail if initialization requires a full runtime. Not part of the JLS.
4445 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
4446 return false;
4447 }
4448
4449 self->AllowThreadSuspension();
4450 uint64_t t0;
4451 {
4452 ObjectLock<mirror::Class> lock(self, klass);
4453
4454 // Re-check under the lock in case another thread initialized ahead of us.
4455 if (klass->IsInitialized()) {
4456 return true;
4457 }
4458
4459 // Was the class already found to be erroneous? Done under the lock to match the JLS.
4460 if (klass->IsErroneous()) {
4461 ThrowEarlierClassFailure(klass.Get(), true);
4462 VlogClassInitializationFailure(klass);
4463 return false;
4464 }
4465
4466 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
4467
4468 if (!klass->IsVerified()) {
4469 VerifyClass(self, klass);
4470 if (!klass->IsVerified()) {
4471 // We failed to verify, expect either the klass to be erroneous or verification failed at
4472 // compile time.
4473 if (klass->IsErroneous()) {
4474 // The class is erroneous. This may be a verifier error, or another thread attempted
4475 // verification and/or initialization and failed. We can distinguish those cases by
4476 // whether an exception is already pending.
4477 if (self->IsExceptionPending()) {
4478 // Check that it's a VerifyError.
4479 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
4480 PrettyClass(self->GetException()->GetClass()));
4481 } else {
4482 // Check that another thread attempted initialization.
4483 DCHECK_NE(0, klass->GetClinitThreadId());
4484 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4485 // Need to rethrow the previous failure now.
4486 ThrowEarlierClassFailure(klass.Get(), true);
4487 }
4488 VlogClassInitializationFailure(klass);
4489 } else {
4490 CHECK(Runtime::Current()->IsAotCompiler());
4491 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
4492 }
4493 return false;
4494 } else {
4495 self->AssertNoPendingException();
4496 }
4497
4498 // A separate thread could have moved us all the way to initialized. A "simple" example
4499 // involves a subclass of the current class being initialized at the same time (which
4500 // will implicitly initialize the superclass, if scheduled that way). b/28254258
4501 DCHECK_NE(mirror::Class::kStatusError, klass->GetStatus());
4502 if (klass->IsInitialized()) {
4503 return true;
4504 }
4505 }
4506
4507 // If the class is kStatusInitializing, either this thread is
4508 // initializing higher up the stack or another thread has beat us
4509 // to initializing and we need to wait. Either way, this
4510 // invocation of InitializeClass will not be responsible for
4511 // running <clinit> and will return.
4512 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4513 // Could have got an exception during verification.
4514 if (self->IsExceptionPending()) {
4515 VlogClassInitializationFailure(klass);
4516 return false;
4517 }
4518 // We caught somebody else in the act; was it us?
4519 if (klass->GetClinitThreadId() == self->GetTid()) {
4520 // Yes. That's fine. Return so we can continue initializing.
4521 return true;
4522 }
4523 // No. That's fine. Wait for another thread to finish initializing.
4524 return WaitForInitializeClass(klass, self, lock);
4525 }
4526
4527 if (!ValidateSuperClassDescriptors(klass)) {
4528 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4529 return false;
4530 }
4531 self->AllowThreadSuspension();
4532
4533 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get())
4534 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
4535
4536 // From here out other threads may observe that we're initializing and so changes of state
4537 // require the a notification.
4538 klass->SetClinitThreadId(self->GetTid());
4539 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
4540
4541 t0 = NanoTime();
4542 }
4543
4544 // Initialize super classes, must be done while initializing for the JLS.
4545 if (!klass->IsInterface() && klass->HasSuperClass()) {
4546 mirror::Class* super_class = klass->GetSuperClass();
4547 if (!super_class->IsInitialized()) {
4548 CHECK(!super_class->IsInterface());
4549 CHECK(can_init_parents);
4550 StackHandleScope<1> hs(self);
4551 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
4552 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
4553 if (!super_initialized) {
4554 // The super class was verified ahead of entering initializing, we should only be here if
4555 // the super class became erroneous due to initialization.
4556 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
4557 << "Super class initialization failed for "
4558 << PrettyDescriptor(handle_scope_super.Get())
4559 << " that has unexpected status " << handle_scope_super->GetStatus()
4560 << "\nPending exception:\n"
4561 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
4562 ObjectLock<mirror::Class> lock(self, klass);
4563 // Initialization failed because the super-class is erroneous.
4564 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4565 return false;
4566 }
4567 }
4568 }
4569
4570 if (!klass->IsInterface()) {
4571 // Initialize interfaces with default methods for the JLS.
4572 size_t num_direct_interfaces = klass->NumDirectInterfaces();
4573 // Only setup the (expensive) handle scope if we actually need to.
4574 if (UNLIKELY(num_direct_interfaces > 0)) {
4575 StackHandleScope<1> hs_iface(self);
4576 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4577 for (size_t i = 0; i < num_direct_interfaces; i++) {
4578 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i));
4579 CHECK(handle_scope_iface.Get() != nullptr);
4580 CHECK(handle_scope_iface->IsInterface());
4581 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4582 // We have already done this for this interface. Skip it.
4583 continue;
4584 }
4585 // We cannot just call initialize class directly because we need to ensure that ALL
4586 // interfaces with default methods are initialized. Non-default interface initialization
4587 // will not affect other non-default super-interfaces.
4588 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4589 handle_scope_iface,
4590 can_init_statics,
4591 can_init_parents);
4592 if (!iface_initialized) {
4593 ObjectLock<mirror::Class> lock(self, klass);
4594 // Initialization failed because one of our interfaces with default methods is erroneous.
4595 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4596 return false;
4597 }
4598 }
4599 }
4600 }
4601
4602 const size_t num_static_fields = klass->NumStaticFields();
4603 if (num_static_fields > 0) {
4604 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4605 CHECK(dex_class_def != nullptr);
4606 const DexFile& dex_file = klass->GetDexFile();
4607 StackHandleScope<3> hs(self);
4608 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
4609 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4610
4611 // Eagerly fill in static fields so that the we don't have to do as many expensive
4612 // Class::FindStaticField in ResolveField.
4613 for (size_t i = 0; i < num_static_fields; ++i) {
4614 ArtField* field = klass->GetStaticField(i);
4615 const uint32_t field_idx = field->GetDexFieldIndex();
4616 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
4617 if (resolved_field == nullptr) {
4618 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
4619 } else {
4620 DCHECK_EQ(field, resolved_field);
4621 }
4622 }
4623
4624 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4625 this, *dex_class_def);
4626 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
4627 ClassDataItemIterator field_it(dex_file, class_data);
4628 if (value_it.HasNext()) {
4629 DCHECK(field_it.HasNextStaticField());
4630 CHECK(can_init_statics);
4631 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
4632 ArtField* field = ResolveField(
4633 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
4634 if (Runtime::Current()->IsActiveTransaction()) {
4635 value_it.ReadValueToField<true>(field);
4636 } else {
4637 value_it.ReadValueToField<false>(field);
4638 }
4639 if (self->IsExceptionPending()) {
4640 break;
4641 }
4642 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
4643 }
4644 }
4645 }
4646
4647
4648 if (!self->IsExceptionPending()) {
4649 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4650 if (clinit != nullptr) {
4651 CHECK(can_init_statics);
4652 JValue result;
4653 clinit->Invoke(self, nullptr, 0, &result, "V");
4654 }
4655 }
4656 self->AllowThreadSuspension();
4657 uint64_t t1 = NanoTime();
4658
4659 bool success = true;
4660 {
4661 ObjectLock<mirror::Class> lock(self, klass);
4662
4663 if (self->IsExceptionPending()) {
4664 WrapExceptionInInitializer(klass);
4665 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4666 success = false;
4667 } else if (Runtime::Current()->IsTransactionAborted()) {
4668 // The exception thrown when the transaction aborted has been caught and cleared
4669 // so we need to throw it again now.
4670 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4671 << " without exception while transaction was aborted: re-throw it now.";
4672 Runtime::Current()->ThrowTransactionAbortError(self);
4673 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4674 success = false;
4675 } else {
4676 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4677 RuntimeStats* thread_stats = self->GetStats();
4678 ++global_stats->class_init_count;
4679 ++thread_stats->class_init_count;
4680 global_stats->class_init_time_ns += (t1 - t0);
4681 thread_stats->class_init_time_ns += (t1 - t0);
4682 // Set the class as initialized except if failed to initialize static fields.
4683 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
4684 if (VLOG_IS_ON(class_linker)) {
4685 std::string temp;
4686 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
4687 klass->GetLocation();
4688 }
4689 // Opportunistically set static method trampolines to their destination.
4690 FixupStaticTrampolines(klass.Get());
4691 }
4692 }
4693 return success;
4694 }
4695
4696 // We recursively run down the tree of interfaces. We need to do this in the order they are declared
4697 // and perform the initialization only on those interfaces that contain default methods.
InitializeDefaultInterfaceRecursive(Thread * self,Handle<mirror::Class> iface,bool can_init_statics,bool can_init_parents)4698 bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4699 Handle<mirror::Class> iface,
4700 bool can_init_statics,
4701 bool can_init_parents) {
4702 CHECK(iface->IsInterface());
4703 size_t num_direct_ifaces = iface->NumDirectInterfaces();
4704 // Only create the (expensive) handle scope if we need it.
4705 if (UNLIKELY(num_direct_ifaces > 0)) {
4706 StackHandleScope<1> hs(self);
4707 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4708 // First we initialize all of iface's super-interfaces recursively.
4709 for (size_t i = 0; i < num_direct_ifaces; i++) {
4710 mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i);
4711 if (!super_iface->HasBeenRecursivelyInitialized()) {
4712 // Recursive step
4713 handle_super_iface.Assign(super_iface);
4714 if (!InitializeDefaultInterfaceRecursive(self,
4715 handle_super_iface,
4716 can_init_statics,
4717 can_init_parents)) {
4718 return false;
4719 }
4720 }
4721 }
4722 }
4723
4724 bool result = true;
4725 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4726 // initialize if we don't have default methods.
4727 if (iface->HasDefaultMethods()) {
4728 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4729 }
4730
4731 // Mark that this interface has undergone recursive default interface initialization so we know we
4732 // can skip it on any later class initializations. We do this even if we are not a default
4733 // interface since we can still avoid the traversal. This is purely a performance optimization.
4734 if (result) {
4735 // TODO This should be done in a better way
4736 ObjectLock<mirror::Class> lock(self, iface);
4737 iface->SetRecursivelyInitialized();
4738 }
4739 return result;
4740 }
4741
WaitForInitializeClass(Handle<mirror::Class> klass,Thread * self,ObjectLock<mirror::Class> & lock)4742 bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4743 Thread* self,
4744 ObjectLock<mirror::Class>& lock)
4745 SHARED_REQUIRES(Locks::mutator_lock_) {
4746 while (true) {
4747 self->AssertNoPendingException();
4748 CHECK(!klass->IsInitialized());
4749 lock.WaitIgnoringInterrupts();
4750
4751 // When we wake up, repeat the test for init-in-progress. If
4752 // there's an exception pending (only possible if
4753 // we were not using WaitIgnoringInterrupts), bail out.
4754 if (self->IsExceptionPending()) {
4755 WrapExceptionInInitializer(klass);
4756 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4757 return false;
4758 }
4759 // Spurious wakeup? Go back to waiting.
4760 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4761 continue;
4762 }
4763 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4764 Runtime::Current()->IsAotCompiler()) {
4765 // Compile time initialization failed.
4766 return false;
4767 }
4768 if (klass->IsErroneous()) {
4769 // The caller wants an exception, but it was thrown in a
4770 // different thread. Synthesize one here.
4771 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
4772 PrettyDescriptor(klass.Get()).c_str());
4773 VlogClassInitializationFailure(klass);
4774 return false;
4775 }
4776 if (klass->IsInitialized()) {
4777 return true;
4778 }
4779 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
4780 << klass->GetStatus();
4781 }
4782 UNREACHABLE();
4783 }
4784
ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,ArtMethod * m)4785 static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4786 Handle<mirror::Class> super_klass,
4787 ArtMethod* method,
4788 ArtMethod* m)
4789 SHARED_REQUIRES(Locks::mutator_lock_) {
4790 DCHECK(Thread::Current()->IsExceptionPending());
4791 DCHECK(!m->IsProxyMethod());
4792 const DexFile* dex_file = m->GetDexFile();
4793 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4794 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
4795 uint16_t return_type_idx = proto_id.return_type_idx_;
4796 std::string return_type = PrettyType(return_type_idx, *dex_file);
4797 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4798 ThrowWrappedLinkageError(klass.Get(),
4799 "While checking class %s method %s signature against %s %s: "
4800 "Failed to resolve return type %s with %s",
4801 PrettyDescriptor(klass.Get()).c_str(),
4802 PrettyMethod(method).c_str(),
4803 super_klass->IsInterface() ? "interface" : "superclass",
4804 PrettyDescriptor(super_klass.Get()).c_str(),
4805 return_type.c_str(), class_loader.c_str());
4806 }
4807
ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,ArtMethod * m,uint32_t index,uint32_t arg_type_idx)4808 static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4809 Handle<mirror::Class> super_klass,
4810 ArtMethod* method,
4811 ArtMethod* m,
4812 uint32_t index,
4813 uint32_t arg_type_idx)
4814 SHARED_REQUIRES(Locks::mutator_lock_) {
4815 DCHECK(Thread::Current()->IsExceptionPending());
4816 DCHECK(!m->IsProxyMethod());
4817 const DexFile* dex_file = m->GetDexFile();
4818 std::string arg_type = PrettyType(arg_type_idx, *dex_file);
4819 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4820 ThrowWrappedLinkageError(klass.Get(),
4821 "While checking class %s method %s signature against %s %s: "
4822 "Failed to resolve arg %u type %s with %s",
4823 PrettyDescriptor(klass.Get()).c_str(),
4824 PrettyMethod(method).c_str(),
4825 super_klass->IsInterface() ? "interface" : "superclass",
4826 PrettyDescriptor(super_klass.Get()).c_str(),
4827 index, arg_type.c_str(), class_loader.c_str());
4828 }
4829
ThrowSignatureMismatch(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,const std::string & error_msg)4830 static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
4831 Handle<mirror::Class> super_klass,
4832 ArtMethod* method,
4833 const std::string& error_msg)
4834 SHARED_REQUIRES(Locks::mutator_lock_) {
4835 ThrowLinkageError(klass.Get(),
4836 "Class %s method %s resolves differently in %s %s: %s",
4837 PrettyDescriptor(klass.Get()).c_str(),
4838 PrettyMethod(method).c_str(),
4839 super_klass->IsInterface() ? "interface" : "superclass",
4840 PrettyDescriptor(super_klass.Get()).c_str(),
4841 error_msg.c_str());
4842 }
4843
HasSameSignatureWithDifferentClassLoaders(Thread * self,size_t pointer_size,Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method1,ArtMethod * method2)4844 static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4845 size_t pointer_size,
4846 Handle<mirror::Class> klass,
4847 Handle<mirror::Class> super_klass,
4848 ArtMethod* method1,
4849 ArtMethod* method2)
4850 SHARED_REQUIRES(Locks::mutator_lock_) {
4851 {
4852 StackHandleScope<1> hs(self);
4853 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */,
4854 pointer_size)));
4855 if (UNLIKELY(return_type.Get() == nullptr)) {
4856 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
4857 return false;
4858 }
4859 mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */,
4860 pointer_size);
4861 if (UNLIKELY(other_return_type == nullptr)) {
4862 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
4863 return false;
4864 }
4865 if (UNLIKELY(other_return_type != return_type.Get())) {
4866 ThrowSignatureMismatch(klass, super_klass, method1,
4867 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4868 PrettyClassAndClassLoader(return_type.Get()).c_str(),
4869 return_type.Get(),
4870 PrettyClassAndClassLoader(other_return_type).c_str(),
4871 other_return_type));
4872 return false;
4873 }
4874 }
4875 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4876 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4877 if (types1 == nullptr) {
4878 if (types2 != nullptr && types2->Size() != 0) {
4879 ThrowSignatureMismatch(klass, super_klass, method1,
4880 StringPrintf("Type list mismatch with %s",
4881 PrettyMethod(method2, true).c_str()));
4882 return false;
4883 }
4884 return true;
4885 } else if (UNLIKELY(types2 == nullptr)) {
4886 if (types1->Size() != 0) {
4887 ThrowSignatureMismatch(klass, super_klass, method1,
4888 StringPrintf("Type list mismatch with %s",
4889 PrettyMethod(method2, true).c_str()));
4890 return false;
4891 }
4892 return true;
4893 }
4894 uint32_t num_types = types1->Size();
4895 if (UNLIKELY(num_types != types2->Size())) {
4896 ThrowSignatureMismatch(klass, super_klass, method1,
4897 StringPrintf("Type list mismatch with %s",
4898 PrettyMethod(method2, true).c_str()));
4899 return false;
4900 }
4901 for (uint32_t i = 0; i < num_types; ++i) {
4902 StackHandleScope<1> hs(self);
4903 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_;
4904 Handle<mirror::Class> param_type(hs.NewHandle(
4905 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size)));
4906 if (UNLIKELY(param_type.Get() == nullptr)) {
4907 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
4908 method1, i, param_type_idx);
4909 return false;
4910 }
4911 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_;
4912 mirror::Class* other_param_type =
4913 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size);
4914 if (UNLIKELY(other_param_type == nullptr)) {
4915 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
4916 method2, i, other_param_type_idx);
4917 return false;
4918 }
4919 if (UNLIKELY(param_type.Get() != other_param_type)) {
4920 ThrowSignatureMismatch(klass, super_klass, method1,
4921 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4922 i,
4923 PrettyClassAndClassLoader(param_type.Get()).c_str(),
4924 param_type.Get(),
4925 PrettyClassAndClassLoader(other_param_type).c_str(),
4926 other_param_type));
4927 return false;
4928 }
4929 }
4930 return true;
4931 }
4932
4933
ValidateSuperClassDescriptors(Handle<mirror::Class> klass)4934 bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
4935 if (klass->IsInterface()) {
4936 return true;
4937 }
4938 // Begin with the methods local to the superclass.
4939 Thread* self = Thread::Current();
4940 StackHandleScope<1> hs(self);
4941 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
4942 if (klass->HasSuperClass() &&
4943 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
4944 super_klass.Assign(klass->GetSuperClass());
4945 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4946 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
4947 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
4948 if (m != super_m) {
4949 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4950 klass, super_klass,
4951 m, super_m))) {
4952 self->AssertPendingException();
4953 return false;
4954 }
4955 }
4956 }
4957 }
4958 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
4959 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
4960 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
4961 uint32_t num_methods = super_klass->NumVirtualMethods();
4962 for (uint32_t j = 0; j < num_methods; ++j) {
4963 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
4964 j, image_pointer_size_);
4965 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
4966 if (m != super_m) {
4967 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4968 klass, super_klass,
4969 m, super_m))) {
4970 self->AssertPendingException();
4971 return false;
4972 }
4973 }
4974 }
4975 }
4976 }
4977 return true;
4978 }
4979
EnsureInitialized(Thread * self,Handle<mirror::Class> c,bool can_init_fields,bool can_init_parents)4980 bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4981 bool can_init_parents) {
4982 DCHECK(c.Get() != nullptr);
4983 if (c->IsInitialized()) {
4984 EnsureSkipAccessChecksMethods(c);
4985 return true;
4986 }
4987 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
4988 if (!success) {
4989 if (can_init_fields && can_init_parents) {
4990 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4991 }
4992 } else {
4993 self->AssertNoPendingException();
4994 }
4995 return success;
4996 }
4997
FixupTemporaryDeclaringClass(mirror::Class * temp_class,mirror::Class * new_class)4998 void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
4999 mirror::Class* new_class) {
5000 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
5001 for (ArtField& field : new_class->GetIFields()) {
5002 if (field.GetDeclaringClass() == temp_class) {
5003 field.SetDeclaringClass(new_class);
5004 }
5005 }
5006
5007 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
5008 for (ArtField& field : new_class->GetSFields()) {
5009 if (field.GetDeclaringClass() == temp_class) {
5010 field.SetDeclaringClass(new_class);
5011 }
5012 }
5013
5014 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
5015 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
5016 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
5017 if (method.GetDeclaringClass() == temp_class) {
5018 method.SetDeclaringClass(new_class);
5019 }
5020 }
5021
5022 // Make sure the remembered set and mod-union tables know that we updated some of the native
5023 // roots.
5024 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
5025 }
5026
RegisterClassLoader(mirror::ClassLoader * class_loader)5027 void ClassLinker::RegisterClassLoader(mirror::ClassLoader* class_loader) {
5028 CHECK(class_loader->GetAllocator() == nullptr);
5029 CHECK(class_loader->GetClassTable() == nullptr);
5030 Thread* const self = Thread::Current();
5031 ClassLoaderData data;
5032 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
5033 // Create and set the class table.
5034 data.class_table = new ClassTable;
5035 class_loader->SetClassTable(data.class_table);
5036 // Create and set the linear allocator.
5037 data.allocator = Runtime::Current()->CreateLinearAlloc();
5038 class_loader->SetAllocator(data.allocator);
5039 // Add to the list so that we know to free the data later.
5040 class_loaders_.push_back(data);
5041 }
5042
InsertClassTableForClassLoader(mirror::ClassLoader * class_loader)5043 ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) {
5044 if (class_loader == nullptr) {
5045 return &boot_class_table_;
5046 }
5047 ClassTable* class_table = class_loader->GetClassTable();
5048 if (class_table == nullptr) {
5049 RegisterClassLoader(class_loader);
5050 class_table = class_loader->GetClassTable();
5051 DCHECK(class_table != nullptr);
5052 }
5053 return class_table;
5054 }
5055
ClassTableForClassLoader(mirror::ClassLoader * class_loader)5056 ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) {
5057 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
5058 }
5059
FindSuperImt(mirror::Class * klass,size_t pointer_size)5060 static ImTable* FindSuperImt(mirror::Class* klass, size_t pointer_size)
5061 SHARED_REQUIRES(Locks::mutator_lock_) {
5062 while (klass->HasSuperClass()) {
5063 klass = klass->GetSuperClass();
5064 if (klass->ShouldHaveImt()) {
5065 return klass->GetImt(pointer_size);
5066 }
5067 }
5068 return nullptr;
5069 }
5070
LinkClass(Thread * self,const char * descriptor,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces,MutableHandle<mirror::Class> * h_new_class_out)5071 bool ClassLinker::LinkClass(Thread* self,
5072 const char* descriptor,
5073 Handle<mirror::Class> klass,
5074 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5075 MutableHandle<mirror::Class>* h_new_class_out) {
5076 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
5077
5078 if (!LinkSuperClass(klass)) {
5079 return false;
5080 }
5081 ArtMethod* imt_data[ImTable::kSize];
5082 // If there are any new conflicts compared to super class.
5083 bool new_conflict = false;
5084 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
5085 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
5086 return false;
5087 }
5088 if (!LinkInstanceFields(self, klass)) {
5089 return false;
5090 }
5091 size_t class_size;
5092 if (!LinkStaticFields(self, klass, &class_size)) {
5093 return false;
5094 }
5095 CreateReferenceInstanceOffsets(klass);
5096 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
5097
5098 ImTable* imt = nullptr;
5099 if (klass->ShouldHaveImt()) {
5100 // If there are any new conflicts compared to the super class we can not make a copy. There
5101 // can be cases where both will have a conflict method at the same slot without having the same
5102 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5103 // will possibly create a table that is incorrect for either of the classes.
5104 // Same IMT with new_conflict does not happen very often.
5105 if (!new_conflict) {
5106 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5107 if (super_imt != nullptr) {
5108 bool imt_equals = true;
5109 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5110 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5111 }
5112 if (imt_equals) {
5113 imt = super_imt;
5114 }
5115 }
5116 }
5117 if (imt == nullptr) {
5118 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5119 imt = reinterpret_cast<ImTable*>(
5120 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5121 if (imt == nullptr) {
5122 return false;
5123 }
5124 imt->Populate(imt_data, image_pointer_size_);
5125 }
5126 }
5127
5128 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5129 // We don't need to retire this class as it has no embedded tables or it was created the
5130 // correct size during class linker initialization.
5131 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
5132
5133 if (klass->ShouldHaveEmbeddedVTable()) {
5134 klass->PopulateEmbeddedVTable(image_pointer_size_);
5135 }
5136 if (klass->ShouldHaveImt()) {
5137 klass->SetImt(imt, image_pointer_size_);
5138 }
5139 // This will notify waiters on klass that saw the not yet resolved
5140 // class in the class_table_ during EnsureResolved.
5141 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
5142 h_new_class_out->Assign(klass.Get());
5143 } else {
5144 CHECK(!klass->IsResolved());
5145 // Retire the temporary class and create the correctly sized resolved class.
5146 StackHandleScope<1> hs(self);
5147 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
5148 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5149 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5150 // may not see any references to the target space and clean the card for a class if another
5151 // class had the same array pointer.
5152 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
5153 klass->SetSFieldsPtrUnchecked(nullptr);
5154 klass->SetIFieldsPtrUnchecked(nullptr);
5155 if (UNLIKELY(h_new_class.Get() == nullptr)) {
5156 self->AssertPendingOOMException();
5157 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
5158 return false;
5159 }
5160
5161 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5162 ObjectLock<mirror::Class> lock(self, h_new_class);
5163 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
5164
5165 {
5166 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
5167 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader();
5168 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
5169 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(),
5170 ComputeModifiedUtf8Hash(descriptor));
5171 if (class_loader != nullptr) {
5172 // We updated the class in the class table, perform the write barrier so that the GC knows
5173 // about the change.
5174 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5175 }
5176 CHECK_EQ(existing, klass.Get());
5177 if (kIsDebugBuild && class_loader == nullptr && dex_cache_boot_image_class_lookup_required_) {
5178 // Check a class loaded with the system class loader matches one in the image if the class
5179 // is in the image.
5180 mirror::Class* const image_class = LookupClassFromBootImage(descriptor);
5181 if (image_class != nullptr) {
5182 CHECK_EQ(klass.Get(), existing) << descriptor;
5183 }
5184 }
5185 if (log_new_class_table_roots_) {
5186 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5187 }
5188 }
5189
5190 // This will notify waiters on temp class that saw the not yet resolved class in the
5191 // class_table_ during EnsureResolved.
5192 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
5193
5194 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
5195 // This will notify waiters on new_class that saw the not yet resolved
5196 // class in the class_table_ during EnsureResolved.
5197 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5198 // Return the new class.
5199 h_new_class_out->Assign(h_new_class.Get());
5200 }
5201 return true;
5202 }
5203
CountMethodsAndFields(ClassDataItemIterator & dex_data,size_t * virtual_methods,size_t * direct_methods,size_t * static_fields,size_t * instance_fields)5204 static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
5205 size_t* virtual_methods,
5206 size_t* direct_methods,
5207 size_t* static_fields,
5208 size_t* instance_fields) {
5209 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
5210
5211 while (dex_data.HasNextStaticField()) {
5212 dex_data.Next();
5213 (*static_fields)++;
5214 }
5215 while (dex_data.HasNextInstanceField()) {
5216 dex_data.Next();
5217 (*instance_fields)++;
5218 }
5219 while (dex_data.HasNextDirectMethod()) {
5220 (*direct_methods)++;
5221 dex_data.Next();
5222 }
5223 while (dex_data.HasNextVirtualMethod()) {
5224 (*virtual_methods)++;
5225 dex_data.Next();
5226 }
5227 DCHECK(!dex_data.HasNext());
5228 }
5229
DumpClass(std::ostream & os,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,const char * suffix)5230 static void DumpClass(std::ostream& os,
5231 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
5232 const char* suffix) {
5233 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
5234 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
5235 os << " Static fields:\n";
5236 while (dex_data.HasNextStaticField()) {
5237 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5238 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5239 dex_data.Next();
5240 }
5241 os << " Instance fields:\n";
5242 while (dex_data.HasNextInstanceField()) {
5243 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5244 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5245 dex_data.Next();
5246 }
5247 os << " Direct methods:\n";
5248 while (dex_data.HasNextDirectMethod()) {
5249 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5250 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5251 dex_data.Next();
5252 }
5253 os << " Virtual methods:\n";
5254 while (dex_data.HasNextVirtualMethod()) {
5255 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5256 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5257 dex_data.Next();
5258 }
5259 }
5260
DumpClasses(const DexFile & dex_file1,const DexFile::ClassDef & dex_class_def1,const DexFile & dex_file2,const DexFile::ClassDef & dex_class_def2)5261 static std::string DumpClasses(const DexFile& dex_file1,
5262 const DexFile::ClassDef& dex_class_def1,
5263 const DexFile& dex_file2,
5264 const DexFile::ClassDef& dex_class_def2) {
5265 std::ostringstream os;
5266 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
5267 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
5268 return os.str();
5269 }
5270
5271
5272 // Very simple structural check on whether the classes match. Only compares the number of
5273 // methods and fields.
SimpleStructuralCheck(const DexFile & dex_file1,const DexFile::ClassDef & dex_class_def1,const DexFile & dex_file2,const DexFile::ClassDef & dex_class_def2,std::string * error_msg)5274 static bool SimpleStructuralCheck(const DexFile& dex_file1,
5275 const DexFile::ClassDef& dex_class_def1,
5276 const DexFile& dex_file2,
5277 const DexFile::ClassDef& dex_class_def2,
5278 std::string* error_msg) {
5279 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
5280 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
5281
5282 // Counters for current dex file.
5283 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
5284 CountMethodsAndFields(dex_data1,
5285 &dex_virtual_methods1,
5286 &dex_direct_methods1,
5287 &dex_static_fields1,
5288 &dex_instance_fields1);
5289 // Counters for compile-time dex file.
5290 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
5291 CountMethodsAndFields(dex_data2,
5292 &dex_virtual_methods2,
5293 &dex_direct_methods2,
5294 &dex_static_fields2,
5295 &dex_instance_fields2);
5296
5297 if (dex_virtual_methods1 != dex_virtual_methods2) {
5298 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5299 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
5300 dex_virtual_methods1,
5301 dex_virtual_methods2,
5302 class_dump.c_str());
5303 return false;
5304 }
5305 if (dex_direct_methods1 != dex_direct_methods2) {
5306 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5307 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
5308 dex_direct_methods1,
5309 dex_direct_methods2,
5310 class_dump.c_str());
5311 return false;
5312 }
5313 if (dex_static_fields1 != dex_static_fields2) {
5314 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5315 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
5316 dex_static_fields1,
5317 dex_static_fields2,
5318 class_dump.c_str());
5319 return false;
5320 }
5321 if (dex_instance_fields1 != dex_instance_fields2) {
5322 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5323 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
5324 dex_instance_fields1,
5325 dex_instance_fields2,
5326 class_dump.c_str());
5327 return false;
5328 }
5329
5330 return true;
5331 }
5332
5333 // Checks whether a the super-class changed from what we had at compile-time. This would
5334 // invalidate quickening.
CheckSuperClassChange(Handle<mirror::Class> klass,const DexFile & dex_file,const DexFile::ClassDef & class_def,mirror::Class * super_class)5335 static bool CheckSuperClassChange(Handle<mirror::Class> klass,
5336 const DexFile& dex_file,
5337 const DexFile::ClassDef& class_def,
5338 mirror::Class* super_class)
5339 SHARED_REQUIRES(Locks::mutator_lock_) {
5340 // Check for unexpected changes in the superclass.
5341 // Quick check 1) is the super_class class-loader the boot class loader? This always has
5342 // precedence.
5343 if (super_class->GetClassLoader() != nullptr &&
5344 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
5345 // which is implied by different dex cache.
5346 klass->GetDexCache() != super_class->GetDexCache()) {
5347 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
5348 // definition for the super-class, and (b) the files are in separate oat files. The oat files
5349 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
5350 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
5351 const OatFile* class_oat_file = nullptr;
5352 if (class_oat_dex_file != nullptr) {
5353 class_oat_file = class_oat_dex_file->GetOatFile();
5354 }
5355
5356 if (class_oat_file != nullptr) {
5357 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
5358 const OatFile* loaded_super_oat_file = nullptr;
5359 if (loaded_super_oat_dex_file != nullptr) {
5360 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
5361 }
5362
5363 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
5364 // Now check (a).
5365 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
5366 if (super_class_def != nullptr) {
5367 // Uh-oh, we found something. Do our check.
5368 std::string error_msg;
5369 if (!SimpleStructuralCheck(dex_file, *super_class_def,
5370 super_class->GetDexFile(), *super_class->GetClassDef(),
5371 &error_msg)) {
5372 // Print a warning to the log. This exception might be caught, e.g., as common in test
5373 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
5374 // only save the type of the exception.
5375 LOG(WARNING) << "Incompatible structural change detected: " <<
5376 StringPrintf(
5377 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5378 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5379 class_oat_file->GetLocation().c_str(),
5380 loaded_super_oat_file->GetLocation().c_str(),
5381 error_msg.c_str());
5382 ThrowIncompatibleClassChangeError(klass.Get(),
5383 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5384 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5385 class_oat_file->GetLocation().c_str(),
5386 loaded_super_oat_file->GetLocation().c_str(),
5387 error_msg.c_str());
5388 return false;
5389 }
5390 }
5391 }
5392 }
5393 }
5394 return true;
5395 }
5396
LoadSuperAndInterfaces(Handle<mirror::Class> klass,const DexFile & dex_file)5397 bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
5398 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
5399 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
5400 uint16_t super_class_idx = class_def.superclass_idx_;
5401 if (super_class_idx != DexFile::kDexNoIndex16) {
5402 // Check that a class does not inherit from itself directly.
5403 //
5404 // TODO: This is a cheap check to detect the straightforward case
5405 // of a class extending itself (b/28685551), but we should do a
5406 // proper cycle detection on loaded classes, to detect all cases
5407 // of class circularity errors (b/28830038).
5408 if (super_class_idx == class_def.class_idx_) {
5409 ThrowClassCircularityError(klass.Get(),
5410 "Class %s extends itself",
5411 PrettyDescriptor(klass.Get()).c_str());
5412 return false;
5413 }
5414
5415 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
5416 if (super_class == nullptr) {
5417 DCHECK(Thread::Current()->IsExceptionPending());
5418 return false;
5419 }
5420 // Verify
5421 if (!klass->CanAccess(super_class)) {
5422 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
5423 PrettyDescriptor(super_class).c_str(),
5424 PrettyDescriptor(klass.Get()).c_str());
5425 return false;
5426 }
5427 CHECK(super_class->IsResolved());
5428 klass->SetSuperClass(super_class);
5429
5430 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
5431 DCHECK(Thread::Current()->IsExceptionPending());
5432 return false;
5433 }
5434 }
5435 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
5436 if (interfaces != nullptr) {
5437 for (size_t i = 0; i < interfaces->Size(); i++) {
5438 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
5439 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
5440 if (interface == nullptr) {
5441 DCHECK(Thread::Current()->IsExceptionPending());
5442 return false;
5443 }
5444 // Verify
5445 if (!klass->CanAccess(interface)) {
5446 // TODO: the RI seemed to ignore this in my testing.
5447 ThrowIllegalAccessError(klass.Get(),
5448 "Interface %s implemented by class %s is inaccessible",
5449 PrettyDescriptor(interface).c_str(),
5450 PrettyDescriptor(klass.Get()).c_str());
5451 return false;
5452 }
5453 }
5454 }
5455 // Mark the class as loaded.
5456 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
5457 return true;
5458 }
5459
LinkSuperClass(Handle<mirror::Class> klass)5460 bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
5461 CHECK(!klass->IsPrimitive());
5462 mirror::Class* super = klass->GetSuperClass();
5463 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
5464 if (super != nullptr) {
5465 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
5466 return false;
5467 }
5468 return true;
5469 }
5470 if (super == nullptr) {
5471 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
5472 PrettyDescriptor(klass.Get()).c_str());
5473 return false;
5474 }
5475 // Verify
5476 if (super->IsFinal() || super->IsInterface()) {
5477 ThrowIncompatibleClassChangeError(klass.Get(),
5478 "Superclass %s of %s is %s",
5479 PrettyDescriptor(super).c_str(),
5480 PrettyDescriptor(klass.Get()).c_str(),
5481 super->IsFinal() ? "declared final" : "an interface");
5482 return false;
5483 }
5484 if (!klass->CanAccess(super)) {
5485 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
5486 PrettyDescriptor(super).c_str(),
5487 PrettyDescriptor(klass.Get()).c_str());
5488 return false;
5489 }
5490
5491 // Inherit kAccClassIsFinalizable from the superclass in case this
5492 // class doesn't override finalize.
5493 if (super->IsFinalizable()) {
5494 klass->SetFinalizable();
5495 }
5496
5497 // Inherit class loader flag form super class.
5498 if (super->IsClassLoaderClass()) {
5499 klass->SetClassLoaderClass();
5500 }
5501
5502 // Inherit reference flags (if any) from the superclass.
5503 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
5504 if (reference_flags != 0) {
5505 CHECK_EQ(klass->GetClassFlags(), 0u);
5506 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
5507 }
5508 // Disallow custom direct subclasses of java.lang.ref.Reference.
5509 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
5510 ThrowLinkageError(klass.Get(),
5511 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
5512 PrettyDescriptor(klass.Get()).c_str());
5513 return false;
5514 }
5515
5516 if (kIsDebugBuild) {
5517 // Ensure super classes are fully resolved prior to resolving fields..
5518 while (super != nullptr) {
5519 CHECK(super->IsResolved());
5520 super = super->GetSuperClass();
5521 }
5522 }
5523 return true;
5524 }
5525
5526 // Populate the class vtable and itable. Compute return type indices.
LinkMethods(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces,bool * out_new_conflict,ArtMethod ** out_imt)5527 bool ClassLinker::LinkMethods(Thread* self,
5528 Handle<mirror::Class> klass,
5529 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5530 bool* out_new_conflict,
5531 ArtMethod** out_imt) {
5532 self->AllowThreadSuspension();
5533 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5534 // need to have default methods be in the virtuals array of each class but we don't set that up
5535 // until LinkInterfaceMethods.
5536 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
5537 // Link virtual methods then interface methods.
5538 // We set up the interface lookup table first because we need it to determine if we need to update
5539 // any vtable entries with new default method implementations.
5540 return SetupInterfaceLookupTable(self, klass, interfaces)
5541 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
5542 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
5543 }
5544
5545 // Comparator for name and signature of a method, used in finding overriding methods. Implementation
5546 // avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5547 // caches in the implementation below.
5548 class MethodNameAndSignatureComparator FINAL : public ValueObject {
5549 public:
5550 explicit MethodNameAndSignatureComparator(ArtMethod* method)
SHARED_REQUIRES(Locks::mutator_lock_)5551 SHARED_REQUIRES(Locks::mutator_lock_) :
5552 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5553 name_(nullptr), name_len_(0) {
5554 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
5555 }
5556
GetName()5557 const char* GetName() {
5558 if (name_ == nullptr) {
5559 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5560 }
5561 return name_;
5562 }
5563
HasSameNameAndSignature(ArtMethod * other)5564 bool HasSameNameAndSignature(ArtMethod* other)
5565 SHARED_REQUIRES(Locks::mutator_lock_) {
5566 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
5567 const DexFile* other_dex_file = other->GetDexFile();
5568 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5569 if (dex_file_ == other_dex_file) {
5570 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5571 }
5572 GetName(); // Only used to make sure its calculated.
5573 uint32_t other_name_len;
5574 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5575 &other_name_len);
5576 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5577 return false;
5578 }
5579 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5580 }
5581
5582 private:
5583 // Dex file for the method to compare against.
5584 const DexFile* const dex_file_;
5585 // MethodId for the method to compare against.
5586 const DexFile::MethodId* const mid_;
5587 // Lazily computed name from the dex file's strings.
5588 const char* name_;
5589 // Lazily computed name length.
5590 uint32_t name_len_;
5591 };
5592
5593 class LinkVirtualHashTable {
5594 public:
LinkVirtualHashTable(Handle<mirror::Class> klass,size_t hash_size,uint32_t * hash_table,size_t image_pointer_size)5595 LinkVirtualHashTable(Handle<mirror::Class> klass,
5596 size_t hash_size,
5597 uint32_t* hash_table,
5598 size_t image_pointer_size)
5599 : klass_(klass),
5600 hash_size_(hash_size),
5601 hash_table_(hash_table),
5602 image_pointer_size_(image_pointer_size) {
5603 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5604 }
5605
Add(uint32_t virtual_method_index)5606 void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) {
5607 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5608 virtual_method_index, image_pointer_size_);
5609 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
5610 uint32_t hash = ComputeModifiedUtf8Hash(name);
5611 uint32_t index = hash % hash_size_;
5612 // Linear probe until we have an empty slot.
5613 while (hash_table_[index] != invalid_index_) {
5614 if (++index == hash_size_) {
5615 index = 0;
5616 }
5617 }
5618 hash_table_[index] = virtual_method_index;
5619 }
5620
FindAndRemove(MethodNameAndSignatureComparator * comparator)5621 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
5622 SHARED_REQUIRES(Locks::mutator_lock_) {
5623 const char* name = comparator->GetName();
5624 uint32_t hash = ComputeModifiedUtf8Hash(name);
5625 size_t index = hash % hash_size_;
5626 while (true) {
5627 const uint32_t value = hash_table_[index];
5628 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5629 // the block and can safely assume not found.
5630 if (value == invalid_index_) {
5631 break;
5632 }
5633 if (value != removed_index_) { // This signifies not already overriden.
5634 ArtMethod* virtual_method =
5635 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5636 if (comparator->HasSameNameAndSignature(
5637 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5638 hash_table_[index] = removed_index_;
5639 return value;
5640 }
5641 }
5642 if (++index == hash_size_) {
5643 index = 0;
5644 }
5645 }
5646 return GetNotFoundIndex();
5647 }
5648
GetNotFoundIndex()5649 static uint32_t GetNotFoundIndex() {
5650 return invalid_index_;
5651 }
5652
5653 private:
5654 static const uint32_t invalid_index_;
5655 static const uint32_t removed_index_;
5656
5657 Handle<mirror::Class> klass_;
5658 const size_t hash_size_;
5659 uint32_t* const hash_table_;
5660 const size_t image_pointer_size_;
5661 };
5662
5663 const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5664 const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5665
LinkVirtualMethods(Thread * self,Handle<mirror::Class> klass,std::unordered_map<size_t,ClassLinker::MethodTranslation> * default_translations)5666 bool ClassLinker::LinkVirtualMethods(
5667 Thread* self,
5668 Handle<mirror::Class> klass,
5669 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
5670 const size_t num_virtual_methods = klass->NumVirtualMethods();
5671 if (klass->IsInterface()) {
5672 // No vtable.
5673 if (!IsUint<16>(num_virtual_methods)) {
5674 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5675 return false;
5676 }
5677 bool has_defaults = false;
5678 // Assign each method an IMT index and set the default flag.
5679 for (size_t i = 0; i < num_virtual_methods; ++i) {
5680 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5681 m->SetMethodIndex(i);
5682 if (!m->IsAbstract()) {
5683 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5684 has_defaults = true;
5685 }
5686 }
5687 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5688 // during initialization. This is a performance optimization. We could simply traverse the
5689 // virtual_methods_ array again during initialization.
5690 if (has_defaults) {
5691 klass->SetHasDefaultMethods();
5692 }
5693 return true;
5694 } else if (klass->HasSuperClass()) {
5695 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5696 const size_t max_count = num_virtual_methods + super_vtable_length;
5697 StackHandleScope<2> hs(self);
5698 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
5699 MutableHandle<mirror::PointerArray> vtable;
5700 if (super_class->ShouldHaveEmbeddedVTable()) {
5701 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
5702 if (UNLIKELY(vtable.Get() == nullptr)) {
5703 self->AssertPendingOOMException();
5704 return false;
5705 }
5706 for (size_t i = 0; i < super_vtable_length; i++) {
5707 vtable->SetElementPtrSize(
5708 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
5709 }
5710 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5711 // might give us new default methods). If no new interfaces then we can skip the rest since
5712 // the class cannot override any of the super-class's methods. This is required for
5713 // correctness since without it we might not update overridden default method vtable entries
5714 // correctly.
5715 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
5716 klass->SetVTable(vtable.Get());
5717 return true;
5718 }
5719 } else {
5720 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
5721 auto* super_vtable = super_class->GetVTable();
5722 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
5723 // We might need to change vtable if we have new virtual methods or new interfaces (since that
5724 // might give us new default methods). See comment above.
5725 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
5726 klass->SetVTable(super_vtable);
5727 return true;
5728 }
5729 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5730 super_vtable->CopyOf(self, max_count)));
5731 if (UNLIKELY(vtable.Get() == nullptr)) {
5732 self->AssertPendingOOMException();
5733 return false;
5734 }
5735 }
5736 // How the algorithm works:
5737 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5738 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5739 // method which has not been matched to a vtable method, and j if the virtual method at the
5740 // index overrode the super virtual method at index j.
5741 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5742 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5743 // the need for the initial vtable which we later shrink back down).
5744 // 3. Add non overridden methods to the end of the vtable.
5745 static constexpr size_t kMaxStackHash = 250;
5746 // + 1 so that even if we only have new default methods we will still be able to use this hash
5747 // table (i.e. it will never have 0 size).
5748 const size_t hash_table_size = num_virtual_methods * 3 + 1;
5749 uint32_t* hash_table_ptr;
5750 std::unique_ptr<uint32_t[]> hash_heap_storage;
5751 if (hash_table_size <= kMaxStackHash) {
5752 hash_table_ptr = reinterpret_cast<uint32_t*>(
5753 alloca(hash_table_size * sizeof(*hash_table_ptr)));
5754 } else {
5755 hash_heap_storage.reset(new uint32_t[hash_table_size]);
5756 hash_table_ptr = hash_heap_storage.get();
5757 }
5758 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
5759 // Add virtual methods to the hash table.
5760 for (size_t i = 0; i < num_virtual_methods; ++i) {
5761 DCHECK(klass->GetVirtualMethodDuringLinking(
5762 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
5763 hash_table.Add(i);
5764 }
5765 // Loop through each super vtable method and see if they are overridden by a method we added to
5766 // the hash table.
5767 for (size_t j = 0; j < super_vtable_length; ++j) {
5768 // Search the hash table to see if we are overridden by any method.
5769 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5770 MethodNameAndSignatureComparator super_method_name_comparator(
5771 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5772 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5773 if (hash_index != hash_table.GetNotFoundIndex()) {
5774 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5775 hash_index, image_pointer_size_);
5776 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5777 super_method->GetAccessFlags())) {
5778 if (super_method->IsFinal()) {
5779 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5780 PrettyMethod(virtual_method).c_str(),
5781 super_method->GetDeclaringClassDescriptor());
5782 return false;
5783 }
5784 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5785 virtual_method->SetMethodIndex(j);
5786 } else {
5787 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
5788 << " would have incorrectly overridden the package-private method in "
5789 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
5790 }
5791 } else if (super_method->IsOverridableByDefaultMethod()) {
5792 // We didn't directly override this method but we might through default methods...
5793 // Check for default method update.
5794 ArtMethod* default_method = nullptr;
5795 switch (FindDefaultMethodImplementation(self,
5796 super_method,
5797 klass,
5798 /*out*/&default_method)) {
5799 case DefaultMethodSearchResult::kDefaultConflict: {
5800 // A conflict was found looking for default methods. Note this (assuming it wasn't
5801 // pre-existing) in the translations map.
5802 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5803 // Don't generate another conflict method to reduce memory use as an optimization.
5804 default_translations->insert(
5805 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5806 }
5807 break;
5808 }
5809 case DefaultMethodSearchResult::kAbstractFound: {
5810 // No conflict but method is abstract.
5811 // We note that this vtable entry must be made abstract.
5812 if (UNLIKELY(!super_method->IsAbstract())) {
5813 default_translations->insert(
5814 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5815 }
5816 break;
5817 }
5818 case DefaultMethodSearchResult::kDefaultFound: {
5819 if (UNLIKELY(super_method->IsDefaultConflicting() ||
5820 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5821 // Found a default method implementation that is new.
5822 // TODO Refactor this add default methods to virtuals here and not in
5823 // LinkInterfaceMethods maybe.
5824 // The problem is default methods might override previously present
5825 // default-method or miranda-method vtable entries from the superclass.
5826 // Unfortunately we need these to be entries in this class's virtuals. We do not
5827 // give these entries there until LinkInterfaceMethods so we pass this map around
5828 // to let it know which vtable entries need to be updated.
5829 // Make a note that vtable entry j must be updated, store what it needs to be updated
5830 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5831 // then.
5832 default_translations->insert(
5833 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
5834 VLOG(class_linker) << "Method " << PrettyMethod(super_method)
5835 << " overridden by default " << PrettyMethod(default_method)
5836 << " in " << PrettyClass(klass.Get());
5837 }
5838 break;
5839 }
5840 }
5841 }
5842 }
5843 size_t actual_count = super_vtable_length;
5844 // Add the non-overridden methods at the end.
5845 for (size_t i = 0; i < num_virtual_methods; ++i) {
5846 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5847 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5848 if (method_idx < super_vtable_length &&
5849 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
5850 continue;
5851 }
5852 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
5853 local_method->SetMethodIndex(actual_count);
5854 ++actual_count;
5855 }
5856 if (!IsUint<16>(actual_count)) {
5857 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
5858 return false;
5859 }
5860 // Shrink vtable if possible
5861 CHECK_LE(actual_count, max_count);
5862 if (actual_count < max_count) {
5863 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
5864 if (UNLIKELY(vtable.Get() == nullptr)) {
5865 self->AssertPendingOOMException();
5866 return false;
5867 }
5868 }
5869 klass->SetVTable(vtable.Get());
5870 } else {
5871 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
5872 if (!IsUint<16>(num_virtual_methods)) {
5873 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5874 static_cast<int>(num_virtual_methods));
5875 return false;
5876 }
5877 auto* vtable = AllocPointerArray(self, num_virtual_methods);
5878 if (UNLIKELY(vtable == nullptr)) {
5879 self->AssertPendingOOMException();
5880 return false;
5881 }
5882 for (size_t i = 0; i < num_virtual_methods; ++i) {
5883 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5884 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
5885 virtual_method->SetMethodIndex(i & 0xFFFF);
5886 }
5887 klass->SetVTable(vtable);
5888 }
5889 return true;
5890 }
5891
5892 // Determine if the given iface has any subinterface in the given list that declares the method
5893 // specified by 'target'.
5894 //
5895 // Arguments
5896 // - self: The thread we are running on
5897 // - target: A comparator that will match any method that overrides the method we are checking for
5898 // - iftable: The iftable we are searching for an overriding method on.
5899 // - ifstart: The index of the interface we are checking to see if anything overrides
5900 // - iface: The interface we are checking to see if anything overrides.
5901 // - image_pointer_size:
5902 // The image pointer size.
5903 //
5904 // Returns
5905 // - True: There is some method that matches the target comparator defined in an interface that
5906 // is a subtype of iface.
5907 // - False: There is no method that matches the target comparator in any interface that is a subtype
5908 // of iface.
ContainsOverridingMethodOf(Thread * self,MethodNameAndSignatureComparator & target,Handle<mirror::IfTable> iftable,size_t ifstart,Handle<mirror::Class> iface,size_t image_pointer_size)5909 static bool ContainsOverridingMethodOf(Thread* self,
5910 MethodNameAndSignatureComparator& target,
5911 Handle<mirror::IfTable> iftable,
5912 size_t ifstart,
5913 Handle<mirror::Class> iface,
5914 size_t image_pointer_size)
5915 SHARED_REQUIRES(Locks::mutator_lock_) {
5916 DCHECK(self != nullptr);
5917 DCHECK(iface.Get() != nullptr);
5918 DCHECK(iftable.Get() != nullptr);
5919 DCHECK_GE(ifstart, 0u);
5920 DCHECK_LT(ifstart, iftable->Count());
5921 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5922 DCHECK(iface->IsInterface());
5923
5924 size_t iftable_count = iftable->Count();
5925 StackHandleScope<1> hs(self);
5926 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5927 for (size_t k = ifstart + 1; k < iftable_count; k++) {
5928 // Skip ifstart since our current interface obviously cannot override itself.
5929 current_iface.Assign(iftable->GetInterface(k));
5930 // Iterate through every method on this interface. The order does not matter.
5931 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
5932 if (UNLIKELY(target.HasSameNameAndSignature(
5933 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
5934 // Check if the i'th interface is a subtype of this one.
5935 if (iface->IsAssignableFrom(current_iface.Get())) {
5936 return true;
5937 }
5938 break;
5939 }
5940 }
5941 }
5942 return false;
5943 }
5944
5945 // Find the default method implementation for 'interface_method' in 'klass'. Stores it into
5946 // out_default_method and returns kDefaultFound on success. If no default method was found return
5947 // kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5948 // default_method conflict) it will return kDefaultConflict.
FindDefaultMethodImplementation(Thread * self,ArtMethod * target_method,Handle<mirror::Class> klass,ArtMethod ** out_default_method) const5949 ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5950 Thread* self,
5951 ArtMethod* target_method,
5952 Handle<mirror::Class> klass,
5953 /*out*/ArtMethod** out_default_method) const {
5954 DCHECK(self != nullptr);
5955 DCHECK(target_method != nullptr);
5956 DCHECK(out_default_method != nullptr);
5957
5958 *out_default_method = nullptr;
5959
5960 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
5961 // table. This lets us walk the table backwards when searching for default methods. The first one
5962 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
5963 // track of it and then continue checking all other interfaces, since we need to throw an error if
5964 // we encounter conflicting default method implementations (one is not a subtype of the other).
5965 //
5966 // The order of unrelated interfaces does not matter and is not defined.
5967 size_t iftable_count = klass->GetIfTableCount();
5968 if (iftable_count == 0) {
5969 // No interfaces. We have already reset out to null so just return kAbstractFound.
5970 return DefaultMethodSearchResult::kAbstractFound;
5971 }
5972
5973 StackHandleScope<3> hs(self);
5974 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
5975 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
5976 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
5977 MethodNameAndSignatureComparator target_name_comparator(
5978 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5979 // Iterates over the klass's iftable in reverse
5980 for (size_t k = iftable_count; k != 0; ) {
5981 --k;
5982
5983 DCHECK_LT(k, iftable->Count());
5984
5985 iface.Assign(iftable->GetInterface(k));
5986 // Iterate through every declared method on this interface. The order does not matter.
5987 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
5988 ArtMethod* current_method = &method_iter;
5989 // Skip abstract methods and methods with different names.
5990 if (current_method->IsAbstract() ||
5991 !target_name_comparator.HasSameNameAndSignature(
5992 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5993 continue;
5994 } else if (!current_method->IsPublic()) {
5995 // The verifier should have caught the non-public method for dex version 37. Just warn and
5996 // skip it since this is from before default-methods so we don't really need to care that it
5997 // has code.
5998 LOG(WARNING) << "Interface method " << PrettyMethod(current_method) << " is not public! "
5999 << "This will be a fatal error in subsequent versions of android. "
6000 << "Continuing anyway.";
6001 }
6002 if (UNLIKELY(chosen_iface.Get() != nullptr)) {
6003 // We have multiple default impls of the same method. This is a potential default conflict.
6004 // We need to check if this possibly conflicting method is either a superclass of the chosen
6005 // default implementation or is overridden by a non-default interface method. In either case
6006 // there is no conflict.
6007 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6008 !ContainsOverridingMethodOf(self,
6009 target_name_comparator,
6010 iftable,
6011 k,
6012 iface,
6013 image_pointer_size_)) {
6014 VLOG(class_linker) << "Conflicting default method implementations found: "
6015 << PrettyMethod(current_method) << " and "
6016 << PrettyMethod(*out_default_method) << " in class "
6017 << PrettyClass(klass.Get()) << " conflict.";
6018 *out_default_method = nullptr;
6019 return DefaultMethodSearchResult::kDefaultConflict;
6020 } else {
6021 break; // Continue checking at the next interface.
6022 }
6023 } else {
6024 // chosen_iface == null
6025 if (!ContainsOverridingMethodOf(self,
6026 target_name_comparator,
6027 iftable,
6028 k,
6029 iface,
6030 image_pointer_size_)) {
6031 // Don't set this as the chosen interface if something else is overriding it (because that
6032 // other interface would be potentially chosen instead if it was default). If the other
6033 // interface was abstract then we wouldn't select this interface as chosen anyway since
6034 // the abstract method masks it.
6035 *out_default_method = current_method;
6036 chosen_iface.Assign(iface.Get());
6037 // We should now finish traversing the graph to find if we have default methods that
6038 // conflict.
6039 } else {
6040 VLOG(class_linker) << "A default method '" << PrettyMethod(current_method) << "' was "
6041 << "skipped because it was overridden by an abstract method in a "
6042 << "subinterface on class '" << PrettyClass(klass.Get()) << "'";
6043 }
6044 }
6045 break;
6046 }
6047 }
6048 if (*out_default_method != nullptr) {
6049 VLOG(class_linker) << "Default method '" << PrettyMethod(*out_default_method) << "' selected "
6050 << "as the implementation for '" << PrettyMethod(target_method) << "' "
6051 << "in '" << PrettyClass(klass.Get()) << "'";
6052 return DefaultMethodSearchResult::kDefaultFound;
6053 } else {
6054 return DefaultMethodSearchResult::kAbstractFound;
6055 }
6056 }
6057
AddMethodToConflictTable(mirror::Class * klass,ArtMethod * conflict_method,ArtMethod * interface_method,ArtMethod * method,bool force_new_conflict_method)6058 ArtMethod* ClassLinker::AddMethodToConflictTable(mirror::Class* klass,
6059 ArtMethod* conflict_method,
6060 ArtMethod* interface_method,
6061 ArtMethod* method,
6062 bool force_new_conflict_method) {
6063 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(sizeof(void*));
6064 Runtime* const runtime = Runtime::Current();
6065 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6066 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6067
6068 // Create a new entry if the existing one is the shared conflict method.
6069 ArtMethod* new_conflict_method = new_entry
6070 ? runtime->CreateImtConflictMethod(linear_alloc)
6071 : conflict_method;
6072
6073 // Allocate a new table. Note that we will leak this table at the next conflict,
6074 // but that's a tradeoff compared to making the table fixed size.
6075 void* data = linear_alloc->Alloc(
6076 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6077 image_pointer_size_));
6078 if (data == nullptr) {
6079 LOG(ERROR) << "Failed to allocate conflict table";
6080 return conflict_method;
6081 }
6082 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6083 interface_method,
6084 method,
6085 image_pointer_size_);
6086
6087 // Do a fence to ensure threads see the data in the table before it is assigned
6088 // to the conflict method.
6089 // Note that there is a race in the presence of multiple threads and we may leak
6090 // memory from the LinearAlloc, but that's a tradeoff compared to using
6091 // atomic operations.
6092 QuasiAtomic::ThreadFenceRelease();
6093 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6094 return new_conflict_method;
6095 }
6096
SetIMTRef(ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,ArtMethod * current_method,bool * new_conflict,ArtMethod ** imt_ref)6097 void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6098 ArtMethod* imt_conflict_method,
6099 ArtMethod* current_method,
6100 /*out*/bool* new_conflict,
6101 /*out*/ArtMethod** imt_ref) {
6102 // Place method in imt if entry is empty, place conflict otherwise.
6103 if (*imt_ref == unimplemented_method) {
6104 *imt_ref = current_method;
6105 } else if (!(*imt_ref)->IsRuntimeMethod()) {
6106 // If we are not a conflict and we have the same signature and name as the imt
6107 // entry, it must be that we overwrote a superclass vtable entry.
6108 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6109 // conflict methods.
6110 MethodNameAndSignatureComparator imt_comparator(
6111 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
6112 if (imt_comparator.HasSameNameAndSignature(
6113 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6114 *imt_ref = current_method;
6115 } else {
6116 *imt_ref = imt_conflict_method;
6117 *new_conflict = true;
6118 }
6119 } else {
6120 // Place the default conflict method. Note that there may be an existing conflict
6121 // method in the IMT, but it could be one tailored to the super class, with a
6122 // specific ImtConflictTable.
6123 *imt_ref = imt_conflict_method;
6124 *new_conflict = true;
6125 }
6126 }
6127
FillIMTAndConflictTables(mirror::Class * klass)6128 void ClassLinker::FillIMTAndConflictTables(mirror::Class* klass) {
6129 DCHECK(klass->ShouldHaveImt()) << PrettyClass(klass);
6130 DCHECK(!klass->IsTemp()) << PrettyClass(klass);
6131 ArtMethod* imt_data[ImTable::kSize];
6132 Runtime* const runtime = Runtime::Current();
6133 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6134 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
6135 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
6136 if (klass->GetIfTable() != nullptr) {
6137 bool new_conflict = false;
6138 FillIMTFromIfTable(klass->GetIfTable(),
6139 unimplemented_method,
6140 conflict_method,
6141 klass,
6142 /*create_conflict_tables*/true,
6143 /*ignore_copied_methods*/false,
6144 &new_conflict,
6145 &imt_data[0]);
6146 }
6147 if (!klass->ShouldHaveImt()) {
6148 return;
6149 }
6150 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6151 // we can just use the same pointer.
6152 ImTable* imt = nullptr;
6153 mirror::Class* super_class = klass->GetSuperClass();
6154 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6155 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6156 bool same = true;
6157 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6158 ArtMethod* method = imt_data[i];
6159 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6160 if (method != super_method) {
6161 bool is_conflict_table = method->IsRuntimeMethod() &&
6162 method != unimplemented_method &&
6163 method != conflict_method;
6164 // Verify conflict contents.
6165 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6166 super_method != unimplemented_method &&
6167 super_method != conflict_method;
6168 if (!is_conflict_table || !super_conflict_table) {
6169 same = false;
6170 } else {
6171 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6172 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6173 same = same && table1->Equals(table2, image_pointer_size_);
6174 }
6175 }
6176 }
6177 if (same) {
6178 imt = super_imt;
6179 }
6180 }
6181 if (imt == nullptr) {
6182 imt = klass->GetImt(image_pointer_size_);
6183 DCHECK(imt != nullptr);
6184 imt->Populate(imt_data, image_pointer_size_);
6185 } else {
6186 klass->SetImt(imt, image_pointer_size_);
6187 }
6188 }
6189
GetIMTIndex(ArtMethod * interface_method)6190 static inline uint32_t GetIMTIndex(ArtMethod* interface_method)
6191 SHARED_REQUIRES(Locks::mutator_lock_) {
6192 return interface_method->GetDexMethodIndex() % ImTable::kSize;
6193 }
6194
CreateImtConflictTable(size_t count,LinearAlloc * linear_alloc,size_t image_pointer_size)6195 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6196 LinearAlloc* linear_alloc,
6197 size_t image_pointer_size) {
6198 void* data = linear_alloc->Alloc(Thread::Current(),
6199 ImtConflictTable::ComputeSize(count,
6200 image_pointer_size));
6201 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6202 }
6203
CreateImtConflictTable(size_t count,LinearAlloc * linear_alloc)6204 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6205 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6206 }
6207
FillIMTFromIfTable(mirror::IfTable * if_table,ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,mirror::Class * klass,bool create_conflict_tables,bool ignore_copied_methods,bool * new_conflict,ArtMethod ** imt)6208 void ClassLinker::FillIMTFromIfTable(mirror::IfTable* if_table,
6209 ArtMethod* unimplemented_method,
6210 ArtMethod* imt_conflict_method,
6211 mirror::Class* klass,
6212 bool create_conflict_tables,
6213 bool ignore_copied_methods,
6214 /*out*/bool* new_conflict,
6215 /*out*/ArtMethod** imt) {
6216 uint32_t conflict_counts[ImTable::kSize] = {};
6217 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6218 mirror::Class* interface = if_table->GetInterface(i);
6219 const size_t num_virtuals = interface->NumVirtualMethods();
6220 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6221 // Virtual methods can be larger than the if table methods if there are default methods.
6222 DCHECK_GE(num_virtuals, method_array_count);
6223 if (kIsDebugBuild) {
6224 if (klass->IsInterface()) {
6225 DCHECK_EQ(method_array_count, 0u);
6226 } else {
6227 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6228 }
6229 }
6230 if (method_array_count == 0) {
6231 continue;
6232 }
6233 auto* method_array = if_table->GetMethodArray(i);
6234 for (size_t j = 0; j < method_array_count; ++j) {
6235 ArtMethod* implementation_method =
6236 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6237 if (ignore_copied_methods && implementation_method->IsCopied()) {
6238 continue;
6239 }
6240 DCHECK(implementation_method != nullptr);
6241 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6242 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6243 // or interface methods in the IMT here they will not create extra conflicts since we compare
6244 // names and signatures in SetIMTRef.
6245 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
6246 const uint32_t imt_index = GetIMTIndex(interface_method);
6247
6248 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6249 // the same implementation method, keep track of this to avoid creating a conflict table in
6250 // this case.
6251
6252 // Conflict table size for each IMT slot.
6253 ++conflict_counts[imt_index];
6254
6255 SetIMTRef(unimplemented_method,
6256 imt_conflict_method,
6257 implementation_method,
6258 /*out*/new_conflict,
6259 /*out*/&imt[imt_index]);
6260 }
6261 }
6262
6263 if (create_conflict_tables) {
6264 // Create the conflict tables.
6265 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6266 for (size_t i = 0; i < ImTable::kSize; ++i) {
6267 size_t conflicts = conflict_counts[i];
6268 if (imt[i] == imt_conflict_method) {
6269 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6270 if (new_table != nullptr) {
6271 ArtMethod* new_conflict_method =
6272 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6273 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6274 imt[i] = new_conflict_method;
6275 } else {
6276 LOG(ERROR) << "Failed to allocate conflict table";
6277 imt[i] = imt_conflict_method;
6278 }
6279 } else {
6280 DCHECK_NE(imt[i], imt_conflict_method);
6281 }
6282 }
6283
6284 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6285 mirror::Class* interface = if_table->GetInterface(i);
6286 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6287 // Virtual methods can be larger than the if table methods if there are default methods.
6288 if (method_array_count == 0) {
6289 continue;
6290 }
6291 auto* method_array = if_table->GetMethodArray(i);
6292 for (size_t j = 0; j < method_array_count; ++j) {
6293 ArtMethod* implementation_method =
6294 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6295 if (ignore_copied_methods && implementation_method->IsCopied()) {
6296 continue;
6297 }
6298 DCHECK(implementation_method != nullptr);
6299 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
6300 const uint32_t imt_index = GetIMTIndex(interface_method);
6301 if (!imt[imt_index]->IsRuntimeMethod() ||
6302 imt[imt_index] == unimplemented_method ||
6303 imt[imt_index] == imt_conflict_method) {
6304 continue;
6305 }
6306 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6307 const size_t num_entries = table->NumEntries(image_pointer_size_);
6308 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6309 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
6310 }
6311 }
6312 }
6313 }
6314
6315 // Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6316 // set.
NotSubinterfaceOfAny(const std::unordered_set<mirror::Class * > & classes,mirror::Class * val)6317 static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes,
6318 mirror::Class* val)
6319 REQUIRES(Roles::uninterruptible_)
6320 SHARED_REQUIRES(Locks::mutator_lock_) {
6321 DCHECK(val != nullptr);
6322 for (auto c : classes) {
6323 if (val->IsAssignableFrom(&*c)) {
6324 return false;
6325 }
6326 }
6327 return true;
6328 }
6329
6330 // Fills in and flattens the interface inheritance hierarchy.
6331 //
6332 // By the end of this function all interfaces in the transitive closure of to_process are added to
6333 // the iftable and every interface precedes all of its sub-interfaces in this list.
6334 //
6335 // all I, J: Interface | I <: J implies J precedes I
6336 //
6337 // (note A <: B means that A is a subtype of B)
6338 //
6339 // This returns the total number of items in the iftable. The iftable might be resized down after
6340 // this call.
6341 //
6342 // We order this backwards so that we do not need to reorder superclass interfaces when new
6343 // interfaces are added in subclass's interface tables.
6344 //
6345 // Upon entry into this function iftable is a copy of the superclass's iftable with the first
6346 // super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6347 // The other entries are uninitialized. We will fill in the remaining entries in this function. The
6348 // iftable must be large enough to hold all interfaces without changing its size.
FillIfTable(mirror::IfTable * iftable,size_t super_ifcount,std::vector<mirror::Class * > to_process)6349 static size_t FillIfTable(mirror::IfTable* iftable,
6350 size_t super_ifcount,
6351 std::vector<mirror::Class*> to_process)
6352 REQUIRES(Roles::uninterruptible_)
6353 SHARED_REQUIRES(Locks::mutator_lock_) {
6354 // This is the set of all class's already in the iftable. Used to make checking if a class has
6355 // already been added quicker.
6356 std::unordered_set<mirror::Class*> classes_in_iftable;
6357 // The first super_ifcount elements are from the superclass. We note that they are already added.
6358 for (size_t i = 0; i < super_ifcount; i++) {
6359 mirror::Class* iface = iftable->GetInterface(i);
6360 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6361 classes_in_iftable.insert(iface);
6362 }
6363 size_t filled_ifcount = super_ifcount;
6364 for (mirror::Class* interface : to_process) {
6365 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6366 // At this point in the loop current-iface-list has the invariant that:
6367 // for every pair of interfaces I,J within it:
6368 // if index_of(I) < index_of(J) then I is not a subtype of J
6369
6370 // If we have already seen this element then all of its super-interfaces must already be in the
6371 // current-iface-list so we can skip adding it.
6372 if (!ContainsElement(classes_in_iftable, interface)) {
6373 // We haven't seen this interface so add all of its super-interfaces onto the
6374 // current-iface-list, skipping those already on it.
6375 int32_t ifcount = interface->GetIfTableCount();
6376 for (int32_t j = 0; j < ifcount; j++) {
6377 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6378 if (!ContainsElement(classes_in_iftable, super_interface)) {
6379 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6380 classes_in_iftable.insert(super_interface);
6381 iftable->SetInterface(filled_ifcount, super_interface);
6382 filled_ifcount++;
6383 }
6384 }
6385 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6386 // Place this interface onto the current-iface-list after all of its super-interfaces.
6387 classes_in_iftable.insert(interface);
6388 iftable->SetInterface(filled_ifcount, interface);
6389 filled_ifcount++;
6390 } else if (kIsDebugBuild) {
6391 // Check all super-interfaces are already in the list.
6392 int32_t ifcount = interface->GetIfTableCount();
6393 for (int32_t j = 0; j < ifcount; j++) {
6394 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6395 DCHECK(ContainsElement(classes_in_iftable, super_interface))
6396 << "Iftable does not contain " << PrettyClass(super_interface)
6397 << ", a superinterface of " << PrettyClass(interface);
6398 }
6399 }
6400 }
6401 if (kIsDebugBuild) {
6402 // Check that the iftable is ordered correctly.
6403 for (size_t i = 0; i < filled_ifcount; i++) {
6404 mirror::Class* if_a = iftable->GetInterface(i);
6405 for (size_t j = i + 1; j < filled_ifcount; j++) {
6406 mirror::Class* if_b = iftable->GetInterface(j);
6407 // !(if_a <: if_b)
6408 CHECK(!if_b->IsAssignableFrom(if_a))
6409 << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends "
6410 << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the "
6411 << "interface list.";
6412 }
6413 }
6414 }
6415 return filled_ifcount;
6416 }
6417
SetupInterfaceLookupTable(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces)6418 bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6419 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6420 StackHandleScope<1> hs(self);
6421 const size_t super_ifcount =
6422 klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6423 const bool have_interfaces = interfaces.Get() != nullptr;
6424 const size_t num_interfaces =
6425 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
6426 if (num_interfaces == 0) {
6427 if (super_ifcount == 0) {
6428 // Class implements no interfaces.
6429 DCHECK_EQ(klass->GetIfTableCount(), 0);
6430 DCHECK(klass->GetIfTable() == nullptr);
6431 return true;
6432 }
6433 // Class implements same interfaces as parent, are any of these not marker interfaces?
6434 bool has_non_marker_interface = false;
6435 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
6436 for (size_t i = 0; i < super_ifcount; ++i) {
6437 if (super_iftable->GetMethodArrayCount(i) > 0) {
6438 has_non_marker_interface = true;
6439 break;
6440 }
6441 }
6442 // Class just inherits marker interfaces from parent so recycle parent's iftable.
6443 if (!has_non_marker_interface) {
6444 klass->SetIfTable(super_iftable);
6445 return true;
6446 }
6447 }
6448 size_t ifcount = super_ifcount + num_interfaces;
6449 // Check that every class being implemented is an interface.
6450 for (size_t i = 0; i < num_interfaces; i++) {
6451 mirror::Class* interface = have_interfaces
6452 ? interfaces->GetWithoutChecks(i)
6453 : mirror::Class::GetDirectInterface(self, klass, i);
6454 DCHECK(interface != nullptr);
6455 if (UNLIKELY(!interface->IsInterface())) {
6456 std::string temp;
6457 ThrowIncompatibleClassChangeError(klass.Get(),
6458 "Class %s implements non-interface class %s",
6459 PrettyDescriptor(klass.Get()).c_str(),
6460 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6461 return false;
6462 }
6463 ifcount += interface->GetIfTableCount();
6464 }
6465 // Create the interface function table.
6466 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
6467 if (UNLIKELY(iftable.Get() == nullptr)) {
6468 self->AssertPendingOOMException();
6469 return false;
6470 }
6471 // Fill in table with superclass's iftable.
6472 if (super_ifcount != 0) {
6473 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
6474 for (size_t i = 0; i < super_ifcount; i++) {
6475 mirror::Class* super_interface = super_iftable->GetInterface(i);
6476 iftable->SetInterface(i, super_interface);
6477 }
6478 }
6479
6480 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6481 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6482 // doesn't really do anything.
6483 self->AllowThreadSuspension();
6484
6485 size_t new_ifcount;
6486 {
6487 ScopedAssertNoThreadSuspension nts(self, "Copying mirror::Class*'s for FillIfTable");
6488 std::vector<mirror::Class*> to_add;
6489 for (size_t i = 0; i < num_interfaces; i++) {
6490 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
6491 mirror::Class::GetDirectInterface(self, klass, i);
6492 to_add.push_back(interface);
6493 }
6494
6495 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
6496 }
6497
6498 self->AllowThreadSuspension();
6499
6500 // Shrink iftable in case duplicates were found
6501 if (new_ifcount < ifcount) {
6502 DCHECK_NE(num_interfaces, 0U);
6503 iftable.Assign(down_cast<mirror::IfTable*>(
6504 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
6505 if (UNLIKELY(iftable.Get() == nullptr)) {
6506 self->AssertPendingOOMException();
6507 return false;
6508 }
6509 ifcount = new_ifcount;
6510 } else {
6511 DCHECK_EQ(new_ifcount, ifcount);
6512 }
6513 klass->SetIfTable(iftable.Get());
6514 return true;
6515 }
6516
6517 // Finds the method with a name/signature that matches cmp in the given list of methods. The list of
6518 // methods must be unique.
FindSameNameAndSignature(MethodNameAndSignatureComparator & cmp,const ScopedArenaVector<ArtMethod * > & list)6519 static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
6520 const ScopedArenaVector<ArtMethod*>& list)
6521 SHARED_REQUIRES(Locks::mutator_lock_) {
6522 for (ArtMethod* method : list) {
6523 if (cmp.HasSameNameAndSignature(method)) {
6524 return method;
6525 }
6526 }
6527 return nullptr;
6528 }
6529
SanityCheckVTable(Handle<mirror::Class> klass,uint32_t pointer_size)6530 static void SanityCheckVTable(Handle<mirror::Class> klass, uint32_t pointer_size)
6531 SHARED_REQUIRES(Locks::mutator_lock_) {
6532 mirror::PointerArray* check_vtable = klass->GetVTableDuringLinking();
6533 mirror::Class* superclass = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
6534 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
6535 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6536 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6537 CHECK(m != nullptr);
6538
6539 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6540 auto is_same_method = [m] (const ArtMethod& meth) {
6541 return &meth == m;
6542 };
6543 CHECK((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6544 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())
6545 << "While linking class '" << PrettyClass(klass.Get()) << "' unable to find owning class "
6546 << "of '" << PrettyMethod(m) << "' (vtable index: " << i << ").";
6547 }
6548 }
6549
FillImtFromSuperClass(Handle<mirror::Class> klass,ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,bool * new_conflict,ArtMethod ** imt)6550 void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6551 ArtMethod* unimplemented_method,
6552 ArtMethod* imt_conflict_method,
6553 bool* new_conflict,
6554 ArtMethod** imt) {
6555 DCHECK(klass->HasSuperClass());
6556 mirror::Class* super_class = klass->GetSuperClass();
6557 if (super_class->ShouldHaveImt()) {
6558 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6559 for (size_t i = 0; i < ImTable::kSize; ++i) {
6560 imt[i] = super_imt->Get(i, image_pointer_size_);
6561 }
6562 } else {
6563 // No imt in the super class, need to reconstruct from the iftable.
6564 mirror::IfTable* if_table = super_class->GetIfTable();
6565 if (if_table != nullptr) {
6566 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
6567 FillIMTFromIfTable(if_table,
6568 unimplemented_method,
6569 imt_conflict_method,
6570 klass.Get(),
6571 /*create_conflict_table*/false,
6572 /*ignore_copied_methods*/true,
6573 /*out*/new_conflict,
6574 /*out*/imt);
6575 }
6576 }
6577 }
6578
6579 // TODO This method needs to be split up into several smaller methods.
LinkInterfaceMethods(Thread * self,Handle<mirror::Class> klass,const std::unordered_map<size_t,ClassLinker::MethodTranslation> & default_translations,bool * out_new_conflict,ArtMethod ** out_imt)6580 bool ClassLinker::LinkInterfaceMethods(
6581 Thread* self,
6582 Handle<mirror::Class> klass,
6583 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6584 bool* out_new_conflict,
6585 ArtMethod** out_imt) {
6586 StackHandleScope<3> hs(self);
6587 Runtime* const runtime = Runtime::Current();
6588
6589 const bool is_interface = klass->IsInterface();
6590 const bool has_superclass = klass->HasSuperClass();
6591 const bool fill_tables = !is_interface;
6592 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6593 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
6594 const size_t method_size = ArtMethod::Size(image_pointer_size_);
6595 const size_t ifcount = klass->GetIfTableCount();
6596
6597 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
6598
6599 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6600 // the virtual methods array.
6601 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6602 // during cross compilation.
6603 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6604 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool());
6605 ScopedArenaAllocator allocator(&stack);
6606
6607 ScopedArenaVector<ArtMethod*> default_conflict_methods(allocator.Adapter());
6608 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter());
6609 ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter());
6610
6611 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6612 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6613 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
6614 // Copy the IMT from the super class if possible.
6615 const bool extend_super_iftable = has_superclass;
6616 if (has_superclass && fill_tables) {
6617 FillImtFromSuperClass(klass,
6618 unimplemented_method,
6619 imt_conflict_method,
6620 out_new_conflict,
6621 out_imt);
6622 }
6623 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
6624 // thread suspension.
6625 if (fill_tables) {
6626 for (size_t i = 0; i < ifcount; ++i) {
6627 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6628 if (num_methods > 0) {
6629 const bool is_super = i < super_ifcount;
6630 // This is an interface implemented by a super-class. Therefore we can just copy the method
6631 // array from the superclass.
6632 const bool super_interface = is_super && extend_super_iftable;
6633 mirror::PointerArray* method_array;
6634 if (super_interface) {
6635 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
6636 DCHECK(if_table != nullptr);
6637 DCHECK(if_table->GetMethodArray(i) != nullptr);
6638 // If we are working on a super interface, try extending the existing method array.
6639 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6640 } else {
6641 method_array = AllocPointerArray(self, num_methods);
6642 }
6643 if (UNLIKELY(method_array == nullptr)) {
6644 self->AssertPendingOOMException();
6645 return false;
6646 }
6647 iftable->SetMethodArray(i, method_array);
6648 }
6649 }
6650 }
6651
6652 auto* old_cause = self->StartAssertNoThreadSuspension(
6653 "Copying ArtMethods for LinkInterfaceMethods");
6654 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
6655 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
6656 // they will already be null. This has the additional benefit that the declarer of a miranda
6657 // method will actually declare an abstract method.
6658 for (size_t i = ifcount; i != 0; ) {
6659 --i;
6660
6661 DCHECK_GE(i, 0u);
6662 DCHECK_LT(i, ifcount);
6663
6664 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6665 if (num_methods > 0) {
6666 StackHandleScope<2> hs2(self);
6667 const bool is_super = i < super_ifcount;
6668 const bool super_interface = is_super && extend_super_iftable;
6669 // We don't actually create or fill these tables for interfaces, we just copy some methods for
6670 // conflict methods. Just set this as nullptr in those cases.
6671 Handle<mirror::PointerArray> method_array(fill_tables
6672 ? hs2.NewHandle(iftable->GetMethodArray(i))
6673 : hs2.NewHandle<mirror::PointerArray>(nullptr));
6674
6675 ArraySlice<ArtMethod> input_virtual_methods;
6676 ScopedNullHandle<mirror::PointerArray> null_handle;
6677 Handle<mirror::PointerArray> input_vtable_array(null_handle);
6678 int32_t input_array_length = 0;
6679
6680 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
6681 // and confusing. Default methods should always look through all the superclasses
6682 // because they are the last choice of an implementation. We get around this by looking
6683 // at the super-classes iftable methods (copied into method_array previously) when we are
6684 // looking for the implementation of a super-interface method but that is rather dirty.
6685 bool using_virtuals;
6686 if (super_interface || is_interface) {
6687 // If we are overwriting a super class interface, try to only virtual methods instead of the
6688 // whole vtable.
6689 using_virtuals = true;
6690 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
6691 input_array_length = input_virtual_methods.size();
6692 } else {
6693 // For a new interface, however, we need the whole vtable in case a new
6694 // interface method is implemented in the whole superclass.
6695 using_virtuals = false;
6696 DCHECK(vtable.Get() != nullptr);
6697 input_vtable_array = vtable;
6698 input_array_length = input_vtable_array->GetLength();
6699 }
6700
6701 // For each method in interface
6702 for (size_t j = 0; j < num_methods; ++j) {
6703 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
6704 MethodNameAndSignatureComparator interface_name_comparator(
6705 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6706 uint32_t imt_index = GetIMTIndex(interface_method);
6707 ArtMethod** imt_ptr = &out_imt[imt_index];
6708 // For each method listed in the interface's method list, find the
6709 // matching method in our class's method list. We want to favor the
6710 // subclass over the superclass, which just requires walking
6711 // back from the end of the vtable. (This only matters if the
6712 // superclass defines a private method and this class redefines
6713 // it -- otherwise it would use the same vtable slot. In .dex files
6714 // those don't end up in the virtual method table, so it shouldn't
6715 // matter which direction we go. We walk it backward anyway.)
6716 //
6717 // To find defaults we need to do the same but also go over interfaces.
6718 bool found_impl = false;
6719 ArtMethod* vtable_impl = nullptr;
6720 for (int32_t k = input_array_length - 1; k >= 0; --k) {
6721 ArtMethod* vtable_method = using_virtuals ?
6722 &input_virtual_methods[k] :
6723 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
6724 ArtMethod* vtable_method_for_name_comparison =
6725 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
6726 if (interface_name_comparator.HasSameNameAndSignature(
6727 vtable_method_for_name_comparison)) {
6728 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
6729 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
6730 // allocations.
6731 self->EndAssertNoThreadSuspension(old_cause);
6732 ThrowIllegalAccessError(klass.Get(),
6733 "Method '%s' implementing interface method '%s' is not public",
6734 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str());
6735 return false;
6736 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
6737 // We might have a newer, better, default method for this, so we just skip it. If we
6738 // are still using this we will select it again when scanning for default methods. To
6739 // obviate the need to copy the method again we will make a note that we already found
6740 // a default here.
6741 // TODO This should be much cleaner.
6742 vtable_impl = vtable_method;
6743 break;
6744 } else {
6745 found_impl = true;
6746 if (LIKELY(fill_tables)) {
6747 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
6748 // Place method in imt if entry is empty, place conflict otherwise.
6749 SetIMTRef(unimplemented_method,
6750 imt_conflict_method,
6751 vtable_method,
6752 /*out*/out_new_conflict,
6753 /*out*/imt_ptr);
6754 }
6755 break;
6756 }
6757 }
6758 }
6759 // Continue on to the next method if we are done.
6760 if (LIKELY(found_impl)) {
6761 continue;
6762 } else if (LIKELY(super_interface)) {
6763 // Don't look for a default implementation when the super-method is implemented directly
6764 // by the class.
6765 //
6766 // See if we can use the superclasses method and skip searching everything else.
6767 // Note: !found_impl && super_interface
6768 CHECK(extend_super_iftable);
6769 // If this is a super_interface method it is possible we shouldn't override it because a
6770 // superclass could have implemented it directly. We get the method the superclass used
6771 // to implement this to know if we can override it with a default method. Doing this is
6772 // safe since we know that the super_iftable is filled in so we can simply pull it from
6773 // there. We don't bother if this is not a super-classes interface since in that case we
6774 // have scanned the entire vtable anyway and would have found it.
6775 // TODO This is rather dirty but it is faster than searching through the entire vtable
6776 // every time.
6777 ArtMethod* supers_method =
6778 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6779 DCHECK(supers_method != nullptr);
6780 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
6781 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
6782 // The method is not overridable by a default method (i.e. it is directly implemented
6783 // in some class). Therefore move onto the next interface method.
6784 continue;
6785 } else {
6786 // If the super-classes method is override-able by a default method we need to keep
6787 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
6788 // If it turns out not to be overridden and we did not keep track of it we might add it
6789 // to the vtable twice, causing corruption in this class and possibly any subclasses.
6790 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
6791 << "vtable_impl was " << PrettyMethod(vtable_impl) << " and not 'nullptr' or "
6792 << PrettyMethod(supers_method) << " as expected. IFTable appears to be corrupt!";
6793 vtable_impl = supers_method;
6794 }
6795 }
6796 // If we haven't found it yet we should search through the interfaces for default methods.
6797 ArtMethod* current_method = nullptr;
6798 switch (FindDefaultMethodImplementation(self,
6799 interface_method,
6800 klass,
6801 /*out*/¤t_method)) {
6802 case DefaultMethodSearchResult::kDefaultConflict: {
6803 // Default method conflict.
6804 DCHECK(current_method == nullptr);
6805 ArtMethod* default_conflict_method = nullptr;
6806 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6807 // We can reuse the method from the superclass, don't bother adding it to virtuals.
6808 default_conflict_method = vtable_impl;
6809 } else {
6810 // See if we already have a conflict method for this method.
6811 ArtMethod* preexisting_conflict = FindSameNameAndSignature(interface_name_comparator,
6812 default_conflict_methods);
6813 if (LIKELY(preexisting_conflict != nullptr)) {
6814 // We already have another conflict we can reuse.
6815 default_conflict_method = preexisting_conflict;
6816 } else {
6817 // Note that we do this even if we are an interface since we need to create this and
6818 // cannot reuse another classes.
6819 // Create a new conflict method for this to use.
6820 default_conflict_method =
6821 reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6822 new(default_conflict_method) ArtMethod(interface_method, image_pointer_size_);
6823 default_conflict_methods.push_back(default_conflict_method);
6824 }
6825 }
6826 current_method = default_conflict_method;
6827 break;
6828 } // case kDefaultConflict
6829 case DefaultMethodSearchResult::kDefaultFound: {
6830 DCHECK(current_method != nullptr);
6831 // Found a default method.
6832 if (vtable_impl != nullptr &&
6833 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6834 // We found a default method but it was the same one we already have from our
6835 // superclass. Don't bother adding it to our vtable again.
6836 current_method = vtable_impl;
6837 } else if (LIKELY(fill_tables)) {
6838 // Interfaces don't need to copy default methods since they don't have vtables.
6839 // Only record this default method if it is new to save space.
6840 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6841 // would make lookup for interface super much faster. (We would only need to scan
6842 // the iftable to find if there is a NSME or AME.)
6843 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator, default_methods);
6844 if (old == nullptr) {
6845 // We found a default method implementation and there were no conflicts.
6846 // Save the default method. We need to add it to the vtable.
6847 default_methods.push_back(current_method);
6848 } else {
6849 CHECK(old == current_method) << "Multiple default implementations selected!";
6850 }
6851 }
6852 break;
6853 } // case kDefaultFound
6854 case DefaultMethodSearchResult::kAbstractFound: {
6855 DCHECK(current_method == nullptr);
6856 // Abstract method masks all defaults.
6857 if (vtable_impl != nullptr &&
6858 vtable_impl->IsAbstract() &&
6859 !vtable_impl->IsDefaultConflicting()) {
6860 // We need to make this an abstract method but the version in the vtable already is so
6861 // don't do anything.
6862 current_method = vtable_impl;
6863 }
6864 break;
6865 } // case kAbstractFound
6866 }
6867 if (LIKELY(fill_tables)) {
6868 if (current_method == nullptr && !super_interface) {
6869 // We could not find an implementation for this method and since it is a brand new
6870 // interface we searched the entire vtable (and all default methods) for an
6871 // implementation but couldn't find one. We therefore need to make a miranda method.
6872 //
6873 // Find out if there is already a miranda method we can use.
6874 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6875 miranda_methods);
6876 if (miranda_method == nullptr) {
6877 DCHECK(interface_method->IsAbstract()) << PrettyMethod(interface_method);
6878 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6879 CHECK(miranda_method != nullptr);
6880 // Point the interface table at a phantom slot.
6881 new(miranda_method) ArtMethod(interface_method, image_pointer_size_);
6882 miranda_methods.push_back(miranda_method);
6883 }
6884 current_method = miranda_method;
6885 }
6886
6887 if (current_method != nullptr) {
6888 // We found a default method implementation. Record it in the iftable and IMT.
6889 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
6890 SetIMTRef(unimplemented_method,
6891 imt_conflict_method,
6892 current_method,
6893 /*out*/out_new_conflict,
6894 /*out*/imt_ptr);
6895 }
6896 }
6897 } // For each method in interface end.
6898 } // if (num_methods > 0)
6899 } // For each interface.
6900 const bool has_new_virtuals = !(miranda_methods.empty() &&
6901 default_methods.empty() &&
6902 default_conflict_methods.empty());
6903 // TODO don't extend virtuals of interface unless necessary (when is it?).
6904 if (has_new_virtuals) {
6905 DCHECK(!is_interface || (default_methods.empty() && miranda_methods.empty()))
6906 << "Interfaces should only have default-conflict methods appended to them.";
6907 VLOG(class_linker) << PrettyClass(klass.Get()) << ": miranda_methods=" << miranda_methods.size()
6908 << " default_methods=" << default_methods.size()
6909 << " default_conflict_methods=" << default_conflict_methods.size();
6910 const size_t old_method_count = klass->NumMethods();
6911 const size_t new_method_count = old_method_count +
6912 miranda_methods.size() +
6913 default_methods.size() +
6914 default_conflict_methods.size();
6915 // Attempt to realloc to save RAM if possible.
6916 LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr();
6917 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6918 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6919 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6920 // CopyFrom has internal read barriers.
6921 //
6922 // TODO We should maybe move some of this into mirror::Class or at least into another method.
6923 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6924 method_size,
6925 method_alignment);
6926 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
6927 method_size,
6928 method_alignment);
6929 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6930 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
6931 runtime->GetLinearAlloc()->Realloc(self, old_methods, old_methods_ptr_size, new_size));
6932 if (UNLIKELY(methods == nullptr)) {
6933 self->AssertPendingOOMException();
6934 self->EndAssertNoThreadSuspension(old_cause);
6935 return false;
6936 }
6937 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
6938 if (methods != old_methods) {
6939 // Maps from heap allocated miranda method to linear alloc miranda method.
6940 StrideIterator<ArtMethod> out = methods->begin(method_size, method_alignment);
6941 // Copy over the old methods.
6942 for (auto& m : klass->GetMethods(image_pointer_size_)) {
6943 move_table.emplace(&m, &*out);
6944 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
6945 // barriers when it copies.
6946 out->CopyFrom(&m, image_pointer_size_);
6947 ++out;
6948 }
6949 }
6950 StrideIterator<ArtMethod> out(methods->begin(method_size, method_alignment) + old_method_count);
6951 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
6952 // we want the roots of the miranda methods to get visited.
6953 for (ArtMethod* mir_method : miranda_methods) {
6954 ArtMethod& new_method = *out;
6955 new_method.CopyFrom(mir_method, image_pointer_size_);
6956 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
6957 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
6958 << "Miranda method should be abstract!";
6959 move_table.emplace(mir_method, &new_method);
6960 ++out;
6961 }
6962 // We need to copy the default methods into our own method table since the runtime requires that
6963 // every method on a class's vtable be in that respective class's virtual method table.
6964 // NOTE This means that two classes might have the same implementation of a method from the same
6965 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
6966 // default method found on a class with one found on the declaring interface directly and must
6967 // look at the declaring class to determine if they are the same.
6968 for (ArtMethod* def_method : default_methods) {
6969 ArtMethod& new_method = *out;
6970 new_method.CopyFrom(def_method, image_pointer_size_);
6971 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been verified
6972 // yet it shouldn't have methods that are skipping access checks.
6973 // TODO This is rather arbitrary. We should maybe support classes where only some of its
6974 // methods are skip_access_checks.
6975 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
6976 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
6977 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6978 move_table.emplace(def_method, &new_method);
6979 ++out;
6980 }
6981 for (ArtMethod* conf_method : default_conflict_methods) {
6982 ArtMethod& new_method = *out;
6983 new_method.CopyFrom(conf_method, image_pointer_size_);
6984 // This is a type of default method (there are default method impls, just a conflict) so mark
6985 // this as a default, non-abstract method, since thats what it is. Also clear the
6986 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
6987 // methods that are skipping access checks.
6988 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
6989 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
6990 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6991 DCHECK(new_method.IsDefaultConflicting());
6992 // The actual method might or might not be marked abstract since we just copied it from a
6993 // (possibly default) interface method. We need to set it entry point to be the bridge so that
6994 // the compiler will not invoke the implementation of whatever method we copied from.
6995 EnsureThrowsInvocationError(&new_method);
6996 move_table.emplace(conf_method, &new_method);
6997 ++out;
6998 }
6999 methods->SetSize(new_method_count);
7000 UpdateClassMethods(klass.Get(), methods);
7001 // Done copying methods, they are all roots in the class now, so we can end the no thread
7002 // suspension assert.
7003 self->EndAssertNoThreadSuspension(old_cause);
7004
7005 if (fill_tables) {
7006 // Update the vtable to the new method structures. We can skip this for interfaces since they
7007 // do not have vtables.
7008 const size_t old_vtable_count = vtable->GetLength();
7009 const size_t new_vtable_count = old_vtable_count +
7010 miranda_methods.size() +
7011 default_methods.size() +
7012 default_conflict_methods.size();
7013 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count)));
7014 if (UNLIKELY(vtable.Get() == nullptr)) {
7015 self->AssertPendingOOMException();
7016 return false;
7017 }
7018 out = methods->begin(method_size, method_alignment) + old_method_count;
7019 size_t vtable_pos = old_vtable_count;
7020 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7021 for (size_t i = old_method_count; i < new_method_count; ++i) {
7022 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7023 // fields are references into the dex file the method was defined in. Since the ArtMethod
7024 // does not store that information it uses declaring_class_->dex_cache_.
7025 out->SetMethodIndex(0xFFFF & vtable_pos);
7026 vtable->SetElementPtrSize(vtable_pos, &*out, image_pointer_size_);
7027 ++out;
7028 ++vtable_pos;
7029 }
7030 CHECK_EQ(vtable_pos, new_vtable_count);
7031 // Update old vtable methods. We use the default_translations map to figure out what each
7032 // vtable entry should be updated to, if they need to be at all.
7033 for (size_t i = 0; i < old_vtable_count; ++i) {
7034 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(
7035 i, image_pointer_size_);
7036 // Try and find what we need to change this method to.
7037 auto translation_it = default_translations.find(i);
7038 bool found_translation = false;
7039 if (translation_it != default_translations.end()) {
7040 if (translation_it->second.IsInConflict()) {
7041 // Find which conflict method we are to use for this method.
7042 MethodNameAndSignatureComparator old_method_comparator(
7043 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
7044 ArtMethod* new_conflict_method = FindSameNameAndSignature(old_method_comparator,
7045 default_conflict_methods);
7046 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7047 translated_method = new_conflict_method;
7048 } else if (translation_it->second.IsAbstract()) {
7049 // Find which miranda method we are to use for this method.
7050 MethodNameAndSignatureComparator old_method_comparator(
7051 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
7052 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7053 miranda_methods);
7054 DCHECK(miranda_method != nullptr);
7055 translated_method = miranda_method;
7056 } else {
7057 // Normal default method (changed from an older default or abstract interface method).
7058 DCHECK(translation_it->second.IsTranslation());
7059 translated_method = translation_it->second.GetTranslation();
7060 }
7061 found_translation = true;
7062 }
7063 DCHECK(translated_method != nullptr);
7064 auto it = move_table.find(translated_method);
7065 if (it != move_table.end()) {
7066 auto* new_method = it->second;
7067 DCHECK(new_method != nullptr);
7068 vtable->SetElementPtrSize(i, new_method, image_pointer_size_);
7069 } else {
7070 // If it was not going to be updated we wouldn't have put it into the default_translations
7071 // map.
7072 CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail.";
7073 }
7074 }
7075 klass->SetVTable(vtable.Get());
7076
7077 // Go fix up all the stale iftable pointers.
7078 for (size_t i = 0; i < ifcount; ++i) {
7079 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7080 auto* method_array = iftable->GetMethodArray(i);
7081 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7082 DCHECK(m != nullptr) << PrettyClass(klass.Get());
7083 auto it = move_table.find(m);
7084 if (it != move_table.end()) {
7085 auto* new_m = it->second;
7086 DCHECK(new_m != nullptr) << PrettyClass(klass.Get());
7087 method_array->SetElementPtrSize(j, new_m, image_pointer_size_);
7088 }
7089 }
7090 }
7091
7092 // Fix up IMT next
7093 for (size_t i = 0; i < ImTable::kSize; ++i) {
7094 auto it = move_table.find(out_imt[i]);
7095 if (it != move_table.end()) {
7096 out_imt[i] = it->second;
7097 }
7098 }
7099 }
7100
7101 // Check that there are no stale methods are in the dex cache array.
7102 if (kIsDebugBuild) {
7103 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods();
7104 for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
7105 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_);
7106 CHECK(move_table.find(m) == move_table.end() ||
7107 // The original versions of copied methods will still be present so allow those too.
7108 // Note that if the first check passes this might fail to GetDeclaringClass().
7109 std::find_if(m->GetDeclaringClass()->GetMethods(image_pointer_size_).begin(),
7110 m->GetDeclaringClass()->GetMethods(image_pointer_size_).end(),
7111 [m] (ArtMethod& meth) {
7112 return &meth == m;
7113 }) != m->GetDeclaringClass()->GetMethods(image_pointer_size_).end())
7114 << "Obsolete methods " << PrettyMethod(m) << " is in dex cache!";
7115 }
7116 }
7117 // Put some random garbage in old methods to help find stale pointers.
7118 if (methods != old_methods && old_methods != nullptr && kIsDebugBuild) {
7119 // Need to make sure the GC is not running since it could be scanning the methods we are
7120 // about to overwrite.
7121 ScopedThreadStateChange tsc(self, kSuspended);
7122 gc::ScopedGCCriticalSection gcs(self,
7123 gc::kGcCauseClassLinker,
7124 gc::kCollectorTypeClassLinker);
7125 memset(old_methods, 0xFEu, old_size);
7126 }
7127 } else {
7128 self->EndAssertNoThreadSuspension(old_cause);
7129 }
7130 if (kIsDebugBuild && !is_interface) {
7131 SanityCheckVTable(klass, image_pointer_size_);
7132 }
7133 return true;
7134 }
7135
LinkInstanceFields(Thread * self,Handle<mirror::Class> klass)7136 bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
7137 CHECK(klass.Get() != nullptr);
7138 return LinkFields(self, klass, false, nullptr);
7139 }
7140
LinkStaticFields(Thread * self,Handle<mirror::Class> klass,size_t * class_size)7141 bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
7142 CHECK(klass.Get() != nullptr);
7143 return LinkFields(self, klass, true, class_size);
7144 }
7145
7146 struct LinkFieldsComparator {
SHARED_REQUIRESart::LinkFieldsComparator7147 explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) {
7148 }
7149 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
operator ()art::LinkFieldsComparator7150 bool operator()(ArtField* field1, ArtField* field2)
7151 NO_THREAD_SAFETY_ANALYSIS {
7152 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
7153 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7154 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
7155 if (type1 != type2) {
7156 if (type1 == Primitive::kPrimNot) {
7157 // Reference always goes first.
7158 return true;
7159 }
7160 if (type2 == Primitive::kPrimNot) {
7161 // Reference always goes first.
7162 return false;
7163 }
7164 size_t size1 = Primitive::ComponentSize(type1);
7165 size_t size2 = Primitive::ComponentSize(type2);
7166 if (size1 != size2) {
7167 // Larger primitive types go first.
7168 return size1 > size2;
7169 }
7170 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7171 return type1 < type2;
7172 }
7173 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7174 // by name and for equal names by type id index.
7175 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7176 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
7177 }
7178 };
7179
LinkFields(Thread * self,Handle<mirror::Class> klass,bool is_static,size_t * class_size)7180 bool ClassLinker::LinkFields(Thread* self,
7181 Handle<mirror::Class> klass,
7182 bool is_static,
7183 size_t* class_size) {
7184 self->AllowThreadSuspension();
7185 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
7186 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7187 klass->GetIFieldsPtr();
7188
7189 // Initialize field_offset
7190 MemberOffset field_offset(0);
7191 if (is_static) {
7192 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
7193 } else {
7194 mirror::Class* super_class = klass->GetSuperClass();
7195 if (super_class != nullptr) {
7196 CHECK(super_class->IsResolved())
7197 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
7198 field_offset = MemberOffset(super_class->GetObjectSize());
7199 }
7200 }
7201
7202 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
7203
7204 // we want a relatively stable order so that adding new fields
7205 // minimizes disruption of C++ version such as Class and Method.
7206 //
7207 // The overall sort order order is:
7208 // 1) All object reference fields, sorted alphabetically.
7209 // 2) All java long (64-bit) integer fields, sorted alphabetically.
7210 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7211 // 4) All java int (32-bit) integer fields, sorted alphabetically.
7212 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7213 // 6) All java char (16-bit) integer fields, sorted alphabetically.
7214 // 7) All java short (16-bit) integer fields, sorted alphabetically.
7215 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7216 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7217 //
7218 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7219 // in the memory layout of the structure. See ShuffleForward for how this is done.
7220 std::deque<ArtField*> grouped_and_sorted_fields;
7221 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
7222 "Naked ArtField references in deque");
7223 for (size_t i = 0; i < num_fields; i++) {
7224 grouped_and_sorted_fields.push_back(&fields->At(i));
7225 }
7226 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7227 LinkFieldsComparator());
7228
7229 // References should be at the front.
7230 size_t current_field = 0;
7231 size_t num_reference_fields = 0;
7232 FieldGaps gaps;
7233
7234 for (; current_field < num_fields; current_field++) {
7235 ArtField* field = grouped_and_sorted_fields.front();
7236 Primitive::Type type = field->GetTypeAsPrimitiveType();
7237 bool isPrimitive = type != Primitive::kPrimNot;
7238 if (isPrimitive) {
7239 break; // past last reference, move on to the next phase
7240 }
7241 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7242 field_offset.Uint32Value()))) {
7243 MemberOffset old_offset = field_offset;
7244 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7245 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7246 }
7247 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
7248 grouped_and_sorted_fields.pop_front();
7249 num_reference_fields++;
7250 field->SetOffset(field_offset);
7251 field_offset = MemberOffset(field_offset.Uint32Value() +
7252 sizeof(mirror::HeapReference<mirror::Object>));
7253 }
7254 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7255 // otherwise we could end up with suboptimal gap fills.
7256 ShuffleForward<8>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7257 ShuffleForward<4>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7258 ShuffleForward<2>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7259 ShuffleForward<1>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7260 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7261 " fields.";
7262 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
7263
7264 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
7265 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
7266 // We know there are no non-reference fields in the Reference classes, and we know
7267 // that 'referent' is alphabetically last, so this is easy...
7268 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
7269 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
7270 << PrettyClass(klass.Get());
7271 --num_reference_fields;
7272 }
7273
7274 size_t size = field_offset.Uint32Value();
7275 // Update klass
7276 if (is_static) {
7277 klass->SetNumReferenceStaticFields(num_reference_fields);
7278 *class_size = size;
7279 } else {
7280 klass->SetNumReferenceInstanceFields(num_reference_fields);
7281 mirror::Class* super_class = klass->GetSuperClass();
7282 if (num_reference_fields == 0 || super_class == nullptr) {
7283 // object has one reference field, klass, but we ignore it since we always visit the class.
7284 // super_class is null iff the class is java.lang.Object.
7285 if (super_class == nullptr ||
7286 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7287 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
7288 }
7289 }
7290 if (kIsDebugBuild) {
7291 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7292 size_t total_reference_instance_fields = 0;
7293 mirror::Class* cur_super = klass.Get();
7294 while (cur_super != nullptr) {
7295 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7296 cur_super = cur_super->GetSuperClass();
7297 }
7298 if (super_class == nullptr) {
7299 CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get());
7300 } else {
7301 // Check that there is at least num_reference_fields other than Object.class.
7302 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
7303 << PrettyClass(klass.Get());
7304 }
7305 }
7306 if (!klass->IsVariableSize()) {
7307 std::string temp;
7308 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7309 size_t previous_size = klass->GetObjectSize();
7310 if (previous_size != 0) {
7311 // Make sure that we didn't originally have an incorrect size.
7312 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
7313 }
7314 klass->SetObjectSize(size);
7315 }
7316 }
7317
7318 if (kIsDebugBuild) {
7319 // Make sure that the fields array is ordered by name but all reference
7320 // offsets are at the beginning as far as alignment allows.
7321 MemberOffset start_ref_offset = is_static
7322 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
7323 : klass->GetFirstReferenceInstanceFieldOffset();
7324 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7325 num_reference_fields *
7326 sizeof(mirror::HeapReference<mirror::Object>));
7327 MemberOffset current_ref_offset = start_ref_offset;
7328 for (size_t i = 0; i < num_fields; i++) {
7329 ArtField* field = &fields->At(i);
7330 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
7331 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
7332 << field->GetOffsetDuringLinking();
7333 if (i != 0) {
7334 ArtField* const prev_field = &fields->At(i - 1);
7335 // NOTE: The field names can be the same. This is not possible in the Java language
7336 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
7337 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
7338 }
7339 Primitive::Type type = field->GetTypeAsPrimitiveType();
7340 bool is_primitive = type != Primitive::kPrimNot;
7341 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7342 strcmp("referent", field->GetName()) == 0) {
7343 is_primitive = true; // We lied above, so we have to expect a lie here.
7344 }
7345 MemberOffset offset = field->GetOffsetDuringLinking();
7346 if (is_primitive) {
7347 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7348 // Shuffled before references.
7349 size_t type_size = Primitive::ComponentSize(type);
7350 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7351 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7352 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7353 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7354 }
7355 } else {
7356 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7357 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7358 sizeof(mirror::HeapReference<mirror::Object>));
7359 }
7360 }
7361 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7362 }
7363 return true;
7364 }
7365
7366 // Set the bitmap of reference instance field offsets.
CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)7367 void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
7368 uint32_t reference_offsets = 0;
7369 mirror::Class* super_class = klass->GetSuperClass();
7370 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
7371 if (super_class != nullptr) {
7372 reference_offsets = super_class->GetReferenceInstanceOffsets();
7373 // Compute reference offsets unless our superclass overflowed.
7374 if (reference_offsets != mirror::Class::kClassWalkSuper) {
7375 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
7376 if (num_reference_fields != 0u) {
7377 // All of the fields that contain object references are guaranteed be grouped in memory
7378 // starting at an appropriately aligned address after super class object data.
7379 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7380 sizeof(mirror::HeapReference<mirror::Object>));
7381 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
7382 sizeof(mirror::HeapReference<mirror::Object>);
7383 if (start_bit + num_reference_fields > 32) {
7384 reference_offsets = mirror::Class::kClassWalkSuper;
7385 } else {
7386 reference_offsets |= (0xffffffffu << start_bit) &
7387 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
7388 }
7389 }
7390 }
7391 }
7392 klass->SetReferenceInstanceOffsets(reference_offsets);
7393 }
7394
ResolveString(const DexFile & dex_file,uint32_t string_idx,Handle<mirror::DexCache> dex_cache)7395 mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
7396 uint32_t string_idx,
7397 Handle<mirror::DexCache> dex_cache) {
7398 DCHECK(dex_cache.Get() != nullptr);
7399 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
7400 if (resolved != nullptr) {
7401 return resolved;
7402 }
7403 uint32_t utf16_length;
7404 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
7405 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
7406 dex_cache->SetResolvedString(string_idx, string);
7407 return string;
7408 }
7409
LookupString(const DexFile & dex_file,uint32_t string_idx,Handle<mirror::DexCache> dex_cache)7410 mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
7411 uint32_t string_idx,
7412 Handle<mirror::DexCache> dex_cache) {
7413 DCHECK(dex_cache.Get() != nullptr);
7414 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
7415 if (resolved != nullptr) {
7416 return resolved;
7417 }
7418 uint32_t utf16_length;
7419 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
7420 mirror::String* string = intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
7421 if (string != nullptr) {
7422 dex_cache->SetResolvedString(string_idx, string);
7423 }
7424 return string;
7425 }
7426
ResolveType(const DexFile & dex_file,uint16_t type_idx,mirror::Class * referrer)7427 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7428 uint16_t type_idx,
7429 mirror::Class* referrer) {
7430 StackHandleScope<2> hs(Thread::Current());
7431 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7432 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
7433 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7434 }
7435
ResolveType(const DexFile & dex_file,uint16_t type_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7436 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7437 uint16_t type_idx,
7438 Handle<mirror::DexCache> dex_cache,
7439 Handle<mirror::ClassLoader> class_loader) {
7440 DCHECK(dex_cache.Get() != nullptr);
7441 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
7442 if (resolved == nullptr) {
7443 Thread* self = Thread::Current();
7444 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7445 resolved = FindClass(self, descriptor, class_loader);
7446 if (resolved != nullptr) {
7447 // TODO: we used to throw here if resolved's class loader was not the
7448 // boot class loader. This was to permit different classes with the
7449 // same name to be loaded simultaneously by different loaders
7450 dex_cache->SetResolvedType(type_idx, resolved);
7451 } else {
7452 CHECK(self->IsExceptionPending())
7453 << "Expected pending exception for failed resolution of: " << descriptor;
7454 // Convert a ClassNotFoundException to a NoClassDefFoundError.
7455 StackHandleScope<1> hs(self);
7456 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7457 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7458 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
7459 self->ClearException();
7460 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7461 self->GetException()->SetCause(cause.Get());
7462 }
7463 }
7464 }
7465 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
7466 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
7467 return resolved;
7468 }
7469
7470 template <ClassLinker::ResolveMode kResolveMode>
ResolveMethod(const DexFile & dex_file,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,ArtMethod * referrer,InvokeType type)7471 ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7472 uint32_t method_idx,
7473 Handle<mirror::DexCache> dex_cache,
7474 Handle<mirror::ClassLoader> class_loader,
7475 ArtMethod* referrer,
7476 InvokeType type) {
7477 DCHECK(dex_cache.Get() != nullptr);
7478 // Check for hit in the dex cache.
7479 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
7480 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
7481 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7482 if (kResolveMode == ClassLinker::kForceICCECheck) {
7483 if (resolved->CheckIncompatibleClassChange(type)) {
7484 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7485 return nullptr;
7486 }
7487 }
7488 return resolved;
7489 }
7490 // Fail, get the declaring class.
7491 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7492 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7493 if (klass == nullptr) {
7494 DCHECK(Thread::Current()->IsExceptionPending());
7495 return nullptr;
7496 }
7497 // Scan using method_idx, this saves string compares but will only hit for matching dex
7498 // caches/files.
7499 switch (type) {
7500 case kDirect: // Fall-through.
7501 case kStatic:
7502 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7503 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7504 break;
7505 case kInterface:
7506 // We have to check whether the method id really belongs to an interface (dex static bytecode
7507 // constraint A15). Otherwise you must not invoke-interface on it.
7508 //
7509 // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod
7510 // assumes that the given type is an interface, and will check the interface table if the
7511 // method isn't declared in the class. So it may find an interface method (usually by name
7512 // in the handling below, but we do the constraint check early). In that case,
7513 // CheckIncompatibleClassChange will succeed (as it is called on an interface method)
7514 // unexpectedly.
7515 // Example:
7516 // interface I {
7517 // foo()
7518 // }
7519 // class A implements I {
7520 // ...
7521 // }
7522 // class B extends A {
7523 // ...
7524 // }
7525 // invoke-interface B.foo
7526 // -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method)
7527 if (UNLIKELY(!klass->IsInterface())) {
7528 ThrowIncompatibleClassChangeError(klass,
7529 "Found class %s, but interface was expected",
7530 PrettyDescriptor(klass).c_str());
7531 return nullptr;
7532 } else {
7533 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7534 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7535 }
7536 break;
7537 case kSuper:
7538 if (klass->IsInterface()) {
7539 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7540 } else {
7541 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7542 }
7543 break;
7544 case kVirtual:
7545 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7546 break;
7547 default:
7548 LOG(FATAL) << "Unreachable - invocation type: " << type;
7549 UNREACHABLE();
7550 }
7551 if (resolved == nullptr) {
7552 // Search by name, which works across dex files.
7553 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7554 const Signature signature = dex_file.GetMethodSignature(method_id);
7555 switch (type) {
7556 case kDirect: // Fall-through.
7557 case kStatic:
7558 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7559 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7560 break;
7561 case kInterface:
7562 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7563 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7564 break;
7565 case kSuper:
7566 if (klass->IsInterface()) {
7567 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7568 } else {
7569 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7570 }
7571 break;
7572 case kVirtual:
7573 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7574 break;
7575 }
7576 }
7577 // If we found a method, check for incompatible class changes.
7578 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
7579 // Be a good citizen and update the dex cache to speed subsequent calls.
7580 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
7581 return resolved;
7582 } else {
7583 // If we had a method, it's an incompatible-class-change error.
7584 if (resolved != nullptr) {
7585 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7586 } else {
7587 // We failed to find the method which means either an access error, an incompatible class
7588 // change, or no such method. First try to find the method among direct and virtual methods.
7589 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7590 const Signature signature = dex_file.GetMethodSignature(method_id);
7591 switch (type) {
7592 case kDirect:
7593 case kStatic:
7594 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7595 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
7596 // have had a resolved method before, which triggers the "true" branch above.
7597 break;
7598 case kInterface:
7599 case kVirtual:
7600 case kSuper:
7601 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7602 break;
7603 }
7604
7605 // If we found something, check that it can be accessed by the referrer.
7606 bool exception_generated = false;
7607 if (resolved != nullptr && referrer != nullptr) {
7608 mirror::Class* methods_class = resolved->GetDeclaringClass();
7609 mirror::Class* referring_class = referrer->GetDeclaringClass();
7610 if (!referring_class->CanAccess(methods_class)) {
7611 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
7612 methods_class,
7613 resolved,
7614 type);
7615 exception_generated = true;
7616 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
7617 ThrowIllegalAccessErrorMethod(referring_class, resolved);
7618 exception_generated = true;
7619 }
7620 }
7621 if (!exception_generated) {
7622 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
7623 // interface methods and throw if we find the method there. If we find nothing, throw a
7624 // NoSuchMethodError.
7625 switch (type) {
7626 case kDirect:
7627 case kStatic:
7628 if (resolved != nullptr) {
7629 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
7630 } else {
7631 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7632 if (resolved != nullptr) {
7633 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
7634 } else {
7635 ThrowNoSuchMethodError(type, klass, name, signature);
7636 }
7637 }
7638 break;
7639 case kInterface:
7640 if (resolved != nullptr) {
7641 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7642 } else {
7643 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7644 if (resolved != nullptr) {
7645 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
7646 } else {
7647 ThrowNoSuchMethodError(type, klass, name, signature);
7648 }
7649 }
7650 break;
7651 case kSuper:
7652 if (resolved != nullptr) {
7653 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7654 } else {
7655 ThrowNoSuchMethodError(type, klass, name, signature);
7656 }
7657 break;
7658 case kVirtual:
7659 if (resolved != nullptr) {
7660 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7661 } else {
7662 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7663 if (resolved != nullptr) {
7664 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
7665 } else {
7666 ThrowNoSuchMethodError(type, klass, name, signature);
7667 }
7668 }
7669 break;
7670 }
7671 }
7672 }
7673 Thread::Current()->AssertPendingException();
7674 return nullptr;
7675 }
7676 }
7677
ResolveMethodWithoutInvokeType(const DexFile & dex_file,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7678 ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
7679 uint32_t method_idx,
7680 Handle<mirror::DexCache> dex_cache,
7681 Handle<mirror::ClassLoader> class_loader) {
7682 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
7683 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
7684 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7685 return resolved;
7686 }
7687 // Fail, get the declaring class.
7688 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7689 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7690 if (klass == nullptr) {
7691 Thread::Current()->AssertPendingException();
7692 return nullptr;
7693 }
7694 if (klass->IsInterface()) {
7695 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass);
7696 return nullptr;
7697 }
7698
7699 // Search both direct and virtual methods
7700 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7701 if (resolved == nullptr) {
7702 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7703 }
7704
7705 return resolved;
7706 }
7707
ResolveField(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool is_static)7708 ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
7709 uint32_t field_idx,
7710 Handle<mirror::DexCache> dex_cache,
7711 Handle<mirror::ClassLoader> class_loader,
7712 bool is_static) {
7713 DCHECK(dex_cache.Get() != nullptr);
7714 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
7715 if (resolved != nullptr) {
7716 return resolved;
7717 }
7718 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
7719 Thread* const self = Thread::Current();
7720 StackHandleScope<1> hs(self);
7721 Handle<mirror::Class> klass(
7722 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
7723 if (klass.Get() == nullptr) {
7724 DCHECK(Thread::Current()->IsExceptionPending());
7725 return nullptr;
7726 }
7727
7728 if (is_static) {
7729 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
7730 } else {
7731 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
7732 }
7733
7734 if (resolved == nullptr) {
7735 const char* name = dex_file.GetFieldName(field_id);
7736 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
7737 if (is_static) {
7738 resolved = mirror::Class::FindStaticField(self, klass, name, type);
7739 } else {
7740 resolved = klass->FindInstanceField(name, type);
7741 }
7742 if (resolved == nullptr) {
7743 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
7744 return nullptr;
7745 }
7746 }
7747 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
7748 return resolved;
7749 }
7750
ResolveFieldJLS(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7751 ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
7752 uint32_t field_idx,
7753 Handle<mirror::DexCache> dex_cache,
7754 Handle<mirror::ClassLoader> class_loader) {
7755 DCHECK(dex_cache.Get() != nullptr);
7756 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
7757 if (resolved != nullptr) {
7758 return resolved;
7759 }
7760 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
7761 Thread* self = Thread::Current();
7762 StackHandleScope<1> hs(self);
7763 Handle<mirror::Class> klass(
7764 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
7765 if (klass.Get() == nullptr) {
7766 DCHECK(Thread::Current()->IsExceptionPending());
7767 return nullptr;
7768 }
7769
7770 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
7771 StringPiece type(dex_file.StringDataByIdx(
7772 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
7773 resolved = mirror::Class::FindField(self, klass, name, type);
7774 if (resolved != nullptr) {
7775 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
7776 } else {
7777 ThrowNoSuchFieldError("", klass.Get(), type, name);
7778 }
7779 return resolved;
7780 }
7781
MethodShorty(uint32_t method_idx,ArtMethod * referrer,uint32_t * length)7782 const char* ClassLinker::MethodShorty(uint32_t method_idx,
7783 ArtMethod* referrer,
7784 uint32_t* length) {
7785 mirror::Class* declaring_class = referrer->GetDeclaringClass();
7786 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
7787 const DexFile& dex_file = *dex_cache->GetDexFile();
7788 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7789 return dex_file.GetMethodShorty(method_id, length);
7790 }
7791
7792 class DumpClassVisitor : public ClassVisitor {
7793 public:
DumpClassVisitor(int flags)7794 explicit DumpClassVisitor(int flags) : flags_(flags) {}
7795
operator ()(mirror::Class * klass)7796 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
7797 klass->DumpClass(LOG(ERROR), flags_);
7798 return true;
7799 }
7800
7801 private:
7802 const int flags_;
7803 };
7804
DumpAllClasses(int flags)7805 void ClassLinker::DumpAllClasses(int flags) {
7806 DumpClassVisitor visitor(flags);
7807 VisitClasses(&visitor);
7808 }
7809
CreateOatMethod(const void * code)7810 static OatFile::OatMethod CreateOatMethod(const void* code) {
7811 CHECK(code != nullptr);
7812 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
7813 base -= sizeof(void*); // Move backward so that code_offset != 0.
7814 const uint32_t code_offset = sizeof(void*);
7815 return OatFile::OatMethod(base, code_offset);
7816 }
7817
IsQuickResolutionStub(const void * entry_point) const7818 bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
7819 return (entry_point == GetQuickResolutionStub()) ||
7820 (quick_resolution_trampoline_ == entry_point);
7821 }
7822
IsQuickToInterpreterBridge(const void * entry_point) const7823 bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
7824 return (entry_point == GetQuickToInterpreterBridge()) ||
7825 (quick_to_interpreter_bridge_trampoline_ == entry_point);
7826 }
7827
IsQuickGenericJniStub(const void * entry_point) const7828 bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
7829 return (entry_point == GetQuickGenericJniStub()) ||
7830 (quick_generic_jni_trampoline_ == entry_point);
7831 }
7832
GetRuntimeQuickGenericJniStub() const7833 const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
7834 return GetQuickGenericJniStub();
7835 }
7836
SetEntryPointsToCompiledCode(ArtMethod * method,const void * method_code) const7837 void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method,
7838 const void* method_code) const {
7839 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
7840 oat_method.LinkMethod(method);
7841 }
7842
SetEntryPointsToInterpreter(ArtMethod * method) const7843 void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
7844 if (!method->IsNative()) {
7845 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
7846 } else {
7847 const void* quick_method_code = GetQuickGenericJniStub();
7848 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
7849 oat_method.LinkMethod(method);
7850 }
7851 }
7852
DumpForSigQuit(std::ostream & os)7853 void ClassLinker::DumpForSigQuit(std::ostream& os) {
7854 ScopedObjectAccess soa(Thread::Current());
7855 if (dex_cache_boot_image_class_lookup_required_) {
7856 AddBootImageClassesToClassTable();
7857 }
7858 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
7859 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
7860 << NumNonZygoteClasses() << "\n";
7861 }
7862
7863 class CountClassesVisitor : public ClassLoaderVisitor {
7864 public:
CountClassesVisitor()7865 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
7866
Visit(mirror::ClassLoader * class_loader)7867 void Visit(mirror::ClassLoader* class_loader)
7868 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
7869 ClassTable* const class_table = class_loader->GetClassTable();
7870 if (class_table != nullptr) {
7871 num_zygote_classes += class_table->NumZygoteClasses();
7872 num_non_zygote_classes += class_table->NumNonZygoteClasses();
7873 }
7874 }
7875
7876 size_t num_zygote_classes;
7877 size_t num_non_zygote_classes;
7878 };
7879
NumZygoteClasses() const7880 size_t ClassLinker::NumZygoteClasses() const {
7881 CountClassesVisitor visitor;
7882 VisitClassLoaders(&visitor);
7883 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses();
7884 }
7885
NumNonZygoteClasses() const7886 size_t ClassLinker::NumNonZygoteClasses() const {
7887 CountClassesVisitor visitor;
7888 VisitClassLoaders(&visitor);
7889 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses();
7890 }
7891
NumLoadedClasses()7892 size_t ClassLinker::NumLoadedClasses() {
7893 if (dex_cache_boot_image_class_lookup_required_) {
7894 AddBootImageClassesToClassTable();
7895 }
7896 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
7897 // Only return non zygote classes since these are the ones which apps which care about.
7898 return NumNonZygoteClasses();
7899 }
7900
GetClassesLockOwner()7901 pid_t ClassLinker::GetClassesLockOwner() {
7902 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
7903 }
7904
GetDexLockOwner()7905 pid_t ClassLinker::GetDexLockOwner() {
7906 return dex_lock_.GetExclusiveOwnerTid();
7907 }
7908
SetClassRoot(ClassRoot class_root,mirror::Class * klass)7909 void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
7910 DCHECK(!init_done_);
7911
7912 DCHECK(klass != nullptr);
7913 DCHECK(klass->GetClassLoader() == nullptr);
7914
7915 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
7916 DCHECK(class_roots != nullptr);
7917 DCHECK(class_roots->Get(class_root) == nullptr);
7918 class_roots->Set<false>(class_root, klass);
7919 }
7920
GetClassRootDescriptor(ClassRoot class_root)7921 const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
7922 static const char* class_roots_descriptors[] = {
7923 "Ljava/lang/Class;",
7924 "Ljava/lang/Object;",
7925 "[Ljava/lang/Class;",
7926 "[Ljava/lang/Object;",
7927 "Ljava/lang/String;",
7928 "Ljava/lang/DexCache;",
7929 "Ljava/lang/ref/Reference;",
7930 "Ljava/lang/reflect/Constructor;",
7931 "Ljava/lang/reflect/Field;",
7932 "Ljava/lang/reflect/Method;",
7933 "Ljava/lang/reflect/Proxy;",
7934 "[Ljava/lang/String;",
7935 "[Ljava/lang/reflect/Constructor;",
7936 "[Ljava/lang/reflect/Field;",
7937 "[Ljava/lang/reflect/Method;",
7938 "Ljava/lang/ClassLoader;",
7939 "Ljava/lang/Throwable;",
7940 "Ljava/lang/ClassNotFoundException;",
7941 "Ljava/lang/StackTraceElement;",
7942 "Z",
7943 "B",
7944 "C",
7945 "D",
7946 "F",
7947 "I",
7948 "J",
7949 "S",
7950 "V",
7951 "[Z",
7952 "[B",
7953 "[C",
7954 "[D",
7955 "[F",
7956 "[I",
7957 "[J",
7958 "[S",
7959 "[Ljava/lang/StackTraceElement;",
7960 };
7961 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
7962 "Mismatch between class descriptors and class-root enum");
7963
7964 const char* descriptor = class_roots_descriptors[class_root];
7965 CHECK(descriptor != nullptr);
7966 return descriptor;
7967 }
7968
CreatePathClassLoader(Thread * self,const std::vector<const DexFile * > & dex_files)7969 jobject ClassLinker::CreatePathClassLoader(Thread* self,
7970 const std::vector<const DexFile*>& dex_files) {
7971 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
7972 // We could move the jobject to the callers, but all call-sites do this...
7973 ScopedObjectAccessUnchecked soa(self);
7974
7975 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
7976 StackHandleScope<10> hs(self);
7977
7978 ArtField* dex_elements_field =
7979 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
7980
7981 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
7982 DCHECK(dex_elements_class != nullptr);
7983 DCHECK(dex_elements_class->IsArrayClass());
7984 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
7985 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
7986 Handle<mirror::Class> h_dex_element_class =
7987 hs.NewHandle(dex_elements_class->GetComponentType());
7988
7989 ArtField* element_file_field =
7990 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
7991 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
7992
7993 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
7994 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
7995
7996 ArtField* file_name_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
7997 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
7998
7999 // Fill the elements array.
8000 int32_t index = 0;
8001 for (const DexFile* dex_file : dex_files) {
8002 StackHandleScope<4> hs2(self);
8003
8004 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
8005 // oat file but we can leave it null.
8006 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
8007 self,
8008 kDexFileIndexStart + 1));
8009 DCHECK(h_long_array.Get() != nullptr);
8010 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
8011
8012 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
8013 cookie_field->GetDeclaringClass()->AllocObject(self));
8014 DCHECK(h_dex_file.Get() != nullptr);
8015 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
8016
8017 Handle<mirror::String> h_file_name = hs2.NewHandle(
8018 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
8019 DCHECK(h_file_name.Get() != nullptr);
8020 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
8021
8022 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
8023 DCHECK(h_element.Get() != nullptr);
8024 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
8025
8026 h_dex_elements->Set(index, h_element.Get());
8027 index++;
8028 }
8029 DCHECK_EQ(index, h_dex_elements->GetLength());
8030
8031 // Create DexPathList.
8032 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
8033 dex_elements_field->GetDeclaringClass()->AllocObject(self));
8034 DCHECK(h_dex_path_list.Get() != nullptr);
8035 // Set elements.
8036 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
8037
8038 // Create PathClassLoader.
8039 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
8040 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
8041 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
8042 h_path_class_class->AllocObject(self));
8043 DCHECK(h_path_class_loader.Get() != nullptr);
8044 // Set DexPathList.
8045 ArtField* path_list_field =
8046 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
8047 DCHECK(path_list_field != nullptr);
8048 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
8049
8050 // Make a pretend boot-classpath.
8051 // TODO: Should we scan the image?
8052 ArtField* const parent_field =
8053 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
8054 "Ljava/lang/ClassLoader;");
8055 DCHECK(parent_field != nullptr);
8056 mirror::Object* boot_cl =
8057 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
8058 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
8059
8060 // Make it a global ref and return.
8061 ScopedLocalRef<jobject> local_ref(
8062 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
8063 return soa.Env()->NewGlobalRef(local_ref.get());
8064 }
8065
CreateRuntimeMethod(LinearAlloc * linear_alloc)8066 ArtMethod* ClassLinker::CreateRuntimeMethod(LinearAlloc* linear_alloc) {
8067 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
8068 const size_t method_size = ArtMethod::Size(image_pointer_size_);
8069 LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray(
8070 Thread::Current(),
8071 linear_alloc,
8072 1);
8073 ArtMethod* method = &method_array->At(0, method_size, method_alignment);
8074 CHECK(method != nullptr);
8075 method->SetDexMethodIndex(DexFile::kDexNoIndex);
8076 CHECK(method->IsRuntimeMethod());
8077 return method;
8078 }
8079
DropFindArrayClassCache()8080 void ClassLinker::DropFindArrayClassCache() {
8081 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
8082 find_array_class_cache_next_victim_ = 0;
8083 }
8084
ClearClassTableStrongRoots() const8085 void ClassLinker::ClearClassTableStrongRoots() const {
8086 Thread* const self = Thread::Current();
8087 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8088 for (const ClassLoaderData& data : class_loaders_) {
8089 if (data.class_table != nullptr) {
8090 data.class_table->ClearStrongRoots();
8091 }
8092 }
8093 }
8094
VisitClassLoaders(ClassLoaderVisitor * visitor) const8095 void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
8096 Thread* const self = Thread::Current();
8097 for (const ClassLoaderData& data : class_loaders_) {
8098 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
8099 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
8100 if (class_loader != nullptr) {
8101 visitor->Visit(class_loader);
8102 }
8103 }
8104 }
8105
InsertDexFileInToClassLoader(mirror::Object * dex_file,mirror::ClassLoader * class_loader)8106 void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file,
8107 mirror::ClassLoader* class_loader) {
8108 DCHECK(dex_file != nullptr);
8109 Thread* const self = Thread::Current();
8110 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8111 ClassTable* const table = ClassTableForClassLoader(class_loader);
8112 DCHECK(table != nullptr);
8113 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
8114 // It was not already inserted, perform the write barrier to let the GC know the class loader's
8115 // class table was modified.
8116 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8117 }
8118 }
8119
CleanupClassLoaders()8120 void ClassLinker::CleanupClassLoaders() {
8121 Thread* const self = Thread::Current();
8122 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8123 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8124 const ClassLoaderData& data = *it;
8125 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
8126 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
8127 if (class_loader != nullptr) {
8128 ++it;
8129 } else {
8130 VLOG(class_linker) << "Freeing class loader";
8131 DeleteClassLoader(self, data);
8132 it = class_loaders_.erase(it);
8133 }
8134 }
8135 }
8136
GetResolvedClasses(bool ignore_boot_classes)8137 std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
8138 ScopedTrace trace(__PRETTY_FUNCTION__);
8139 ScopedObjectAccess soa(Thread::Current());
8140 ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__);
8141 std::set<DexCacheResolvedClasses> ret;
8142 VLOG(class_linker) << "Collecting resolved classes";
8143 const uint64_t start_time = NanoTime();
8144 ReaderMutexLock mu(soa.Self(), *DexLock());
8145 // Loop through all the dex caches and inspect resolved classes.
8146 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8147 if (soa.Self()->IsJWeakCleared(data.weak_root)) {
8148 continue;
8149 }
8150 mirror::DexCache* dex_cache =
8151 down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root));
8152 if (dex_cache == nullptr) {
8153 continue;
8154 }
8155 const DexFile* dex_file = dex_cache->GetDexFile();
8156 const std::string& location = dex_file->GetLocation();
8157 const size_t num_class_defs = dex_file->NumClassDefs();
8158 // Use the resolved types, this will miss array classes.
8159 const size_t num_types = dex_file->NumTypeIds();
8160 VLOG(class_linker) << "Collecting class profile for dex file " << location
8161 << " types=" << num_types << " class_defs=" << num_class_defs;
8162 DexCacheResolvedClasses resolved_classes(dex_file->GetLocation(),
8163 dex_file->GetBaseLocation(),
8164 dex_file->GetLocationChecksum());
8165 size_t num_resolved = 0;
8166 std::unordered_set<uint16_t> class_set;
8167 CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
8168 for (size_t i = 0; i < num_types; ++i) {
8169 mirror::Class* klass = dex_cache->GetResolvedType(i);
8170 // Filter out null class loader since that is the boot class loader.
8171 if (klass == nullptr || (ignore_boot_classes && klass->GetClassLoader() == nullptr)) {
8172 continue;
8173 }
8174 ++num_resolved;
8175 DCHECK(!klass->IsProxyClass());
8176 if (!klass->IsResolved()) {
8177 DCHECK(klass->IsErroneous());
8178 continue;
8179 }
8180 mirror::DexCache* klass_dex_cache = klass->GetDexCache();
8181 if (klass_dex_cache == dex_cache) {
8182 const size_t class_def_idx = klass->GetDexClassDefIndex();
8183 DCHECK(klass->IsResolved());
8184 CHECK_LT(class_def_idx, num_class_defs);
8185 class_set.insert(class_def_idx);
8186 }
8187 }
8188
8189 if (!class_set.empty()) {
8190 auto it = ret.find(resolved_classes);
8191 if (it != ret.end()) {
8192 // Already have the key, union the class def idxs.
8193 it->AddClasses(class_set.begin(), class_set.end());
8194 } else {
8195 resolved_classes.AddClasses(class_set.begin(), class_set.end());
8196 ret.insert(resolved_classes);
8197 }
8198 }
8199
8200 VLOG(class_linker) << "Dex location " << location << " has " << num_resolved << " / "
8201 << num_class_defs << " resolved classes";
8202 }
8203 VLOG(class_linker) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
8204 return ret;
8205 }
8206
GetClassDescriptorsForProfileKeys(const std::set<DexCacheResolvedClasses> & classes)8207 std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForProfileKeys(
8208 const std::set<DexCacheResolvedClasses>& classes) {
8209 ScopedTrace trace(__PRETTY_FUNCTION__);
8210 std::unordered_set<std::string> ret;
8211 Thread* const self = Thread::Current();
8212 std::unordered_map<std::string, const DexFile*> location_to_dex_file;
8213 ScopedObjectAccess soa(self);
8214 ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__);
8215 ReaderMutexLock mu(self, *DexLock());
8216 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8217 if (!self->IsJWeakCleared(data.weak_root)) {
8218 mirror::DexCache* dex_cache =
8219 down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root));
8220 if (dex_cache != nullptr) {
8221 const DexFile* dex_file = dex_cache->GetDexFile();
8222 // There could be duplicates if two dex files with the same location are mapped.
8223 location_to_dex_file.emplace(
8224 ProfileCompilationInfo::GetProfileDexFileKey(dex_file->GetLocation()), dex_file);
8225 }
8226 }
8227 }
8228 for (const DexCacheResolvedClasses& info : classes) {
8229 const std::string& profile_key = info.GetDexLocation();
8230 auto found = location_to_dex_file.find(profile_key);
8231 if (found != location_to_dex_file.end()) {
8232 const DexFile* dex_file = found->second;
8233 VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with "
8234 << info.GetClasses().size() << " classes";
8235 DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum());
8236 for (uint16_t class_def_idx : info.GetClasses()) {
8237 if (class_def_idx >= dex_file->NumClassDefs()) {
8238 LOG(WARNING) << "Class def index " << class_def_idx << " >= " << dex_file->NumClassDefs();
8239 continue;
8240 }
8241 const DexFile::TypeId& type_id = dex_file->GetTypeId(
8242 dex_file->GetClassDef(class_def_idx).class_idx_);
8243 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
8244 ret.insert(descriptor);
8245 }
8246 } else {
8247 VLOG(class_linker) << "Failed to find opened dex file for profile key " << profile_key;
8248 }
8249 }
8250 return ret;
8251 }
8252
8253 // Instantiate ResolveMethod.
8254 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>(
8255 const DexFile& dex_file,
8256 uint32_t method_idx,
8257 Handle<mirror::DexCache> dex_cache,
8258 Handle<mirror::ClassLoader> class_loader,
8259 ArtMethod* referrer,
8260 InvokeType type);
8261 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>(
8262 const DexFile& dex_file,
8263 uint32_t method_idx,
8264 Handle<mirror::DexCache> dex_cache,
8265 Handle<mirror::ClassLoader> class_loader,
8266 ArtMethod* referrer,
8267 InvokeType type);
8268
8269 } // namespace art
8270