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