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