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