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