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