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