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