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