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