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 #ifndef ART_RUNTIME_CLASS_LINKER_H_
18 #define ART_RUNTIME_CLASS_LINKER_H_
19 
20 #include <set>
21 #include <string>
22 #include <unordered_map>
23 #include <unordered_set>
24 #include <utility>
25 #include <vector>
26 
27 #include "base/enums.h"
28 #include "base/macros.h"
29 #include "base/mutex.h"
30 #include "class_table.h"
31 #include "dex_cache_resolved_classes.h"
32 #include "dex_file.h"
33 #include "dex_file_types.h"
34 #include "gc_root.h"
35 #include "handle.h"
36 #include "jni.h"
37 #include "mirror/class.h"
38 #include "object_callbacks.h"
39 #include "verifier/verifier_enums.h"
40 
41 namespace art {
42 
43 namespace gc {
44 namespace space {
45   class ImageSpace;
46 }  // namespace space
47 }  // namespace gc
48 namespace mirror {
49   class ClassLoader;
50   class DexCache;
51   class DexCachePointerArray;
52   class DexCacheMethodHandlesTest_Open_Test;
53   class DexCacheTest_Open_Test;
54   class IfTable;
55   class MethodHandle;
56   class MethodHandlesLookup;
57   class MethodType;
58   template<class T> class ObjectArray;
59   class StackTraceElement;
60 }  // namespace mirror
61 
62 template<class T> class Handle;
63 class ImtConflictTable;
64 template<typename T> class LengthPrefixedArray;
65 template<class T> class MutableHandle;
66 class InternTable;
67 class OatFile;
68 template<class T> class ObjectLock;
69 class Runtime;
70 class ScopedObjectAccessAlreadyRunnable;
71 template<size_t kNumReferences> class PACKED(4) StackHandleScope;
72 
73 enum VisitRootFlags : uint8_t;
74 
75 class ClassVisitor {
76  public:
~ClassVisitor()77   virtual ~ClassVisitor() {}
78   // Return true to continue visiting.
79   virtual bool operator()(ObjPtr<mirror::Class> klass) = 0;
80 };
81 
82 class ClassLoaderVisitor {
83  public:
~ClassLoaderVisitor()84   virtual ~ClassLoaderVisitor() {}
85   virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader)
86       REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) = 0;
87 };
88 
89 class ClassLinker {
90  public:
91   // Well known mirror::Class roots accessed via GetClassRoot.
92   enum ClassRoot {
93     kJavaLangClass,
94     kJavaLangObject,
95     kClassArrayClass,
96     kObjectArrayClass,
97     kJavaLangString,
98     kJavaLangDexCache,
99     kJavaLangRefReference,
100     kJavaLangReflectConstructor,
101     kJavaLangReflectField,
102     kJavaLangReflectMethod,
103     kJavaLangReflectProxy,
104     kJavaLangStringArrayClass,
105     kJavaLangReflectConstructorArrayClass,
106     kJavaLangReflectFieldArrayClass,
107     kJavaLangReflectMethodArrayClass,
108     kJavaLangInvokeCallSite,
109     kJavaLangInvokeMethodHandleImpl,
110     kJavaLangInvokeMethodHandlesLookup,
111     kJavaLangInvokeMethodType,
112     kJavaLangClassLoader,
113     kJavaLangThrowable,
114     kJavaLangClassNotFoundException,
115     kJavaLangStackTraceElement,
116     kDalvikSystemEmulatedStackFrame,
117     kPrimitiveBoolean,
118     kPrimitiveByte,
119     kPrimitiveChar,
120     kPrimitiveDouble,
121     kPrimitiveFloat,
122     kPrimitiveInt,
123     kPrimitiveLong,
124     kPrimitiveShort,
125     kPrimitiveVoid,
126     kBooleanArrayClass,
127     kByteArrayClass,
128     kCharArrayClass,
129     kDoubleArrayClass,
130     kFloatArrayClass,
131     kIntArrayClass,
132     kLongArrayClass,
133     kShortArrayClass,
134     kJavaLangStackTraceElementArrayClass,
135     kDalvikSystemClassExt,
136     kClassRootsMax,
137   };
138 
139   explicit ClassLinker(InternTable* intern_table);
140   ~ClassLinker();
141 
142   // Initialize class linker by bootstraping from dex files.
143   bool InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
144                         std::string* error_msg)
145       REQUIRES_SHARED(Locks::mutator_lock_)
146       REQUIRES(!Locks::dex_lock_);
147 
148   // Initialize class linker from one or more boot images.
149   bool InitFromBootImage(std::string* error_msg)
150       REQUIRES_SHARED(Locks::mutator_lock_)
151       REQUIRES(!Locks::dex_lock_);
152 
153   // Add an image space to the class linker, may fix up classloader fields and dex cache fields.
154   // The dex files that were newly opened for the space are placed in the out argument
155   // out_dex_files. Returns true if the operation succeeded.
156   // The space must be already added to the heap before calling AddImageSpace since we need to
157   // properly handle read barriers and object marking.
158   bool AddImageSpace(gc::space::ImageSpace* space,
159                      Handle<mirror::ClassLoader> class_loader,
160                      jobjectArray dex_elements,
161                      const char* dex_location,
162                      std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
163                      std::string* error_msg)
164       REQUIRES(!Locks::dex_lock_)
165       REQUIRES_SHARED(Locks::mutator_lock_);
166 
167   bool OpenImageDexFiles(gc::space::ImageSpace* space,
168                          std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
169                          std::string* error_msg)
170       REQUIRES(!Locks::dex_lock_)
171       REQUIRES_SHARED(Locks::mutator_lock_);
172 
173   // Finds a class by its descriptor, loading it if necessary.
174   // If class_loader is null, searches boot_class_path_.
175   mirror::Class* FindClass(Thread* self,
176                            const char* descriptor,
177                            Handle<mirror::ClassLoader> class_loader)
178       REQUIRES_SHARED(Locks::mutator_lock_)
179       REQUIRES(!Locks::dex_lock_);
180 
181   // Finds a class by its descriptor using the "system" class loader, ie by searching the
182   // boot_class_path_.
FindSystemClass(Thread * self,const char * descriptor)183   mirror::Class* FindSystemClass(Thread* self, const char* descriptor)
184       REQUIRES_SHARED(Locks::mutator_lock_)
185       REQUIRES(!Locks::dex_lock_) {
186     return FindClass(self, descriptor, ScopedNullHandle<mirror::ClassLoader>());
187   }
188 
189   // Finds the array class given for the element class.
190   mirror::Class* FindArrayClass(Thread* self, ObjPtr<mirror::Class>* element_class)
191       REQUIRES_SHARED(Locks::mutator_lock_)
192       REQUIRES(!Locks::dex_lock_);
193 
194   // Returns true if the class linker is initialized.
IsInitialized()195   bool IsInitialized() const {
196     return init_done_;
197   }
198 
199   // Define a new a class based on a ClassDef from a DexFile
200   mirror::Class* DefineClass(Thread* self,
201                              const char* descriptor,
202                              size_t hash,
203                              Handle<mirror::ClassLoader> class_loader,
204                              const DexFile& dex_file,
205                              const DexFile::ClassDef& dex_class_def)
206       REQUIRES_SHARED(Locks::mutator_lock_)
207       REQUIRES(!Locks::dex_lock_);
208 
209   // Finds a class by its descriptor, returning null if it isn't wasn't loaded
210   // by the given 'class_loader'.
LookupClass(Thread * self,const char * descriptor,ObjPtr<mirror::ClassLoader> class_loader)211   mirror::Class* LookupClass(Thread* self,
212                              const char* descriptor,
213                              ObjPtr<mirror::ClassLoader> class_loader)
214       REQUIRES(!Locks::classlinker_classes_lock_)
215       REQUIRES_SHARED(Locks::mutator_lock_) {
216     return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
217   }
218 
219   // Finds all the classes with the given descriptor, regardless of ClassLoader.
220   void LookupClasses(const char* descriptor, std::vector<ObjPtr<mirror::Class>>& classes)
221       REQUIRES(!Locks::classlinker_classes_lock_)
222       REQUIRES_SHARED(Locks::mutator_lock_);
223 
224   mirror::Class* FindPrimitiveClass(char type) REQUIRES_SHARED(Locks::mutator_lock_);
225 
226   void DumpForSigQuit(std::ostream& os) REQUIRES(!Locks::classlinker_classes_lock_);
227 
228   size_t NumLoadedClasses()
229       REQUIRES(!Locks::classlinker_classes_lock_)
230       REQUIRES_SHARED(Locks::mutator_lock_);
231 
232   // Resolve a String with the given index from the DexFile, storing the
233   // result in the DexCache.
234   mirror::String* ResolveString(const DexFile& dex_file,
235                                 dex::StringIndex string_idx,
236                                 Handle<mirror::DexCache> dex_cache)
237       REQUIRES_SHARED(Locks::mutator_lock_);
238 
239   // Find a String with the given index from the DexFile, storing the
240   // result in the DexCache if found. Return null if not found.
241   mirror::String* LookupString(const DexFile& dex_file,
242                                dex::StringIndex string_idx,
243                                ObjPtr<mirror::DexCache> dex_cache)
244       REQUIRES_SHARED(Locks::mutator_lock_);
245 
246   // Resolve a Type with the given index from the DexFile, storing the
247   // result in the DexCache. The referrer is used to identify the
248   // target DexCache and ClassLoader to use for resolution.
249   mirror::Class* ResolveType(const DexFile& dex_file,
250                              dex::TypeIndex type_idx,
251                              ObjPtr<mirror::Class> referrer)
252       REQUIRES_SHARED(Locks::mutator_lock_)
253       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
254 
255   // Resolve a Type with the given index from the DexFile, storing the
256   // result in the DexCache. The referrer is used to identify the
257   // target DexCache and ClassLoader to use for resolution.
258   mirror::Class* ResolveType(dex::TypeIndex type_idx, ArtMethod* referrer)
259       REQUIRES_SHARED(Locks::mutator_lock_)
260       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
261 
262   // Look up a resolved type with the given ID from the DexFile. The ClassLoader is used to search
263   // for the type, since it may be referenced from but not contained within the given DexFile.
264   ObjPtr<mirror::Class> LookupResolvedType(const DexFile& dex_file,
265                                            dex::TypeIndex type_idx,
266                                            ObjPtr<mirror::DexCache> dex_cache,
267                                            ObjPtr<mirror::ClassLoader> class_loader)
268       REQUIRES_SHARED(Locks::mutator_lock_);
269   static ObjPtr<mirror::Class> LookupResolvedType(dex::TypeIndex type_idx,
270                                                   ObjPtr<mirror::DexCache> dex_cache,
271                                                   ObjPtr<mirror::ClassLoader> class_loader)
272       REQUIRES_SHARED(Locks::mutator_lock_);
273 
274   // Resolve a type with the given ID from the DexFile, storing the
275   // result in DexCache. The ClassLoader is used to search for the
276   // type, since it may be referenced from but not contained within
277   // the given DexFile.
278   mirror::Class* ResolveType(const DexFile& dex_file,
279                              dex::TypeIndex type_idx,
280                              Handle<mirror::DexCache> dex_cache,
281                              Handle<mirror::ClassLoader> class_loader)
282       REQUIRES_SHARED(Locks::mutator_lock_)
283       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
284 
285   // Determine whether a dex cache result should be trusted, or an IncompatibleClassChangeError
286   // check should be performed even after a hit.
287   enum ResolveMode {  // private.
288     kNoICCECheckForCache,
289     kForceICCECheck
290   };
291 
292   // Resolve a method with a given ID from the DexFile, storing the
293   // result in DexCache. The ClassLinker and ClassLoader are used as
294   // in ResolveType. What is unique is the method type argument which
295   // is used to determine if this method is a direct, static, or
296   // virtual method.
297   template <ResolveMode kResolveMode>
298   ArtMethod* ResolveMethod(const DexFile& dex_file,
299                            uint32_t method_idx,
300                            Handle<mirror::DexCache> dex_cache,
301                            Handle<mirror::ClassLoader> class_loader,
302                            ArtMethod* referrer,
303                            InvokeType type)
304       REQUIRES_SHARED(Locks::mutator_lock_)
305       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
306 
307   ArtMethod* GetResolvedMethod(uint32_t method_idx, ArtMethod* referrer)
308       REQUIRES_SHARED(Locks::mutator_lock_);
309 
310   // This returns the class referred to by GetMethodId(method_idx).class_idx_. This might be
311   // different then the declaring class of the resolved method due to copied
312   // miranda/default/conflict methods.
313   mirror::Class* ResolveReferencedClassOfMethod(uint32_t method_idx,
314                                                 Handle<mirror::DexCache> dex_cache,
315                                                 Handle<mirror::ClassLoader> class_loader)
316       REQUIRES_SHARED(Locks::mutator_lock_)
317       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
318   template <ResolveMode kResolveMode>
319   ArtMethod* ResolveMethod(Thread* self, uint32_t method_idx, ArtMethod* referrer, InvokeType type)
320       REQUIRES_SHARED(Locks::mutator_lock_)
321       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
322   ArtMethod* ResolveMethodWithoutInvokeType(const DexFile& dex_file,
323                                             uint32_t method_idx,
324                                             Handle<mirror::DexCache> dex_cache,
325                                             Handle<mirror::ClassLoader> class_loader)
326       REQUIRES_SHARED(Locks::mutator_lock_)
327       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
328 
329   ArtField* LookupResolvedField(uint32_t field_idx, ArtMethod* referrer, bool is_static)
330       REQUIRES_SHARED(Locks::mutator_lock_);
331   ArtField* ResolveField(uint32_t field_idx, ArtMethod* referrer, bool is_static)
332       REQUIRES_SHARED(Locks::mutator_lock_)
333       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
334 
335   // Resolve a field with a given ID from the DexFile, storing the
336   // result in DexCache. The ClassLinker and ClassLoader are used as
337   // in ResolveType. What is unique is the is_static argument which is
338   // used to determine if we are resolving a static or non-static
339   // field.
340   ArtField* ResolveField(const DexFile& dex_file, uint32_t field_idx,
341                          Handle<mirror::DexCache> dex_cache,
342                          Handle<mirror::ClassLoader> class_loader, bool is_static)
343       REQUIRES_SHARED(Locks::mutator_lock_)
344       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
345 
346   // Resolve a field with a given ID from the DexFile, storing the
347   // result in DexCache. The ClassLinker and ClassLoader are used as
348   // in ResolveType. No is_static argument is provided so that Java
349   // field resolution semantics are followed.
350   ArtField* ResolveFieldJLS(const DexFile& dex_file,
351                             uint32_t field_idx,
352                             Handle<mirror::DexCache> dex_cache,
353                             Handle<mirror::ClassLoader> class_loader)
354       REQUIRES_SHARED(Locks::mutator_lock_)
355       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
356 
357   // Resolve a method type with a given ID from the DexFile, storing
358   // the result in the DexCache.
359   mirror::MethodType* ResolveMethodType(const DexFile& dex_file,
360                                         uint32_t proto_idx,
361                                         Handle<mirror::DexCache> dex_cache,
362                                         Handle<mirror::ClassLoader> class_loader)
363       REQUIRES_SHARED(Locks::mutator_lock_)
364       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
365 
366   // Resolve a method handle with a given ID from the DexFile. The
367   // result is not cached in the DexCache as the instance will only be
368   // used once in most circumstances.
369   mirror::MethodHandle* ResolveMethodHandle(uint32_t method_handle_idx, ArtMethod* referrer)
370       REQUIRES_SHARED(Locks::mutator_lock_);
371 
372   // Returns true on success, false if there's an exception pending.
373   // can_run_clinit=false allows the compiler to attempt to init a class,
374   // given the restriction that no <clinit> execution is possible.
375   bool EnsureInitialized(Thread* self,
376                          Handle<mirror::Class> c,
377                          bool can_init_fields,
378                          bool can_init_parents)
379       REQUIRES_SHARED(Locks::mutator_lock_)
380       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
381 
382   // Initializes classes that have instances in the image but that have
383   // <clinit> methods so they could not be initialized by the compiler.
384   void RunRootClinits()
385       REQUIRES_SHARED(Locks::mutator_lock_)
386       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
387 
388   ObjPtr<mirror::DexCache> RegisterDexFile(const DexFile& dex_file,
389                                            ObjPtr<mirror::ClassLoader> class_loader)
390       REQUIRES(!Locks::dex_lock_)
391       REQUIRES_SHARED(Locks::mutator_lock_);
392   void RegisterBootClassPathDexFile(const DexFile& dex_file, ObjPtr<mirror::DexCache> dex_cache)
393       REQUIRES(!Locks::dex_lock_)
394       REQUIRES_SHARED(Locks::mutator_lock_);
395 
GetBootClassPath()396   const std::vector<const DexFile*>& GetBootClassPath() {
397     return boot_class_path_;
398   }
399 
400   void VisitClasses(ClassVisitor* visitor)
401       REQUIRES(!Locks::classlinker_classes_lock_)
402       REQUIRES_SHARED(Locks::mutator_lock_);
403 
404   // Less efficient variant of VisitClasses that copies the class_table_ into secondary storage
405   // so that it can visit individual classes without holding the doesn't hold the
406   // Locks::classlinker_classes_lock_. As the Locks::classlinker_classes_lock_ isn't held this code
407   // can race with insertion and deletion of classes while the visitor is being called.
408   void VisitClassesWithoutClassesLock(ClassVisitor* visitor)
409       REQUIRES_SHARED(Locks::mutator_lock_)
410       REQUIRES(!Locks::dex_lock_);
411 
412   void VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags)
413       REQUIRES(!Locks::classlinker_classes_lock_, !Locks::trace_lock_)
414       REQUIRES_SHARED(Locks::mutator_lock_);
415   void VisitRoots(RootVisitor* visitor, VisitRootFlags flags)
416       REQUIRES(!Locks::dex_lock_, !Locks::classlinker_classes_lock_, !Locks::trace_lock_)
417       REQUIRES_SHARED(Locks::mutator_lock_);
418 
419   bool IsDexFileRegistered(Thread* self, const DexFile& dex_file)
420       REQUIRES(!Locks::dex_lock_)
421       REQUIRES_SHARED(Locks::mutator_lock_);
422   ObjPtr<mirror::DexCache> FindDexCache(Thread* self, const DexFile& dex_file)
423       REQUIRES(!Locks::dex_lock_)
424       REQUIRES_SHARED(Locks::mutator_lock_);
425   ClassTable* FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache)
426       REQUIRES(!Locks::dex_lock_)
427       REQUIRES_SHARED(Locks::mutator_lock_);
428   void FixupDexCaches(ArtMethod* resolution_method)
429       REQUIRES(!Locks::dex_lock_)
430       REQUIRES_SHARED(Locks::mutator_lock_);
431 
432   LengthPrefixedArray<ArtField>* AllocArtFieldArray(Thread* self,
433                                                     LinearAlloc* allocator,
434                                                     size_t length);
435 
436   LengthPrefixedArray<ArtMethod>* AllocArtMethodArray(Thread* self,
437                                                       LinearAlloc* allocator,
438                                                       size_t length);
439 
440   mirror::PointerArray* AllocPointerArray(Thread* self, size_t length)
441       REQUIRES_SHARED(Locks::mutator_lock_)
442       REQUIRES(!Roles::uninterruptible_);
443 
444   mirror::IfTable* AllocIfTable(Thread* self, size_t ifcount)
445       REQUIRES_SHARED(Locks::mutator_lock_)
446       REQUIRES(!Roles::uninterruptible_);
447 
448   mirror::ObjectArray<mirror::StackTraceElement>* AllocStackTraceElementArray(Thread* self,
449                                                                               size_t length)
450       REQUIRES_SHARED(Locks::mutator_lock_)
451       REQUIRES(!Roles::uninterruptible_);
452 
453   verifier::FailureKind VerifyClass(
454       Thread* self,
455       Handle<mirror::Class> klass,
456       verifier::HardFailLogMode log_level = verifier::HardFailLogMode::kLogNone)
457       REQUIRES_SHARED(Locks::mutator_lock_)
458       REQUIRES(!Locks::dex_lock_);
459   bool VerifyClassUsingOatFile(const DexFile& dex_file,
460                                ObjPtr<mirror::Class> klass,
461                                mirror::Class::Status& oat_file_class_status)
462       REQUIRES_SHARED(Locks::mutator_lock_)
463       REQUIRES(!Locks::dex_lock_);
464   void ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass)
465       REQUIRES_SHARED(Locks::mutator_lock_)
466       REQUIRES(!Locks::dex_lock_);
467   void ResolveMethodExceptionHandlerTypes(ArtMethod* klass)
468       REQUIRES_SHARED(Locks::mutator_lock_)
469       REQUIRES(!Locks::dex_lock_);
470 
471   mirror::Class* CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
472                                   jstring name,
473                                   jobjectArray interfaces,
474                                   jobject loader,
475                                   jobjectArray methods,
476                                   jobjectArray throws)
477       REQUIRES_SHARED(Locks::mutator_lock_);
478   std::string GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class)
479       REQUIRES_SHARED(Locks::mutator_lock_);
480   template<ReadBarrierOption kReadBarrierOption = kWithReadBarrier>
481   ArtMethod* FindMethodForProxy(ObjPtr<mirror::Class> proxy_class, ArtMethod* proxy_method)
482       REQUIRES(!Locks::dex_lock_)
483       REQUIRES_SHARED(Locks::mutator_lock_);
484 
485   // Get the oat code for a method when its class isn't yet initialized.
486   const void* GetQuickOatCodeFor(ArtMethod* method)
487       REQUIRES_SHARED(Locks::mutator_lock_);
488 
489   pid_t GetClassesLockOwner();  // For SignalCatcher.
490   pid_t GetDexLockOwner();  // For SignalCatcher.
491 
492   mirror::Class* GetClassRoot(ClassRoot class_root) REQUIRES_SHARED(Locks::mutator_lock_);
493 
494   static const char* GetClassRootDescriptor(ClassRoot class_root);
495 
496   // Is the given entry point quick code to run the resolution stub?
497   bool IsQuickResolutionStub(const void* entry_point) const;
498 
499   // Is the given entry point quick code to bridge into the interpreter?
500   bool IsQuickToInterpreterBridge(const void* entry_point) const;
501 
502   // Is the given entry point quick code to run the generic JNI stub?
503   bool IsQuickGenericJniStub(const void* entry_point) const;
504 
GetQuickToInterpreterBridgeTrampoline()505   const void* GetQuickToInterpreterBridgeTrampoline() const {
506     return quick_to_interpreter_bridge_trampoline_;
507   }
508 
GetInternTable()509   InternTable* GetInternTable() const {
510     return intern_table_;
511   }
512 
513   // Set the entrypoints up for method to the given code.
514   void SetEntryPointsToCompiledCode(ArtMethod* method, const void* method_code) const
515       REQUIRES_SHARED(Locks::mutator_lock_);
516 
517   // Set the entrypoints up for method to the enter the interpreter.
518   void SetEntryPointsToInterpreter(ArtMethod* method) const
519       REQUIRES_SHARED(Locks::mutator_lock_);
520 
521   // Set the entrypoints up for an obsolete method.
522   void SetEntryPointsForObsoleteMethod(ArtMethod* method) const
523       REQUIRES_SHARED(Locks::mutator_lock_);
524 
525   // Attempts to insert a class into a class table.  Returns null if
526   // the class was inserted, otherwise returns an existing class with
527   // the same descriptor and ClassLoader.
528   mirror::Class* InsertClass(const char* descriptor, ObjPtr<mirror::Class> klass, size_t hash)
529       REQUIRES(!Locks::classlinker_classes_lock_)
530       REQUIRES_SHARED(Locks::mutator_lock_);
531 
532   // Add an oat file with .bss GC roots to be visited again at the end of GC
533   // for collector types that need it.
534   void WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file)
535       REQUIRES(!Locks::classlinker_classes_lock_)
536       REQUIRES_SHARED(Locks::mutator_lock_);
537 
GetClassRoots()538   mirror::ObjectArray<mirror::Class>* GetClassRoots() REQUIRES_SHARED(Locks::mutator_lock_) {
539     mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
540     DCHECK(class_roots != nullptr);
541     return class_roots;
542   }
543 
544   // Move the class table to the pre-zygote table to reduce memory usage. This works by ensuring
545   // that no more classes are ever added to the pre zygote table which makes it that the pages
546   // always remain shared dirty instead of private dirty.
547   void MoveClassTableToPreZygote()
548       REQUIRES(!Locks::classlinker_classes_lock_)
549       REQUIRES_SHARED(Locks::mutator_lock_);
550 
551   // Creates a GlobalRef PathClassLoader that can be used to load classes from the given dex files.
552   // Note: the objects are not completely set up. Do not use this outside of tests and the compiler.
553   jobject CreatePathClassLoader(Thread* self, const std::vector<const DexFile*>& dex_files)
554       REQUIRES_SHARED(Locks::mutator_lock_)
555       REQUIRES(!Locks::dex_lock_);
556 
GetImagePointerSize()557   PointerSize GetImagePointerSize() const {
558     return image_pointer_size_;
559   }
560 
561   // Used by image writer for checking.
562   bool ClassInClassTable(ObjPtr<mirror::Class> klass)
563       REQUIRES(Locks::classlinker_classes_lock_)
564       REQUIRES_SHARED(Locks::mutator_lock_);
565 
566   // Clear the ArrayClass cache. This is necessary when cleaning up for the image, as the cache
567   // entries are roots, but potentially not image classes.
568   void DropFindArrayClassCache() REQUIRES_SHARED(Locks::mutator_lock_);
569 
570   // Clean up class loaders, this needs to happen after JNI weak globals are cleared.
571   void CleanupClassLoaders()
572       REQUIRES(!Locks::classlinker_classes_lock_)
573       REQUIRES_SHARED(Locks::mutator_lock_);
574 
575   // Unlike GetOrCreateAllocatorForClassLoader, GetAllocatorForClassLoader asserts that the
576   // allocator for this class loader is already created.
577   LinearAlloc* GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader)
578       REQUIRES_SHARED(Locks::mutator_lock_);
579 
580   // Return the linear alloc for a class loader if it is already allocated, otherwise allocate and
581   // set it. TODO: Consider using a lock other than classlinker_classes_lock_.
582   LinearAlloc* GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader)
583       REQUIRES(!Locks::classlinker_classes_lock_)
584       REQUIRES_SHARED(Locks::mutator_lock_);
585 
586   // May be called with null class_loader due to legacy code. b/27954959
587   void InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
588                                     ObjPtr<mirror::ClassLoader> class_loader)
589       REQUIRES(!Locks::classlinker_classes_lock_)
590       REQUIRES_SHARED(Locks::mutator_lock_);
591 
592   static bool ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code)
593       REQUIRES_SHARED(Locks::mutator_lock_);
594 
595   std::set<DexCacheResolvedClasses> GetResolvedClasses(bool ignore_boot_classes)
596       REQUIRES(!Locks::dex_lock_);
597 
598   // Returns the class descriptors for loaded dex files.
599   std::unordered_set<std::string> GetClassDescriptorsForResolvedClasses(
600       const std::set<DexCacheResolvedClasses>& classes)
601       REQUIRES(!Locks::dex_lock_);
602 
603   static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
604                                 ObjPtr<mirror::ClassLoader> class_loader)
605       REQUIRES_SHARED(Locks::mutator_lock_);
606 
607   ArtMethod* AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
608                                       ArtMethod* conflict_method,
609                                       ArtMethod* interface_method,
610                                       ArtMethod* method,
611                                       bool force_new_conflict_method)
612       REQUIRES_SHARED(Locks::mutator_lock_);
613 
614   // Create a conflict table with a specified capacity.
615   ImtConflictTable* CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc);
616 
617   // Static version for when the class linker is not yet created.
618   static ImtConflictTable* CreateImtConflictTable(size_t count,
619                                                   LinearAlloc* linear_alloc,
620                                                   PointerSize pointer_size);
621 
622 
623   // Create the IMT and conflict tables for a class.
624   void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
625 
626   // Clear class table strong roots (other than classes themselves). This is done by dex2oat to
627   // allow pruning dex caches.
628   void ClearClassTableStrongRoots() const
629       REQUIRES(!Locks::classlinker_classes_lock_)
630       REQUIRES_SHARED(Locks::mutator_lock_);
631 
632   // Throw the class initialization failure recorded when first trying to initialize the given
633   // class.
634   void ThrowEarlierClassFailure(ObjPtr<mirror::Class> c, bool wrap_in_no_class_def = false)
635       REQUIRES_SHARED(Locks::mutator_lock_)
636       REQUIRES(!Locks::dex_lock_);
637 
638   // Get the actual holding class for a copied method. Pretty slow, don't call often.
639   mirror::Class* GetHoldingClassOfCopiedMethod(ArtMethod* method)
640       REQUIRES_SHARED(Locks::mutator_lock_);
641 
642   // Returns null if not found.
643   ClassTable* ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader)
644       REQUIRES_SHARED(Locks::mutator_lock_);
645 
646   void AppendToBootClassPath(Thread* self, const DexFile& dex_file)
647       REQUIRES_SHARED(Locks::mutator_lock_)
648       REQUIRES(!Locks::dex_lock_);
649 
650   struct DexCacheData {
651     // Construct an invalid data object.
DexCacheDataDexCacheData652     DexCacheData()
653         : weak_root(nullptr),
654           dex_file(nullptr),
655           resolved_methods(nullptr),
656           class_table(nullptr) { }
657 
658     // Check if the data is valid.
IsValidDexCacheData659     bool IsValid() const {
660       return dex_file != nullptr;
661     }
662 
663     // Weak root to the DexCache. Note: Do not decode this unnecessarily or else class unloading may
664     // not work properly.
665     jweak weak_root;
666     // The following two fields are caches to the DexCache's fields and here to avoid unnecessary
667     // jweak decode that triggers read barriers (and mark them alive unnecessarily and mess with
668     // class unloading.)
669     const DexFile* dex_file;
670     ArtMethod** resolved_methods;
671     // Identify the associated class loader's class table. This is used to make sure that
672     // the Java call to native DexCache.setResolvedType() inserts the resolved type in that
673     // class table. It is also used to make sure we don't register the same dex cache with
674     // multiple class loaders.
675     ClassTable* class_table;
676   };
677 
678  private:
679   class LinkInterfaceMethodsHelper;
680 
681   struct ClassLoaderData {
682     jweak weak_root;  // Weak root to enable class unloading.
683     ClassTable* class_table;
684     LinearAlloc* allocator;
685   };
686 
687   // Ensures that the supertype of 'klass' ('supertype') is verified. Returns false and throws
688   // appropriate exceptions if verification failed hard. Returns true for successful verification or
689   // soft-failures.
690   bool AttemptSupertypeVerification(Thread* self,
691                                     Handle<mirror::Class> klass,
692                                     Handle<mirror::Class> supertype)
693       REQUIRES(!Locks::dex_lock_)
694       REQUIRES_SHARED(Locks::mutator_lock_);
695 
696   static void DeleteClassLoader(Thread* self, const ClassLoaderData& data)
697       REQUIRES_SHARED(Locks::mutator_lock_);
698 
699   void VisitClassLoaders(ClassLoaderVisitor* visitor) const
700       REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_);
701 
702   void VisitClassesInternal(ClassVisitor* visitor)
703       REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_);
704 
705   // Returns the number of zygote and image classes.
706   size_t NumZygoteClasses() const
707       REQUIRES(Locks::classlinker_classes_lock_)
708       REQUIRES_SHARED(Locks::mutator_lock_);
709 
710   // Returns the number of non zygote nor image classes.
711   size_t NumNonZygoteClasses() const
712       REQUIRES(Locks::classlinker_classes_lock_)
713       REQUIRES_SHARED(Locks::mutator_lock_);
714 
715   void FinishInit(Thread* self)
716       REQUIRES_SHARED(Locks::mutator_lock_)
717       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
718 
719   // For early bootstrapping by Init
720   mirror::Class* AllocClass(Thread* self,
721                             ObjPtr<mirror::Class> java_lang_Class,
722                             uint32_t class_size)
723       REQUIRES_SHARED(Locks::mutator_lock_)
724       REQUIRES(!Roles::uninterruptible_);
725 
726   // Alloc* convenience functions to avoid needing to pass in mirror::Class*
727   // values that are known to the ClassLinker such as
728   // kObjectArrayClass and kJavaLangString etc.
729   mirror::Class* AllocClass(Thread* self, uint32_t class_size)
730       REQUIRES_SHARED(Locks::mutator_lock_)
731       REQUIRES(!Roles::uninterruptible_);
732 
733   mirror::DexCache* AllocDexCache(ObjPtr<mirror::String>* out_location,
734                                   Thread* self,
735                                   const DexFile& dex_file)
736       REQUIRES_SHARED(Locks::mutator_lock_)
737       REQUIRES(!Roles::uninterruptible_);
738 
739   // Used for tests and AppendToBootClassPath.
740   mirror::DexCache* AllocAndInitializeDexCache(Thread* self,
741                                                const DexFile& dex_file,
742                                                LinearAlloc* linear_alloc)
743       REQUIRES_SHARED(Locks::mutator_lock_)
744       REQUIRES(!Locks::dex_lock_)
745       REQUIRES(!Roles::uninterruptible_);
746 
747   mirror::Class* CreatePrimitiveClass(Thread* self, Primitive::Type type)
748       REQUIRES_SHARED(Locks::mutator_lock_)
749       REQUIRES(!Roles::uninterruptible_);
750   mirror::Class* InitializePrimitiveClass(ObjPtr<mirror::Class> primitive_class,
751                                           Primitive::Type type)
752       REQUIRES_SHARED(Locks::mutator_lock_)
753       REQUIRES(!Roles::uninterruptible_);
754 
755   mirror::Class* CreateArrayClass(Thread* self,
756                                   const char* descriptor,
757                                   size_t hash,
758                                   Handle<mirror::ClassLoader> class_loader)
759       REQUIRES_SHARED(Locks::mutator_lock_)
760       REQUIRES(!Locks::dex_lock_, !Roles::uninterruptible_);
761 
762   void AppendToBootClassPath(const DexFile& dex_file, ObjPtr<mirror::DexCache> dex_cache)
763       REQUIRES_SHARED(Locks::mutator_lock_)
764       REQUIRES(!Locks::dex_lock_);
765 
766   // Precomputes size needed for Class, in the case of a non-temporary class this size must be
767   // sufficient to hold all static fields.
768   uint32_t SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
769                                             const DexFile::ClassDef& dex_class_def);
770 
771   // Setup the classloader, class def index, type idx so that we can insert this class in the class
772   // table.
773   void SetupClass(const DexFile& dex_file,
774                   const DexFile::ClassDef& dex_class_def,
775                   Handle<mirror::Class> klass,
776                   ObjPtr<mirror::ClassLoader> class_loader)
777       REQUIRES_SHARED(Locks::mutator_lock_);
778 
779   void LoadClass(Thread* self,
780                  const DexFile& dex_file,
781                  const DexFile::ClassDef& dex_class_def,
782                  Handle<mirror::Class> klass)
783       REQUIRES_SHARED(Locks::mutator_lock_);
784   void LoadClassMembers(Thread* self,
785                         const DexFile& dex_file,
786                         const uint8_t* class_data,
787                         Handle<mirror::Class> klass)
788       REQUIRES_SHARED(Locks::mutator_lock_);
789 
790   void LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass, ArtField* dst)
791       REQUIRES_SHARED(Locks::mutator_lock_);
792 
793   void LoadMethod(const DexFile& dex_file,
794                   const ClassDataItemIterator& it,
795                   Handle<mirror::Class> klass, ArtMethod* dst)
796       REQUIRES_SHARED(Locks::mutator_lock_);
797 
798   void FixupStaticTrampolines(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
799 
800   // Finds a class in a Path- or DexClassLoader, loading it if necessary without using JNI. Hash
801   // function is supposed to be ComputeModifiedUtf8Hash(descriptor). Returns true if the
802   // class-loader chain could be handled, false otherwise, i.e., a non-supported class-loader
803   // was encountered while walking the parent chain (currently only BootClassLoader and
804   // PathClassLoader are supported).
805   bool FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
806                                      Thread* self,
807                                      const char* descriptor,
808                                      size_t hash,
809                                      Handle<mirror::ClassLoader> class_loader,
810                                      ObjPtr<mirror::Class>* result)
811       REQUIRES_SHARED(Locks::mutator_lock_)
812       REQUIRES(!Locks::dex_lock_);
813 
814   // Finds a class by its descriptor, returning NULL if it isn't wasn't loaded
815   // by the given 'class_loader'. Uses the provided hash for the descriptor.
816   mirror::Class* LookupClass(Thread* self,
817                              const char* descriptor,
818                              size_t hash,
819                              ObjPtr<mirror::ClassLoader> class_loader)
820       REQUIRES(!Locks::classlinker_classes_lock_)
821       REQUIRES_SHARED(Locks::mutator_lock_);
822 
823   // Find a field by its field index.
824   ArtField* LookupResolvedField(uint32_t field_idx,
825                                 ObjPtr<mirror::DexCache> dex_cache,
826                                 ObjPtr<mirror::ClassLoader> class_loader,
827                                 bool is_static)
828       REQUIRES_SHARED(Locks::mutator_lock_);
829 
830   void RegisterDexFileLocked(const DexFile& dex_file,
831                              ObjPtr<mirror::DexCache> dex_cache,
832                              ObjPtr<mirror::ClassLoader> class_loader)
833       REQUIRES(Locks::dex_lock_)
834       REQUIRES_SHARED(Locks::mutator_lock_);
835   DexCacheData FindDexCacheDataLocked(const DexFile& dex_file)
836       REQUIRES(Locks::dex_lock_)
837       REQUIRES_SHARED(Locks::mutator_lock_);
838   static ObjPtr<mirror::DexCache> DecodeDexCache(Thread* self, const DexCacheData& data)
839       REQUIRES_SHARED(Locks::mutator_lock_);
840   // Called to ensure that the dex cache has been registered with the same class loader.
841   // If yes, returns the dex cache, otherwise throws InternalError and returns null.
842   ObjPtr<mirror::DexCache> EnsureSameClassLoader(Thread* self,
843                                                  ObjPtr<mirror::DexCache> dex_cache,
844                                                  const DexCacheData& data,
845                                                  ObjPtr<mirror::ClassLoader> class_loader)
846       REQUIRES(!Locks::dex_lock_)
847       REQUIRES_SHARED(Locks::mutator_lock_);
848 
849   bool InitializeClass(Thread* self,
850                        Handle<mirror::Class> klass,
851                        bool can_run_clinit,
852                        bool can_init_parents)
853       REQUIRES_SHARED(Locks::mutator_lock_)
854       REQUIRES(!Locks::dex_lock_);
855   bool InitializeDefaultInterfaceRecursive(Thread* self,
856                                            Handle<mirror::Class> klass,
857                                            bool can_run_clinit,
858                                            bool can_init_parents)
859       REQUIRES(!Locks::dex_lock_)
860       REQUIRES_SHARED(Locks::mutator_lock_);
861   bool WaitForInitializeClass(Handle<mirror::Class> klass,
862                               Thread* self,
863                               ObjectLock<mirror::Class>& lock);
864   bool ValidateSuperClassDescriptors(Handle<mirror::Class> klass)
865       REQUIRES_SHARED(Locks::mutator_lock_);
866 
867   bool IsSameDescriptorInDifferentClassContexts(Thread* self,
868                                                 const char* descriptor,
869                                                 Handle<mirror::ClassLoader> class_loader1,
870                                                 Handle<mirror::ClassLoader> class_loader2)
871       REQUIRES_SHARED(Locks::mutator_lock_);
872 
873   bool IsSameMethodSignatureInDifferentClassContexts(Thread* self,
874                                                      ArtMethod* method,
875                                                      ObjPtr<mirror::Class> klass1,
876                                                      ObjPtr<mirror::Class> klass2)
877       REQUIRES_SHARED(Locks::mutator_lock_);
878 
879   bool LinkClass(Thread* self,
880                  const char* descriptor,
881                  Handle<mirror::Class> klass,
882                  Handle<mirror::ObjectArray<mirror::Class>> interfaces,
883                  MutableHandle<mirror::Class>* h_new_class_out)
884       REQUIRES_SHARED(Locks::mutator_lock_)
885       REQUIRES(!Locks::classlinker_classes_lock_);
886 
887   bool LinkSuperClass(Handle<mirror::Class> klass)
888       REQUIRES_SHARED(Locks::mutator_lock_);
889 
890   bool LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file)
891       REQUIRES_SHARED(Locks::mutator_lock_)
892       REQUIRES(!Locks::dex_lock_);
893 
894   bool LinkMethods(Thread* self,
895                    Handle<mirror::Class> klass,
896                    Handle<mirror::ObjectArray<mirror::Class>> interfaces,
897                    bool* out_new_conflict,
898                    ArtMethod** out_imt)
899       REQUIRES_SHARED(Locks::mutator_lock_);
900 
901   // A wrapper class representing the result of a method translation used for linking methods and
902   // updating superclass default methods. For each method in a classes vtable there are 4 states it
903   // could be in:
904   // 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
905   //    is the standard case and is true when the method is not overridable by a default method,
906   //    the class defines a concrete implementation of the method, the default method implementation
907   //    remains the same, or an abstract method stayed abstract.
908   // 2) The method must be translated to a different default method. We note this with
909   //    CreateTranslatedMethod.
910   // 3) The method must be replaced with a conflict method. This happens when a superclass
911   //    implements an interface with a default method and this class implements an unrelated
912   //    interface that also defines that default method. We note this with CreateConflictingMethod.
913   // 4) The method must be replaced with an abstract miranda method. This happens when a superclass
914   //    implements an interface with a default method and this class implements a subinterface of
915   //    the superclass's interface which declares the default method abstract. We note this with
916   //    CreateAbstractMethod.
917   //
918   // When a method translation is unnecessary (case #1), we don't put it into the
919   // default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
920   class MethodTranslation {
921    public:
922     // This slot must become a default conflict method.
CreateConflictingMethod()923     static MethodTranslation CreateConflictingMethod() {
924       return MethodTranslation(Type::kConflict, /*translation*/nullptr);
925     }
926 
927     // This slot must become an abstract method.
CreateAbstractMethod()928     static MethodTranslation CreateAbstractMethod() {
929       return MethodTranslation(Type::kAbstract, /*translation*/nullptr);
930     }
931 
932     // Use the given method as the current value for this vtable slot during translation.
CreateTranslatedMethod(ArtMethod * new_method)933     static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
934       return MethodTranslation(Type::kTranslation, new_method);
935     }
936 
937     // Returns true if this is a method that must become a conflict method.
IsInConflict()938     bool IsInConflict() const {
939       return type_ == Type::kConflict;
940     }
941 
942     // Returns true if this is a method that must become an abstract method.
IsAbstract()943     bool IsAbstract() const {
944       return type_ == Type::kAbstract;
945     }
946 
947     // Returns true if this is a method that must become a different method.
IsTranslation()948     bool IsTranslation() const {
949       return type_ == Type::kTranslation;
950     }
951 
952     // Get the translated version of this method.
GetTranslation()953     ArtMethod* GetTranslation() const {
954       DCHECK(IsTranslation());
955       DCHECK(translation_ != nullptr);
956       return translation_;
957     }
958 
959    private:
960     enum class Type {
961       kTranslation,
962       kConflict,
963       kAbstract,
964     };
965 
MethodTranslation(Type type,ArtMethod * translation)966     MethodTranslation(Type type, ArtMethod* translation)
967         : translation_(translation), type_(type) {}
968 
969     ArtMethod* const translation_;
970     const Type type_;
971   };
972 
973   // Links the virtual methods for the given class and records any default methods that will need to
974   // be updated later.
975   //
976   // Arguments:
977   // * self - The current thread.
978   // * klass - class, whose vtable will be filled in.
979   // * default_translations - Vtable index to new method map.
980   //                          Any vtable entries that need to be updated with new default methods
981   //                          are stored into the default_translations map. The default_translations
982   //                          map is keyed on the vtable index that needs to be updated. We use this
983   //                          map because if we override a default method with another default
984   //                          method we need to update the vtable to point to the new method.
985   //                          Unfortunately since we copy the ArtMethod* we cannot just do a simple
986   //                          scan, we therefore store the vtable index's that might need to be
987   //                          updated with the method they will turn into.
988   // TODO This whole default_translations thing is very dirty. There should be a better way.
989   bool LinkVirtualMethods(
990         Thread* self,
991         Handle<mirror::Class> klass,
992         /*out*/std::unordered_map<size_t, MethodTranslation>* default_translations)
993       REQUIRES_SHARED(Locks::mutator_lock_);
994 
995   // Sets up the interface lookup table (IFTable) in the correct order to allow searching for
996   // default methods.
997   bool SetupInterfaceLookupTable(Thread* self,
998                                  Handle<mirror::Class> klass,
999                                  Handle<mirror::ObjectArray<mirror::Class>> interfaces)
1000       REQUIRES_SHARED(Locks::mutator_lock_);
1001 
1002 
1003   enum class DefaultMethodSearchResult {
1004     kDefaultFound,
1005     kAbstractFound,
1006     kDefaultConflict
1007   };
1008 
1009   // Find the default method implementation for 'interface_method' in 'klass', if one exists.
1010   //
1011   // Arguments:
1012   // * self - The current thread.
1013   // * target_method - The method we are trying to find a default implementation for.
1014   // * klass - The class we are searching for a definition of target_method.
1015   // * out_default_method - The pointer we will store the found default method to on success.
1016   //
1017   // Return value:
1018   // * kDefaultFound - There were no conflicting method implementations found in the class while
1019   //                   searching for target_method. The default method implementation is stored into
1020   //                   out_default_method.
1021   // * kAbstractFound - There were no conflicting method implementations found in the class while
1022   //                   searching for target_method but no default implementation was found either.
1023   //                   out_default_method is set to null and the method should be considered not
1024   //                   implemented.
1025   // * kDefaultConflict - Conflicting method implementations were found when searching for
1026   //                      target_method. The value of *out_default_method is null.
1027   DefaultMethodSearchResult FindDefaultMethodImplementation(
1028       Thread* self,
1029       ArtMethod* target_method,
1030       Handle<mirror::Class> klass,
1031       /*out*/ArtMethod** out_default_method) const
1032       REQUIRES_SHARED(Locks::mutator_lock_);
1033 
1034   // Sets the imt entries and fixes up the vtable for the given class by linking all the interface
1035   // methods. See LinkVirtualMethods for an explanation of what default_translations is.
1036   bool LinkInterfaceMethods(
1037       Thread* self,
1038       Handle<mirror::Class> klass,
1039       const std::unordered_map<size_t, MethodTranslation>& default_translations,
1040       bool* out_new_conflict,
1041       ArtMethod** out_imt)
1042       REQUIRES_SHARED(Locks::mutator_lock_);
1043 
1044   bool LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size)
1045       REQUIRES_SHARED(Locks::mutator_lock_);
1046   bool LinkInstanceFields(Thread* self, Handle<mirror::Class> klass)
1047       REQUIRES_SHARED(Locks::mutator_lock_);
1048   bool LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static, size_t* class_size)
1049       REQUIRES_SHARED(Locks::mutator_lock_);
1050   void CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)
1051       REQUIRES_SHARED(Locks::mutator_lock_);
1052 
1053   void CheckProxyConstructor(ArtMethod* constructor) const
1054       REQUIRES_SHARED(Locks::mutator_lock_);
1055   void CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const
1056       REQUIRES_SHARED(Locks::mutator_lock_);
1057 
GetDexCacheCount()1058   size_t GetDexCacheCount() REQUIRES_SHARED(Locks::mutator_lock_, Locks::dex_lock_) {
1059     return dex_caches_.size();
1060   }
GetDexCachesData()1061   const std::list<DexCacheData>& GetDexCachesData()
1062       REQUIRES_SHARED(Locks::mutator_lock_, Locks::dex_lock_) {
1063     return dex_caches_;
1064   }
1065 
1066   void CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out)
1067       REQUIRES_SHARED(Locks::mutator_lock_);
1068   void CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype, ArtMethod* out)
1069       REQUIRES_SHARED(Locks::mutator_lock_);
1070 
1071   // Register a class loader and create its class table and allocator. Should not be called if
1072   // these are already created.
1073   void RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader)
1074       REQUIRES_SHARED(Locks::mutator_lock_)
1075       REQUIRES(Locks::classlinker_classes_lock_);
1076 
1077   // Insert a new class table if not found.
1078   ClassTable* InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader)
1079       REQUIRES_SHARED(Locks::mutator_lock_)
1080       REQUIRES(Locks::classlinker_classes_lock_);
1081 
1082   // EnsureResolved is called to make sure that a class in the class_table_ has been resolved
1083   // before returning it to the caller. Its the responsibility of the thread that placed the class
1084   // in the table to make it resolved. The thread doing resolution must notify on the class' lock
1085   // when resolution has occurred. This happens in mirror::Class::SetStatus. As resolution may
1086   // retire a class, the version of the class in the table is returned and this may differ from
1087   // the class passed in.
1088   mirror::Class* EnsureResolved(Thread* self, const char* descriptor, ObjPtr<mirror::Class> klass)
1089       WARN_UNUSED
1090       REQUIRES_SHARED(Locks::mutator_lock_)
1091       REQUIRES(!Locks::dex_lock_);
1092 
1093   void FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
1094                                     ObjPtr<mirror::Class> new_class)
1095       REQUIRES_SHARED(Locks::mutator_lock_);
1096 
1097   void SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass)
1098       REQUIRES_SHARED(Locks::mutator_lock_);
1099 
1100   // Return the quick generic JNI stub for testing.
1101   const void* GetRuntimeQuickGenericJniStub() const;
1102 
1103   bool CanWeInitializeClass(ObjPtr<mirror::Class> klass,
1104                             bool can_init_statics,
1105                             bool can_init_parents)
1106       REQUIRES_SHARED(Locks::mutator_lock_);
1107 
1108   void UpdateClassMethods(ObjPtr<mirror::Class> klass,
1109                           LengthPrefixedArray<ArtMethod>* new_methods)
1110       REQUIRES_SHARED(Locks::mutator_lock_)
1111       REQUIRES(!Locks::classlinker_classes_lock_);
1112 
1113   // new_class_set is the set of classes that were read from the class table section in the image.
1114   // If there was no class table section, it is null.
1115   bool UpdateAppImageClassLoadersAndDexCaches(
1116       gc::space::ImageSpace* space,
1117       Handle<mirror::ClassLoader> class_loader,
1118       Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
1119       ClassTable::ClassSet* new_class_set,
1120       bool* out_forward_dex_cache_array,
1121       std::string* out_error_msg)
1122       REQUIRES(!Locks::dex_lock_)
1123       REQUIRES_SHARED(Locks::mutator_lock_);
1124 
1125   // Check that c1 == FindSystemClass(self, descriptor). Abort with class dumps otherwise.
1126   void CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor)
1127       REQUIRES(!Locks::dex_lock_)
1128       REQUIRES_SHARED(Locks::mutator_lock_);
1129 
1130   // Allocate method arrays for interfaces.
1131   bool AllocateIfTableMethodArrays(Thread* self,
1132                                    Handle<mirror::Class> klass,
1133                                    Handle<mirror::IfTable> iftable)
1134       REQUIRES_SHARED(Locks::mutator_lock_);
1135 
1136   // Sets imt_ref appropriately for LinkInterfaceMethods.
1137   // If there is no method in the imt location of imt_ref it will store the given method there.
1138   // Otherwise it will set the conflict method which will figure out which method to use during
1139   // runtime.
1140   void SetIMTRef(ArtMethod* unimplemented_method,
1141                  ArtMethod* imt_conflict_method,
1142                  ArtMethod* current_method,
1143                  /*out*/bool* new_conflict,
1144                  /*out*/ArtMethod** imt_ref) REQUIRES_SHARED(Locks::mutator_lock_);
1145 
1146   void FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
1147                           ArtMethod* unimplemented_method,
1148                           ArtMethod* imt_conflict_method,
1149                           ObjPtr<mirror::Class> klass,
1150                           bool create_conflict_tables,
1151                           bool ignore_copied_methods,
1152                           /*out*/bool* new_conflict,
1153                           /*out*/ArtMethod** imt) REQUIRES_SHARED(Locks::mutator_lock_);
1154 
1155   void FillImtFromSuperClass(Handle<mirror::Class> klass,
1156                              ArtMethod* unimplemented_method,
1157                              ArtMethod* imt_conflict_method,
1158                              bool* new_conflict,
1159                              ArtMethod** imt) REQUIRES_SHARED(Locks::mutator_lock_);
1160 
1161   std::vector<const DexFile*> boot_class_path_;
1162   std::vector<std::unique_ptr<const DexFile>> boot_dex_files_;
1163 
1164   // JNI weak globals and side data to allow dex caches to get unloaded. We lazily delete weak
1165   // globals when we register new dex files.
1166   std::list<DexCacheData> dex_caches_ GUARDED_BY(Locks::dex_lock_);
1167 
1168   // This contains the class loaders which have class tables. It is populated by
1169   // InsertClassTableForClassLoader.
1170   std::list<ClassLoaderData> class_loaders_
1171       GUARDED_BY(Locks::classlinker_classes_lock_);
1172 
1173   // Boot class path table. Since the class loader for this is null.
1174   ClassTable boot_class_table_ GUARDED_BY(Locks::classlinker_classes_lock_);
1175 
1176   // New class roots, only used by CMS since the GC needs to mark these in the pause.
1177   std::vector<GcRoot<mirror::Class>> new_class_roots_ GUARDED_BY(Locks::classlinker_classes_lock_);
1178 
1179   // Boot image oat files with new .bss GC roots to be visited in the pause by CMS.
1180   std::vector<const OatFile*> new_bss_roots_boot_oat_files_
1181       GUARDED_BY(Locks::classlinker_classes_lock_);
1182 
1183   // Number of times we've searched dex caches for a class. After a certain number of misses we move
1184   // the classes into the class_table_ to avoid dex cache based searches.
1185   Atomic<uint32_t> failed_dex_cache_class_lookups_;
1186 
1187   // Well known mirror::Class roots.
1188   GcRoot<mirror::ObjectArray<mirror::Class>> class_roots_;
1189 
1190   // The interface table used by all arrays.
1191   GcRoot<mirror::IfTable> array_iftable_;
1192 
1193   // A cache of the last FindArrayClass results. The cache serves to avoid creating array class
1194   // descriptors for the sake of performing FindClass.
1195   static constexpr size_t kFindArrayCacheSize = 16;
1196   GcRoot<mirror::Class> find_array_class_cache_[kFindArrayCacheSize];
1197   size_t find_array_class_cache_next_victim_;
1198 
1199   bool init_done_;
1200   bool log_new_roots_ GUARDED_BY(Locks::classlinker_classes_lock_);
1201 
1202   InternTable* intern_table_;
1203 
1204   // Trampolines within the image the bounce to runtime entrypoints. Done so that there is a single
1205   // patch point within the image. TODO: make these proper relocations.
1206   const void* quick_resolution_trampoline_;
1207   const void* quick_imt_conflict_trampoline_;
1208   const void* quick_generic_jni_trampoline_;
1209   const void* quick_to_interpreter_bridge_trampoline_;
1210 
1211   // Image pointer size.
1212   PointerSize image_pointer_size_;
1213 
1214   class FindVirtualMethodHolderVisitor;
1215   friend struct CompilationHelper;  // For Compile in ImageTest.
1216   friend class ImageDumper;  // for DexLock
1217   friend class ImageWriter;  // for GetClassRoots
1218   friend class VMClassLoader;  // for LookupClass and FindClassInBaseDexClassLoader.
1219   friend class JniCompilerTest;  // for GetRuntimeQuickGenericJniStub
1220   friend class JniInternalTest;  // for GetRuntimeQuickGenericJniStub
1221   ART_FRIEND_TEST(ClassLinkerTest, RegisterDexFileName);  // for DexLock, and RegisterDexFileLocked
1222   ART_FRIEND_TEST(mirror::DexCacheMethodHandlesTest, Open);  // for AllocDexCache
1223   ART_FRIEND_TEST(mirror::DexCacheTest, Open);  // for AllocDexCache
1224   DISALLOW_COPY_AND_ASSIGN(ClassLinker);
1225 };
1226 
1227 class ClassLoadCallback {
1228  public:
~ClassLoadCallback()1229   virtual ~ClassLoadCallback() {}
1230 
1231   // If set we will replace initial_class_def & initial_dex_file with the final versions. The
1232   // callback author is responsible for ensuring these are allocated in such a way they can be
1233   // cleaned up if another transformation occurs. Note that both must be set or null/unchanged on
1234   // return.
1235   // Note: the class may be temporary, in which case a following ClassPrepare event will be a
1236   //       different object. It is the listener's responsibility to handle this.
1237   // Note: This callback is rarely useful so a default implementation has been given that does
1238   //       nothing.
ClassPreDefine(const char * descriptor ATTRIBUTE_UNUSED,Handle<mirror::Class> klass ATTRIBUTE_UNUSED,Handle<mirror::ClassLoader> class_loader ATTRIBUTE_UNUSED,const DexFile & initial_dex_file ATTRIBUTE_UNUSED,const DexFile::ClassDef & initial_class_def ATTRIBUTE_UNUSED,DexFile const ** final_dex_file ATTRIBUTE_UNUSED,DexFile::ClassDef const ** final_class_def ATTRIBUTE_UNUSED)1239   virtual void ClassPreDefine(const char* descriptor ATTRIBUTE_UNUSED,
1240                               Handle<mirror::Class> klass ATTRIBUTE_UNUSED,
1241                               Handle<mirror::ClassLoader> class_loader ATTRIBUTE_UNUSED,
1242                               const DexFile& initial_dex_file ATTRIBUTE_UNUSED,
1243                               const DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
1244                               /*out*/DexFile const** final_dex_file ATTRIBUTE_UNUSED,
1245                               /*out*/DexFile::ClassDef const** final_class_def ATTRIBUTE_UNUSED)
1246       REQUIRES_SHARED(Locks::mutator_lock_) {}
1247 
1248   // A class has been loaded.
1249   // Note: the class may be temporary, in which case a following ClassPrepare event will be a
1250   //       different object. It is the listener's responsibility to handle this.
1251   virtual void ClassLoad(Handle<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1252 
1253   // A class has been prepared, i.e., resolved. As the ClassLoad event might have been for a
1254   // temporary class, provide both the former and the current class.
1255   virtual void ClassPrepare(Handle<mirror::Class> temp_klass,
1256                             Handle<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1257 };
1258 
1259 }  // namespace art
1260 
1261 #endif  // ART_RUNTIME_CLASS_LINKER_H_
1262