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