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