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 <deque>
21 #include <string>
22 #include <utility>
23 #include <vector>
24 
25 #include "base/allocator.h"
26 #include "base/hash_set.h"
27 #include "base/macros.h"
28 #include "base/mutex.h"
29 #include "dex_file.h"
30 #include "gc_root.h"
31 #include "jni.h"
32 #include "oat_file.h"
33 #include "object_callbacks.h"
34 
35 namespace art {
36 
37 namespace gc {
38 namespace space {
39   class ImageSpace;
40 }  // namespace space
41 }  // namespace gc
42 namespace mirror {
43   class ClassLoader;
44   class DexCache;
45   class DexCachePointerArray;
46   class DexCacheTest_Open_Test;
47   class IfTable;
48   template<class T> class ObjectArray;
49   class StackTraceElement;
50 }  // namespace mirror
51 
52 template<class T> class Handle;
53 template<class T> class MutableHandle;
54 class InternTable;
55 template<class T> class ObjectLock;
56 class Runtime;
57 class ScopedObjectAccessAlreadyRunnable;
58 template<size_t kNumReferences> class PACKED(4) StackHandleScope;
59 
60 typedef bool (ClassVisitor)(mirror::Class* c, void* arg);
61 
62 enum VisitRootFlags : uint8_t;
63 
64 class ClassLinker {
65  public:
66   // Well known mirror::Class roots accessed via GetClassRoot.
67   enum ClassRoot {
68     kJavaLangClass,
69     kJavaLangObject,
70     kClassArrayClass,
71     kObjectArrayClass,
72     kJavaLangString,
73     kJavaLangDexCache,
74     kJavaLangRefReference,
75     kJavaLangReflectConstructor,
76     kJavaLangReflectField,
77     kJavaLangReflectMethod,
78     kJavaLangReflectProxy,
79     kJavaLangStringArrayClass,
80     kJavaLangReflectConstructorArrayClass,
81     kJavaLangReflectFieldArrayClass,
82     kJavaLangReflectMethodArrayClass,
83     kJavaLangClassLoader,
84     kJavaLangThrowable,
85     kJavaLangClassNotFoundException,
86     kJavaLangStackTraceElement,
87     kPrimitiveBoolean,
88     kPrimitiveByte,
89     kPrimitiveChar,
90     kPrimitiveDouble,
91     kPrimitiveFloat,
92     kPrimitiveInt,
93     kPrimitiveLong,
94     kPrimitiveShort,
95     kPrimitiveVoid,
96     kBooleanArrayClass,
97     kByteArrayClass,
98     kCharArrayClass,
99     kDoubleArrayClass,
100     kFloatArrayClass,
101     kIntArrayClass,
102     kLongArrayClass,
103     kShortArrayClass,
104     kJavaLangStackTraceElementArrayClass,
105     kClassRootsMax,
106   };
107 
108   explicit ClassLinker(InternTable* intern_table);
109   ~ClassLinker();
110 
111   // Initialize class linker by bootstraping from dex files.
112   void InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path)
113       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
114 
115   // Initialize class linker from one or more images.
116   void InitFromImage() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
117 
118   // Finds a class by its descriptor, loading it if necessary.
119   // If class_loader is null, searches boot_class_path_.
120   mirror::Class* FindClass(Thread* self, const char* descriptor,
121                            Handle<mirror::ClassLoader> class_loader)
122       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
123 
124   // Finds a class in the path class loader, loading it if necessary without using JNI. Hash
125   // function is supposed to be ComputeModifiedUtf8Hash(descriptor). Returns true if the
126   // class-loader chain could be handled, false otherwise, i.e., a non-supported class-loader
127   // was encountered while walking the parent chain (currently only BootClassLoader and
128   // PathClassLoader are supported).
129   bool FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
130                                   Thread* self, const char* descriptor, size_t hash,
131                                   Handle<mirror::ClassLoader> class_loader,
132                                   mirror::Class** result)
133       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
134 
135   // Finds a class by its descriptor using the "system" class loader, ie by searching the
136   // boot_class_path_.
137   mirror::Class* FindSystemClass(Thread* self, const char* descriptor)
138       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
139 
140   // Finds the array class given for the element class.
141   mirror::Class* FindArrayClass(Thread* self, mirror::Class** element_class)
142       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
143 
144   // Returns true if the class linker is initialized.
IsInitialized()145   bool IsInitialized() const {
146     return init_done_;
147   }
148 
149   // Define a new a class based on a ClassDef from a DexFile
150   mirror::Class* DefineClass(Thread* self, const char* descriptor, size_t hash,
151                              Handle<mirror::ClassLoader> class_loader,
152                              const DexFile& dex_file, const DexFile::ClassDef& dex_class_def)
153       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
154 
155   // Finds a class by its descriptor, returning null if it isn't wasn't loaded
156   // by the given 'class_loader'.
157   mirror::Class* LookupClass(Thread* self, const char* descriptor, size_t hash,
158                              mirror::ClassLoader* class_loader)
159       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
160       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
161 
162   // Finds all the classes with the given descriptor, regardless of ClassLoader.
163   void LookupClasses(const char* descriptor, std::vector<mirror::Class*>& classes)
164       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
165       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
166 
167   mirror::Class* FindPrimitiveClass(char type) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
168 
169   // General class unloading is not supported, this is used to prune
170   // unwanted classes during image writing.
171   bool RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader)
172       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
173       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
174 
175   void DumpAllClasses(int flags)
176       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
177       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
178 
179   void DumpForSigQuit(std::ostream& os)
180       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_);
181 
182   size_t NumLoadedClasses()
183       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
184       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
185 
186   // Resolve a String with the given index from the DexFile, storing the
187   // result in the DexCache. The referrer is used to identify the
188   // target DexCache and ClassLoader to use for resolution.
189   mirror::String* ResolveString(uint32_t string_idx, ArtMethod* referrer)
190       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
191 
192   // Resolve a String with the given index from the DexFile, storing the
193   // result in the DexCache.
194   mirror::String* ResolveString(const DexFile& dex_file, uint32_t string_idx,
195                                 Handle<mirror::DexCache> dex_cache)
196       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
197 
198   // Resolve a Type with the given index from the DexFile, storing the
199   // result in the DexCache. The referrer is used to identity the
200   // target DexCache and ClassLoader to use for resolution.
201   mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx, mirror::Class* referrer)
202       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
203 
204   // Resolve a Type with the given index from the DexFile, storing the
205   // result in the DexCache. The referrer is used to identify the
206   // target DexCache and ClassLoader to use for resolution.
207   mirror::Class* ResolveType(uint16_t type_idx, ArtMethod* referrer)
208       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
209 
210   mirror::Class* ResolveType(uint16_t type_idx, ArtField* referrer)
211       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
212 
213   // Resolve a type with the given ID from the DexFile, storing the
214   // result in DexCache. The ClassLoader is used to search for the
215   // type, since it may be referenced from but not contained within
216   // the given DexFile.
217   mirror::Class* ResolveType(const DexFile& dex_file, uint16_t type_idx,
218                              Handle<mirror::DexCache> dex_cache,
219                              Handle<mirror::ClassLoader> class_loader)
220       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
221 
222   // Resolve a method with a given ID from the DexFile, storing the
223   // result in DexCache. The ClassLinker and ClassLoader are used as
224   // in ResolveType. What is unique is the method type argument which
225   // is used to determine if this method is a direct, static, or
226   // virtual method.
227   ArtMethod* ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
228                            Handle<mirror::DexCache> dex_cache,
229                            Handle<mirror::ClassLoader> class_loader, ArtMethod* referrer,
230                            InvokeType type)
231       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
232 
233   ArtMethod* GetResolvedMethod(uint32_t method_idx, ArtMethod* referrer)
234       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
235   ArtMethod* ResolveMethod(Thread* self, uint32_t method_idx, ArtMethod* referrer, InvokeType type)
236       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
237 
238   ArtField* GetResolvedField(uint32_t field_idx, mirror::Class* field_declaring_class)
239       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
240   ArtField* GetResolvedField(uint32_t field_idx, mirror::DexCache* dex_cache)
241       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
242   ArtField* ResolveField(uint32_t field_idx, ArtMethod* referrer, bool is_static)
243       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
244 
245   // Resolve a field with a given ID from the DexFile, storing the
246   // result in DexCache. The ClassLinker and ClassLoader are used as
247   // in ResolveType. What is unique is the is_static argument which is
248   // used to determine if we are resolving a static or non-static
249   // field.
250   ArtField* ResolveField(const DexFile& dex_file,
251                                  uint32_t field_idx,
252                                  Handle<mirror::DexCache> dex_cache,
253                                  Handle<mirror::ClassLoader> class_loader,
254                                  bool is_static)
255       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
256 
257   // Resolve a field with a given ID from the DexFile, storing the
258   // result in DexCache. The ClassLinker and ClassLoader are used as
259   // in ResolveType. No is_static argument is provided so that Java
260   // field resolution semantics are followed.
261   ArtField* ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
262                             Handle<mirror::DexCache> dex_cache,
263                             Handle<mirror::ClassLoader> class_loader)
264       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
265 
266   // Get shorty from method index without resolution. Used to do handlerization.
267   const char* MethodShorty(uint32_t method_idx, ArtMethod* referrer, uint32_t* length)
268       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
269 
270   // Returns true on success, false if there's an exception pending.
271   // can_run_clinit=false allows the compiler to attempt to init a class,
272   // given the restriction that no <clinit> execution is possible.
273   bool EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
274                          bool can_init_parents)
275       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
276 
277   // Initializes classes that have instances in the image but that have
278   // <clinit> methods so they could not be initialized by the compiler.
279   void RunRootClinits() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
280 
281   void RegisterDexFile(const DexFile& dex_file)
282       LOCKS_EXCLUDED(dex_lock_)
283       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
284   void RegisterDexFile(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
285       LOCKS_EXCLUDED(dex_lock_)
286       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
287 
288   const OatFile* RegisterOatFile(const OatFile* oat_file)
289       LOCKS_EXCLUDED(dex_lock_);
290 
GetBootClassPath()291   const std::vector<const DexFile*>& GetBootClassPath() {
292     return boot_class_path_;
293   }
294 
295   // Returns the first non-image oat file in the class path.
296   const OatFile* GetPrimaryOatFile()
297       LOCKS_EXCLUDED(dex_lock_);
298 
299   void VisitClasses(ClassVisitor* visitor, void* arg)
300       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
301       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
302 
303   // Less efficient variant of VisitClasses that copies the class_table_ into secondary storage
304   // so that it can visit individual classes without holding the doesn't hold the
305   // Locks::classlinker_classes_lock_. As the Locks::classlinker_classes_lock_ isn't held this code
306   // can race with insertion and deletion of classes while the visitor is being called.
307   void VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg)
308       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
309 
310   void VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags)
311       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
312       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
313   void VisitRoots(RootVisitor* visitor, VisitRootFlags flags)
314       LOCKS_EXCLUDED(dex_lock_)
315       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
316 
317   mirror::DexCache* FindDexCache(const DexFile& dex_file)
318       LOCKS_EXCLUDED(dex_lock_)
319       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
320   bool IsDexFileRegistered(const DexFile& dex_file)
321       LOCKS_EXCLUDED(dex_lock_) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
322   void FixupDexCaches(ArtMethod* resolution_method)
323       LOCKS_EXCLUDED(dex_lock_)
324       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
325 
326   // Finds or creates the oat file holding dex_location. Then loads and returns
327   // all corresponding dex files (there may be more than one dex file loaded
328   // in the case of multidex).
329   // This may return the original, unquickened dex files if the oat file could
330   // not be generated.
331   //
332   // Returns an empty vector if the dex files could not be loaded. In this
333   // case, there will be at least one error message returned describing why no
334   // dex files could not be loaded. The 'error_msgs' argument must not be
335   // null, regardless of whether there is an error or not.
336   //
337   // This method should not be called with the mutator_lock_ held, because it
338   // could end up starving GC if we need to generate or relocate any oat
339   // files.
340   std::vector<std::unique_ptr<const DexFile>>  OpenDexFilesFromOat(
341       const char* dex_location, const char* oat_location,
342       std::vector<std::string>* error_msgs)
343       LOCKS_EXCLUDED(dex_lock_, Locks::mutator_lock_);
344 
345   // Allocate an instance of a java.lang.Object.
346   mirror::Object* AllocObject(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
347 
348   // TODO: replace this with multiple methods that allocate the correct managed type.
349   template <class T>
350   mirror::ObjectArray<T>* AllocObjectArray(Thread* self, size_t length)
351       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
352 
353   mirror::ObjectArray<mirror::Class>* AllocClassArray(Thread* self, size_t length)
354       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
355 
356   mirror::ObjectArray<mirror::String>* AllocStringArray(Thread* self, size_t length)
357       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
358 
359   ArtMethod* AllocArtMethodArray(Thread* self, size_t length);
360 
361   mirror::PointerArray* AllocPointerArray(Thread* self, size_t length)
362       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
363 
364   mirror::IfTable* AllocIfTable(Thread* self, size_t ifcount)
365       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
366 
367   ArtField* AllocArtFieldArray(Thread* self, size_t length)
368       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
369 
370   mirror::ObjectArray<mirror::StackTraceElement>* AllocStackTraceElementArray(Thread* self,
371                                                                               size_t length)
372       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
373 
374   void VerifyClass(Thread* self, Handle<mirror::Class> klass)
375       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
376   bool VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
377                                mirror::Class::Status& oat_file_class_status)
378       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
379   void ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
380                                          Handle<mirror::Class> klass)
381       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
382   void ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, ArtMethod* klass)
383       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
384 
385   mirror::Class* CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
386                                   jobjectArray interfaces, jobject loader, jobjectArray methods,
387                                   jobjectArray throws)
388       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
389   std::string GetDescriptorForProxy(mirror::Class* proxy_class)
390       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
391   ArtMethod* FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method)
392       LOCKS_EXCLUDED(dex_lock_)
393       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
394 
395   // Get the oat code for a method when its class isn't yet initialized
396   const void* GetQuickOatCodeFor(ArtMethod* method)
397       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
398 
399   // Get the oat code for a method from a method index.
400   const void* GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
401                                  uint32_t method_idx)
402       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
403 
404   // Get compiled code for a method, return null if no code
405   // exists. This is unlike Get..OatCodeFor which will return a bridge
406   // or interpreter entrypoint.
407   const void* GetOatMethodQuickCodeFor(ArtMethod* method)
408       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
409 
410   pid_t GetClassesLockOwner();  // For SignalCatcher.
411   pid_t GetDexLockOwner();  // For SignalCatcher.
412 
413   mirror::Class* GetClassRoot(ClassRoot class_root) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
414 
415   static const char* GetClassRootDescriptor(ClassRoot class_root);
416 
417   // Is the given entry point quick code to run the resolution stub?
418   bool IsQuickResolutionStub(const void* entry_point) const;
419 
420   // Is the given entry point quick code to bridge into the interpreter?
421   bool IsQuickToInterpreterBridge(const void* entry_point) const;
422 
423   // Is the given entry point quick code to run the generic JNI stub?
424   bool IsQuickGenericJniStub(const void* entry_point) const;
425 
GetInternTable()426   InternTable* GetInternTable() const {
427     return intern_table_;
428   }
429 
430   // Set the entrypoints up for method to the given code.
431   void SetEntryPointsToCompiledCode(ArtMethod* method, const void* method_code) const
432       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
433 
434   // Set the entrypoints up for method to the enter the interpreter.
435   void SetEntryPointsToInterpreter(ArtMethod* method) const
436       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
437 
438   // Attempts to insert a class into a class table.  Returns null if
439   // the class was inserted, otherwise returns an existing class with
440   // the same descriptor and ClassLoader.
441   mirror::Class* InsertClass(const char* descriptor, mirror::Class* klass, size_t hash)
442       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
443       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
444 
GetClassRoots()445   mirror::ObjectArray<mirror::Class>* GetClassRoots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
446     mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
447     DCHECK(class_roots != nullptr);
448     return class_roots;
449   }
450 
451   // Move all of the image classes into the class table for faster lookups.
452   void MoveImageClassesToClassTable()
453       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
454       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
455   // Move the class table to the pre-zygote table to reduce memory usage. This works by ensuring
456   // that no more classes are ever added to the pre zygote table which makes it that the pages
457   // always remain shared dirty instead of private dirty.
458   void MoveClassTableToPreZygote()
459       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
460       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
461 
462   // Returns true if the method can be called with its direct code pointer, false otherwise.
463   bool MayBeCalledWithDirectCodePointer(ArtMethod* m)
464       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
465 
466   // Creates a GlobalRef PathClassLoader that can be used to load classes from the given dex files.
467   // Note: the objects are not completely set up. Do not use this outside of tests and the compiler.
468   jobject CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files)
469       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
470 
GetImagePointerSize()471   size_t GetImagePointerSize() const {
472     DCHECK(ValidPointerSize(image_pointer_size_)) << image_pointer_size_;
473     return image_pointer_size_;
474   }
475 
476   // Used by image writer for checking.
477   bool ClassInClassTable(mirror::Class* klass)
478       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
479       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
480 
481   ArtMethod* CreateRuntimeMethod();
482 
483   // Clear the ArrayClass cache. This is necessary when cleaning up for the image, as the cache
484   // entries are roots, but potentially not image classes.
485   void DropFindArrayClassCache() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
486 
487  private:
488   const OatFile::OatMethod FindOatMethodFor(ArtMethod* method, bool* found)
489       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
490 
491   OatFile& GetImageOatFile(gc::space::ImageSpace* space)
492       LOCKS_EXCLUDED(dex_lock_)
493       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
494 
495   void FinishInit(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
496 
497   // For early bootstrapping by Init
498   mirror::Class* AllocClass(Thread* self, mirror::Class* java_lang_Class, uint32_t class_size)
499       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
500 
501   // Alloc* convenience functions to avoid needing to pass in mirror::Class*
502   // values that are known to the ClassLinker such as
503   // kObjectArrayClass and kJavaLangString etc.
504   mirror::Class* AllocClass(Thread* self, uint32_t class_size)
505       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
506   mirror::DexCache* AllocDexCache(Thread* self, const DexFile& dex_file)
507       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
508 
509   mirror::Class* CreatePrimitiveClass(Thread* self, Primitive::Type type)
510       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
511   mirror::Class* InitializePrimitiveClass(mirror::Class* primitive_class, Primitive::Type type)
512       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
513 
514 
515   mirror::Class* CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
516                                   Handle<mirror::ClassLoader> class_loader)
517       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
518 
519   void AppendToBootClassPath(Thread* self, const DexFile& dex_file)
520       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
521   void AppendToBootClassPath(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
522       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
523 
524   // Precomputes size needed for Class, in the case of a non-temporary class this size must be
525   // sufficient to hold all static fields.
526   uint32_t SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
527                                             const DexFile::ClassDef& dex_class_def);
528 
529   // Setup the classloader, class def index, type idx so that we can insert this class in the class
530   // table.
531   void SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
532                   Handle<mirror::Class> klass, mirror::ClassLoader* class_loader)
533       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
534 
535   void LoadClass(Thread* self, const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
536                  Handle<mirror::Class> klass)
537       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
538   void LoadClassMembers(Thread* self, const DexFile& dex_file, const uint8_t* class_data,
539                         Handle<mirror::Class> klass, const OatFile::OatClass* oat_class)
540       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
541 
542   void LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
543                  ArtField* dst)
544       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
545 
546   void LoadMethod(Thread* self, const DexFile& dex_file, const ClassDataItemIterator& it,
547                   Handle<mirror::Class> klass, ArtMethod* dst)
548       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
549 
550   void FixupStaticTrampolines(mirror::Class* klass) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
551 
552   // Finds the associated oat class for a dex_file and descriptor. Returns an invalid OatClass on
553   // error and sets found to false.
554   OatFile::OatClass FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, bool* found)
555       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
556 
557   void RegisterDexFileLocked(const DexFile& dex_file, Handle<mirror::DexCache> dex_cache)
558       EXCLUSIVE_LOCKS_REQUIRED(dex_lock_)
559       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
560   bool IsDexFileRegisteredLocked(const DexFile& dex_file)
561       SHARED_LOCKS_REQUIRED(dex_lock_, Locks::mutator_lock_);
562 
563   bool InitializeClass(Thread* self, Handle<mirror::Class> klass, bool can_run_clinit,
564                        bool can_init_parents)
565       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
566   bool WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
567                               ObjectLock<mirror::Class>& lock);
568   bool ValidateSuperClassDescriptors(Handle<mirror::Class> klass)
569       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
570 
571   bool IsSameDescriptorInDifferentClassContexts(Thread* self, const char* descriptor,
572                                                 Handle<mirror::ClassLoader> class_loader1,
573                                                 Handle<mirror::ClassLoader> class_loader2)
574       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
575 
576   bool IsSameMethodSignatureInDifferentClassContexts(Thread* self, ArtMethod* method,
577                                                      mirror::Class* klass1, mirror::Class* klass2)
578       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
579 
580   bool LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
581                  Handle<mirror::ObjectArray<mirror::Class>> interfaces,
582                  MutableHandle<mirror::Class>* h_new_class_out)
583       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
584 
585   bool LinkSuperClass(Handle<mirror::Class> klass)
586       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
587 
588   bool LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file)
589       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
590 
591   bool LinkMethods(Thread* self, Handle<mirror::Class> klass,
592                    Handle<mirror::ObjectArray<mirror::Class>> interfaces,
593                    ArtMethod** out_imt)
594       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
595 
596   bool LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass)
597       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
598 
599   bool LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
600                             Handle<mirror::ObjectArray<mirror::Class>> interfaces,
601                             ArtMethod** out_imt)
602       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
603 
604   bool LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size)
605       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
606   bool LinkInstanceFields(Thread* self, Handle<mirror::Class> klass)
607       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
608   bool LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static, size_t* class_size)
609       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
610   void LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
611                 uint32_t class_def_method_index)
612       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
613   void CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)
614       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
615 
616   void CheckProxyConstructor(ArtMethod* constructor) const
617       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
618   void CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const
619       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
620 
621   // For use by ImageWriter to find DexCaches for its roots
DexLock()622   ReaderWriterMutex* DexLock()
623       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) LOCK_RETURNED(dex_lock_) {
624     return &dex_lock_;
625   }
GetDexCacheCount()626   size_t GetDexCacheCount() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, dex_lock_) {
627     return dex_caches_.size();
628   }
629   mirror::DexCache* GetDexCache(size_t idx) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, dex_lock_);
630 
631   const OatFile* FindOpenedOatFileFromOatLocation(const std::string& oat_location)
632       LOCKS_EXCLUDED(dex_lock_);
633 
634   // Returns the boot image oat file.
635   const OatFile* GetBootOatFile() SHARED_LOCKS_REQUIRED(dex_lock_);
636 
637   void CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out)
638       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
639   void CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype, ArtMethod* out)
640       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
641 
642   // Ensures that methods have the kAccPreverified bit set. We use the kAccPreverfied bit on the
643   // class access flags to determine whether this has been done before.
644   void EnsurePreverifiedMethods(Handle<mirror::Class> c)
645       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
646 
647   mirror::Class* LookupClassFromTableLocked(const char* descriptor,
648                                             mirror::ClassLoader* class_loader,
649                                             size_t hash)
650       SHARED_LOCKS_REQUIRED(Locks::classlinker_classes_lock_, Locks::mutator_lock_);
651 
652   mirror::Class* UpdateClass(const char* descriptor, mirror::Class* klass, size_t hash)
653       LOCKS_EXCLUDED(Locks::classlinker_classes_lock_)
654       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
655 
656   mirror::Class* LookupClassFromImage(const char* descriptor)
657       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
658 
659   // EnsureResolved is called to make sure that a class in the class_table_ has been resolved
660   // before returning it to the caller. Its the responsibility of the thread that placed the class
661   // in the table to make it resolved. The thread doing resolution must notify on the class' lock
662   // when resolution has occurred. This happens in mirror::Class::SetStatus. As resolution may
663   // retire a class, the version of the class in the table is returned and this may differ from
664   // the class passed in.
665   mirror::Class* EnsureResolved(Thread* self, const char* descriptor, mirror::Class* klass)
666       WARN_UNUSED SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
667 
668   void FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class)
669       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
670 
671   void SetClassRoot(ClassRoot class_root, mirror::Class* klass)
672       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
673 
674   // Return the quick generic JNI stub for testing.
675   const void* GetRuntimeQuickGenericJniStub() const;
676 
677   // Throw the class initialization failure recorded when first trying to initialize the given
678   // class.
679   // Note: Currently we only store the descriptor, so we cannot throw the exact throwable, only
680   //       a recreation with a custom string.
681   void ThrowEarlierClassFailure(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
682 
683   // Check for duplicate class definitions of the given oat file against all open oat files.
684   bool HasCollisions(const OatFile* oat_file, std::string* error_msg) LOCKS_EXCLUDED(dex_lock_);
685 
686   bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
687       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
688 
689   bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, bool can_init_parents)
690       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
691 
692   void UpdateClassVirtualMethods(mirror::Class* klass, ArtMethod* new_methods,
693                                  size_t new_num_methods)
694       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) LOCKS_EXCLUDED(Locks::classlinker_classes_lock_);
695 
696   std::vector<const DexFile*> boot_class_path_;
697   std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
698 
699   mutable ReaderWriterMutex dex_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
700   std::vector<size_t> new_dex_cache_roots_ GUARDED_BY(dex_lock_);
701   std::vector<GcRoot<mirror::DexCache>> dex_caches_ GUARDED_BY(dex_lock_);
702   std::vector<const OatFile*> oat_files_ GUARDED_BY(dex_lock_);
703 
704   class ClassDescriptorHashEquals {
705    public:
706     // Same class loader and descriptor.
707     std::size_t operator()(const GcRoot<mirror::Class>& root) const NO_THREAD_SAFETY_ANALYSIS;
708     bool operator()(const GcRoot<mirror::Class>& a, const GcRoot<mirror::Class>& b) const
709         NO_THREAD_SAFETY_ANALYSIS;
710     // Same class loader and descriptor.
711     std::size_t operator()(const std::pair<const char*, mirror::ClassLoader*>& element) const
712         NO_THREAD_SAFETY_ANALYSIS;
713     bool operator()(const GcRoot<mirror::Class>& a,
714                     const std::pair<const char*, mirror::ClassLoader*>& b) const
715         NO_THREAD_SAFETY_ANALYSIS;
716     // Same descriptor.
717     bool operator()(const GcRoot<mirror::Class>& a, const char* descriptor) const
718         NO_THREAD_SAFETY_ANALYSIS;
719     std::size_t operator()(const char* descriptor) const NO_THREAD_SAFETY_ANALYSIS;
720   };
721   class GcRootEmptyFn {
722    public:
MakeEmpty(GcRoot<mirror::Class> & item)723     void MakeEmpty(GcRoot<mirror::Class>& item) const {
724       item = GcRoot<mirror::Class>();
725     }
IsEmpty(const GcRoot<mirror::Class> & item)726     bool IsEmpty(const GcRoot<mirror::Class>& item) const {
727       return item.IsNull();
728     }
729   };
730 
731   // hash set which hashes class descriptor, and compares descriptors nad class loaders. Results
732   // should be compared for a matching Class descriptor and class loader.
733   typedef HashSet<GcRoot<mirror::Class>, GcRootEmptyFn, ClassDescriptorHashEquals,
734       ClassDescriptorHashEquals, TrackingAllocator<GcRoot<mirror::Class>, kAllocatorTagClassTable>>
735       Table;
736   // This contains strong roots. To enable concurrent root scanning of
737   // the class table, be careful to use a read barrier when accessing this.
738   Table class_table_ GUARDED_BY(Locks::classlinker_classes_lock_);
739   Table pre_zygote_class_table_ GUARDED_BY(Locks::classlinker_classes_lock_);
740   std::vector<GcRoot<mirror::Class>> new_class_roots_;
741 
742   // Do we need to search dex caches to find image classes?
743   bool dex_cache_image_class_lookup_required_;
744   // Number of times we've searched dex caches for a class. After a certain number of misses we move
745   // the classes into the class_table_ to avoid dex cache based searches.
746   Atomic<uint32_t> failed_dex_cache_class_lookups_;
747 
748   // Well known mirror::Class roots.
749   GcRoot<mirror::ObjectArray<mirror::Class>> class_roots_;
750 
751   // The interface table used by all arrays.
752   GcRoot<mirror::IfTable> array_iftable_;
753 
754   // A cache of the last FindArrayClass results. The cache serves to avoid creating array class
755   // descriptors for the sake of performing FindClass.
756   static constexpr size_t kFindArrayCacheSize = 16;
757   GcRoot<mirror::Class> find_array_class_cache_[kFindArrayCacheSize];
758   size_t find_array_class_cache_next_victim_;
759 
760   bool init_done_;
761   bool log_new_dex_caches_roots_ GUARDED_BY(dex_lock_);
762   bool log_new_class_table_roots_ GUARDED_BY(Locks::classlinker_classes_lock_);
763 
764   InternTable* intern_table_;
765 
766   // Trampolines within the image the bounce to runtime entrypoints. Done so that there is a single
767   // patch point within the image. TODO: make these proper relocations.
768   const void* quick_resolution_trampoline_;
769   const void* quick_imt_conflict_trampoline_;
770   const void* quick_generic_jni_trampoline_;
771   const void* quick_to_interpreter_bridge_trampoline_;
772 
773   // Image pointer size.
774   size_t image_pointer_size_;
775 
776   friend class ImageWriter;  // for GetClassRoots
777   friend class ImageDumper;  // for FindOpenedOatFileFromOatLocation
778   friend class JniCompilerTest;  // for GetRuntimeQuickGenericJniStub
779   ART_FRIEND_TEST(mirror::DexCacheTest, Open);  // for AllocDexCache
780 
781   DISALLOW_COPY_AND_ASSIGN(ClassLinker);
782 };
783 
784 }  // namespace art
785 
786 #endif  // ART_RUNTIME_CLASS_LINKER_H_
787