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