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