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_DEX2OAT_LINKER_IMAGE_WRITER_H_
18 #define ART_DEX2OAT_LINKER_IMAGE_WRITER_H_
19 
20 #include <stdint.h>
21 #include "base/memory_tool.h"
22 
23 #include <cstddef>
24 #include <memory>
25 #include <ostream>
26 #include <set>
27 #include <stack>
28 #include <string>
29 
30 #include "art_method.h"
31 #include "base/bit_utils.h"
32 #include "base/dchecked_vector.h"
33 #include "base/enums.h"
34 #include "base/length_prefixed_array.h"
35 #include "base/macros.h"
36 #include "base/os.h"
37 #include "base/safe_map.h"
38 #include "base/utils.h"
39 #include "class_table.h"
40 #include "driver/compiler_driver.h"
41 #include "image.h"
42 #include "intern_table.h"
43 #include "lock_word.h"
44 #include "mem_map.h"
45 #include "mirror/dex_cache.h"
46 #include "oat_file.h"
47 #include "obj_ptr.h"
48 
49 namespace art {
50 namespace gc {
51 namespace accounting {
52 template <size_t kAlignment> class SpaceBitmap;
53 typedef SpaceBitmap<kObjectAlignment> ContinuousSpaceBitmap;
54 }  // namespace accounting
55 namespace space {
56 class ImageSpace;
57 }  // namespace space
58 }  // namespace gc
59 
60 namespace mirror {
61 class ClassLoader;
62 }  // namespace mirror
63 
64 class ClassLoaderVisitor;
65 class ImTable;
66 class ImtConflictTable;
67 
68 static constexpr int kInvalidFd = -1;
69 
70 namespace linker {
71 
72 // Write a Space built during compilation for use during execution.
73 class ImageWriter FINAL {
74  public:
75   ImageWriter(const CompilerDriver& compiler_driver,
76               uintptr_t image_begin,
77               bool compile_pic,
78               bool compile_app_image,
79               ImageHeader::StorageMode image_storage_mode,
80               const std::vector<const char*>& oat_filenames,
81               const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map,
82               const std::unordered_set<std::string>* dirty_image_objects);
83 
84   bool PrepareImageAddressSpace();
85 
IsImageAddressSpaceReady()86   bool IsImageAddressSpaceReady() const {
87     DCHECK(!image_infos_.empty());
88     for (const ImageInfo& image_info : image_infos_) {
89       if (image_info.image_roots_address_ == 0u) {
90         return false;
91       }
92     }
93     return true;
94   }
95 
GetClassLoader()96   ObjPtr<mirror::ClassLoader> GetClassLoader() {
97     CHECK_EQ(class_loaders_.size(), compile_app_image_ ? 1u : 0u);
98     return compile_app_image_ ? *class_loaders_.begin() : nullptr;
99   }
100 
101   template <typename T>
GetImageAddress(T * object)102   T* GetImageAddress(T* object) const REQUIRES_SHARED(Locks::mutator_lock_) {
103     if (object == nullptr || IsInBootImage(object)) {
104       return object;
105     } else {
106       size_t oat_index = GetOatIndex(object);
107       const ImageInfo& image_info = GetImageInfo(oat_index);
108       return reinterpret_cast<T*>(image_info.image_begin_ + GetImageOffset(object));
109     }
110   }
111 
112   ArtMethod* GetImageMethodAddress(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
113 
GetOatFileOffset(size_t oat_index)114   size_t GetOatFileOffset(size_t oat_index) const {
115     return GetImageInfo(oat_index).oat_offset_;
116   }
117 
GetOatFileBegin(size_t oat_index)118   const uint8_t* GetOatFileBegin(size_t oat_index) const {
119     return GetImageInfo(oat_index).oat_file_begin_;
120   }
121 
122   // If image_fd is not kInvalidFd, then we use that for the image file. Otherwise we open
123   // the names in image_filenames.
124   // If oat_fd is not kInvalidFd, then we use that for the oat file. Otherwise we open
125   // the names in oat_filenames.
126   bool Write(int image_fd,
127              const std::vector<const char*>& image_filenames,
128              const std::vector<const char*>& oat_filenames)
129       REQUIRES(!Locks::mutator_lock_);
130 
GetOatDataBegin(size_t oat_index)131   uintptr_t GetOatDataBegin(size_t oat_index) {
132     return reinterpret_cast<uintptr_t>(GetImageInfo(oat_index).oat_data_begin_);
133   }
134 
135   // Get the index of the oat file containing the dex file.
136   //
137   // This "oat_index" is used to retrieve information about the the memory layout
138   // of the oat file and its associated image file, needed for link-time patching
139   // of references to the image or across oat files.
140   size_t GetOatIndexForDexFile(const DexFile* dex_file) const;
141 
142   // Get the index of the oat file containing the dex file served by the dex cache.
143   size_t GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const
144       REQUIRES_SHARED(Locks::mutator_lock_);
145 
146   // Update the oat layout for the given oat file.
147   // This will make the oat_offset for the next oat file valid.
148   void UpdateOatFileLayout(size_t oat_index,
149                            size_t oat_loaded_size,
150                            size_t oat_data_offset,
151                            size_t oat_data_size);
152   // Update information about the oat header, i.e. checksum and trampoline offsets.
153   void UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header);
154 
155  private:
156   using WorkStack = std::stack<std::pair<mirror::Object*, size_t>>;
157 
158   bool AllocMemory();
159 
160   // Mark the objects defined in this space in the given live bitmap.
161   void RecordImageAllocations() REQUIRES_SHARED(Locks::mutator_lock_);
162 
163   // Classify different kinds of bins that objects end up getting packed into during image writing.
164   // Ordered from dirtiest to cleanest (until ArtMethods).
165   enum class Bin {
166     kKnownDirty,                  // Known dirty objects from --dirty-image-objects list
167     kMiscDirty,                   // Dex caches, object locks, etc...
168     kClassVerified,               // Class verified, but initializers haven't been run
169     // Unknown mix of clean/dirty:
170     kRegular,
171     kClassInitialized,            // Class initializers have been run
172     // All classes get their own bins since their fields often dirty
173     kClassInitializedFinalStatics,  // Class initializers have been run, no non-final statics
174     // Likely-clean:
175     kString,                      // [String] Almost always immutable (except for obj header).
176     // Add more bins here if we add more segregation code.
177     // Non mirror fields must be below.
178     // ArtFields should be always clean.
179     kArtField,
180     // If the class is initialized, then the ArtMethods are probably clean.
181     kArtMethodClean,
182     // ArtMethods may be dirty if the class has native methods or a declaring class that isn't
183     // initialized.
184     kArtMethodDirty,
185     // IMT (clean)
186     kImTable,
187     // Conflict tables (clean).
188     kIMTConflictTable,
189     // Runtime methods (always clean, do not have a length prefix array).
190     kRuntimeMethod,
191     // Dex cache arrays have a special slot for PC-relative addressing. Since they are
192     // huge, and as such their dirtiness is not important for the clean/dirty separation,
193     // we arbitrarily keep them at the end of the native data.
194     kDexCacheArray,               // Arrays belonging to dex cache.
195     kLast = kDexCacheArray,
196     // Number of bins which are for mirror objects.
197     kMirrorCount = kArtField,
198   };
199   friend std::ostream& operator<<(std::ostream& stream, const Bin& bin);
200 
201   enum class NativeObjectRelocationType {
202     kArtField,
203     kArtFieldArray,
204     kArtMethodClean,
205     kArtMethodArrayClean,
206     kArtMethodDirty,
207     kArtMethodArrayDirty,
208     kRuntimeMethod,
209     kIMTable,
210     kIMTConflictTable,
211     kDexCacheArray,
212   };
213   friend std::ostream& operator<<(std::ostream& stream, const NativeObjectRelocationType& type);
214 
215   enum class StubType {
216     kInterpreterToInterpreterBridge,
217     kInterpreterToCompiledCodeBridge,
218     kJNIDlsymLookup,
219     kQuickGenericJNITrampoline,
220     kQuickIMTConflictTrampoline,
221     kQuickResolutionTrampoline,
222     kQuickToInterpreterBridge,
223     kLast = kQuickToInterpreterBridge,
224   };
225   friend std::ostream& operator<<(std::ostream& stream, const StubType& stub_type);
226 
227   static constexpr size_t kBinBits =
228       MinimumBitsToStore<uint32_t>(static_cast<size_t>(Bin::kMirrorCount) - 1);
229   // uint32 = typeof(lockword_)
230   // Subtract read barrier bits since we want these to remain 0, or else it may result in DCHECK
231   // failures due to invalid read barrier bits during object field reads.
232   static const size_t kBinShift = BitSizeOf<uint32_t>() - kBinBits - LockWord::kGCStateSize;
233   // 111000.....0
234   static const size_t kBinMask = ((static_cast<size_t>(1) << kBinBits) - 1) << kBinShift;
235 
236   // Number of bins, including non-mirror bins.
237   static constexpr size_t kNumberOfBins = static_cast<size_t>(Bin::kLast) + 1u;
238 
239   // Number of stub types.
240   static constexpr size_t kNumberOfStubTypes = static_cast<size_t>(StubType::kLast) + 1u;
241 
242   // We use the lock word to store the bin # and bin index of the object in the image.
243   //
244   // The struct size must be exactly sizeof(LockWord), currently 32-bits, since this will end up
245   // stored in the lock word bit-for-bit when object forwarding addresses are being calculated.
246   struct BinSlot {
247     explicit BinSlot(uint32_t lockword);
248     BinSlot(Bin bin, uint32_t index);
249 
250     // The bin an object belongs to, i.e. regular, class/verified, class/initialized, etc.
251     Bin GetBin() const;
252     // The offset in bytes from the beginning of the bin. Aligned to object size.
253     uint32_t GetIndex() const;
254     // Pack into a single uint32_t, for storing into a lock word.
Uint32ValueBinSlot255     uint32_t Uint32Value() const { return lockword_; }
256     // Comparison operator for map support
257     bool operator<(const BinSlot& other) const  { return lockword_ < other.lockword_; }
258 
259    private:
260     // Must be the same size as LockWord, any larger and we would truncate the data.
261     const uint32_t lockword_;
262   };
263 
264   struct ImageInfo {
265     ImageInfo();
266     ImageInfo(ImageInfo&&) = default;
267 
268     // Create the image sections into the out sections variable, returns the size of the image
269     // excluding the bitmap.
270     size_t CreateImageSections(ImageSection* out_sections, bool app_image) const;
271 
GetStubOffsetImageInfo272     size_t GetStubOffset(StubType stub_type) const {
273       DCHECK_LT(static_cast<size_t>(stub_type), kNumberOfStubTypes);
274       return stub_offsets_[static_cast<size_t>(stub_type)];
275     }
276 
SetStubOffsetImageInfo277     void SetStubOffset(StubType stub_type, size_t offset) {
278       DCHECK_LT(static_cast<size_t>(stub_type), kNumberOfStubTypes);
279       stub_offsets_[static_cast<size_t>(stub_type)] = offset;
280     }
281 
GetBinSlotOffsetImageInfo282     size_t GetBinSlotOffset(Bin bin) const {
283       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
284       return bin_slot_offsets_[static_cast<size_t>(bin)];
285     }
286 
IncrementBinSlotSizeImageInfo287     void IncrementBinSlotSize(Bin bin, size_t size_to_add) {
288       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
289       bin_slot_sizes_[static_cast<size_t>(bin)] += size_to_add;
290     }
291 
GetBinSlotSizeImageInfo292     size_t GetBinSlotSize(Bin bin) const {
293       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
294       return bin_slot_sizes_[static_cast<size_t>(bin)];
295     }
296 
IncrementBinSlotCountImageInfo297     void IncrementBinSlotCount(Bin bin, size_t count_to_add) {
298       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
299       bin_slot_count_[static_cast<size_t>(bin)] += count_to_add;
300     }
301 
302     // Calculate the sum total of the bin slot sizes in [0, up_to). Defaults to all bins.
303     size_t GetBinSizeSum(Bin up_to) const;
304 
305     std::unique_ptr<MemMap> image_;  // Memory mapped for generating the image.
306 
307     // Target begin of this image. Notes: It is not valid to write here, this is the address
308     // of the target image, not necessarily where image_ is mapped. The address is only valid
309     // after layouting (otherwise null).
310     uint8_t* image_begin_ = nullptr;
311 
312     // Offset to the free space in image_, initially size of image header.
313     size_t image_end_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);
314     uint32_t image_roots_address_ = 0;  // The image roots address in the image.
315     size_t image_offset_ = 0;  // Offset of this image from the start of the first image.
316 
317     // Image size is the *address space* covered by this image. As the live bitmap is aligned
318     // to the page size, the live bitmap will cover more address space than necessary. But live
319     // bitmaps may not overlap, so an image has a "shadow," which is accounted for in the size.
320     // The next image may only start at image_begin_ + image_size_ (which is guaranteed to be
321     // page-aligned).
322     size_t image_size_ = 0;
323 
324     // Oat data.
325     // Offset of the oat file for this image from start of oat files. This is
326     // valid when the previous oat file has been written.
327     size_t oat_offset_ = 0;
328     // Layout of the loaded ELF file containing the oat file, valid after UpdateOatFileLayout().
329     const uint8_t* oat_file_begin_ = nullptr;
330     size_t oat_loaded_size_ = 0;
331     const uint8_t* oat_data_begin_ = nullptr;
332     size_t oat_size_ = 0;  // Size of the corresponding oat data.
333     // The oat header checksum, valid after UpdateOatFileHeader().
334     uint32_t oat_checksum_ = 0u;
335 
336     // Image bitmap which lets us know where the objects inside of the image reside.
337     std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> image_bitmap_;
338 
339     // The start offsets of the dex cache arrays.
340     SafeMap<const DexFile*, size_t> dex_cache_array_starts_;
341 
342     // Offset from oat_data_begin_ to the stubs.
343     uint32_t stub_offsets_[kNumberOfStubTypes] = {};
344 
345     // Bin slot tracking for dirty object packing.
346     size_t bin_slot_sizes_[kNumberOfBins] = {};  // Number of bytes in a bin.
347     size_t bin_slot_offsets_[kNumberOfBins] = {};  // Number of bytes in previous bins.
348     size_t bin_slot_count_[kNumberOfBins] = {};  // Number of objects in a bin.
349 
350     // Cached size of the intern table for when we allocate memory.
351     size_t intern_table_bytes_ = 0;
352 
353     // Number of image class table bytes.
354     size_t class_table_bytes_ = 0;
355 
356     // Number of object fixup bytes.
357     size_t object_fixup_bytes_ = 0;
358 
359     // Number of pointer fixup bytes.
360     size_t pointer_fixup_bytes_ = 0;
361 
362     // Intern table associated with this image for serialization.
363     std::unique_ptr<InternTable> intern_table_;
364 
365     // Class table associated with this image for serialization.
366     std::unique_ptr<ClassTable> class_table_;
367   };
368 
369   // We use the lock word to store the offset of the object in the image.
370   void AssignImageOffset(mirror::Object* object, BinSlot bin_slot)
371       REQUIRES_SHARED(Locks::mutator_lock_);
372   void SetImageOffset(mirror::Object* object, size_t offset)
373       REQUIRES_SHARED(Locks::mutator_lock_);
374   bool IsImageOffsetAssigned(mirror::Object* object) const
375       REQUIRES_SHARED(Locks::mutator_lock_);
376   size_t GetImageOffset(mirror::Object* object) const REQUIRES_SHARED(Locks::mutator_lock_);
377   void UpdateImageOffset(mirror::Object* obj, uintptr_t offset)
378       REQUIRES_SHARED(Locks::mutator_lock_);
379 
380   void PrepareDexCacheArraySlots() REQUIRES_SHARED(Locks::mutator_lock_);
381   void AssignImageBinSlot(mirror::Object* object, size_t oat_index)
382       REQUIRES_SHARED(Locks::mutator_lock_);
383   mirror::Object* TryAssignBinSlot(WorkStack& work_stack, mirror::Object* obj, size_t oat_index)
384       REQUIRES_SHARED(Locks::mutator_lock_);
385   void SetImageBinSlot(mirror::Object* object, BinSlot bin_slot)
386       REQUIRES_SHARED(Locks::mutator_lock_);
387   bool IsImageBinSlotAssigned(mirror::Object* object) const
388       REQUIRES_SHARED(Locks::mutator_lock_);
389   BinSlot GetImageBinSlot(mirror::Object* object) const REQUIRES_SHARED(Locks::mutator_lock_);
390 
391   void AddDexCacheArrayRelocation(void* array, size_t offset, ObjPtr<mirror::DexCache> dex_cache)
392       REQUIRES_SHARED(Locks::mutator_lock_);
393   void AddMethodPointerArray(mirror::PointerArray* arr) REQUIRES_SHARED(Locks::mutator_lock_);
394 
GetImageAddressCallback(void * writer,mirror::Object * obj)395   static void* GetImageAddressCallback(void* writer, mirror::Object* obj)
396       REQUIRES_SHARED(Locks::mutator_lock_) {
397     return reinterpret_cast<ImageWriter*>(writer)->GetImageAddress(obj);
398   }
399 
GetLocalAddress(mirror::Object * object)400   mirror::Object* GetLocalAddress(mirror::Object* object) const
401       REQUIRES_SHARED(Locks::mutator_lock_) {
402     size_t offset = GetImageOffset(object);
403     size_t oat_index = GetOatIndex(object);
404     const ImageInfo& image_info = GetImageInfo(oat_index);
405     uint8_t* dst = image_info.image_->Begin() + offset;
406     return reinterpret_cast<mirror::Object*>(dst);
407   }
408 
409   // Returns the address in the boot image if we are compiling the app image.
410   const uint8_t* GetOatAddress(StubType type) const;
411 
GetOatAddressForOffset(uint32_t offset,const ImageInfo & image_info)412   const uint8_t* GetOatAddressForOffset(uint32_t offset, const ImageInfo& image_info) const {
413     // With Quick, code is within the OatFile, as there are all in one
414     // .o ELF object. But interpret it as signed.
415     DCHECK_LE(static_cast<int32_t>(offset), static_cast<int32_t>(image_info.oat_size_));
416     DCHECK(image_info.oat_data_begin_ != nullptr);
417     return offset == 0u ? nullptr : image_info.oat_data_begin_ + static_cast<int32_t>(offset);
418   }
419 
420   // Returns true if the class was in the original requested image classes list.
421   bool KeepClass(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
422 
423   // Debug aid that list of requested image classes.
424   void DumpImageClasses();
425 
426   // Preinitializes some otherwise lazy fields (such as Class name) to avoid runtime image dirtying.
427   void ComputeLazyFieldsForImageClasses()
428       REQUIRES_SHARED(Locks::mutator_lock_);
429 
430   // Visit all class loaders.
431   void VisitClassLoaders(ClassLoaderVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_);
432 
433   // Remove unwanted classes from various roots.
434   void PruneNonImageClasses() REQUIRES_SHARED(Locks::mutator_lock_);
435 
436   // Remove unwanted classes from the DexCache roots and preload deterministic DexCache contents.
437   void PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
438                                ObjPtr<mirror::ClassLoader> class_loader)
439       REQUIRES_SHARED(Locks::mutator_lock_)
440       REQUIRES(!Locks::classlinker_classes_lock_);
441 
442   // Verify unwanted classes removed.
443   void CheckNonImageClassesRemoved() REQUIRES_SHARED(Locks::mutator_lock_);
444 
445   // Lays out where the image objects will be at runtime.
446   void CalculateNewObjectOffsets()
447       REQUIRES_SHARED(Locks::mutator_lock_);
448   void ProcessWorkStack(WorkStack* work_stack)
449       REQUIRES_SHARED(Locks::mutator_lock_);
450   void CreateHeader(size_t oat_index)
451       REQUIRES_SHARED(Locks::mutator_lock_);
452   mirror::ObjectArray<mirror::Object>* CreateImageRoots(size_t oat_index) const
453       REQUIRES_SHARED(Locks::mutator_lock_);
454   void CalculateObjectBinSlots(mirror::Object* obj)
455       REQUIRES_SHARED(Locks::mutator_lock_);
456   void UnbinObjectsIntoOffset(mirror::Object* obj)
457       REQUIRES_SHARED(Locks::mutator_lock_);
458 
459   // Creates the contiguous image in memory and adjusts pointers.
460   void CopyAndFixupNativeData(size_t oat_index) REQUIRES_SHARED(Locks::mutator_lock_);
461   void CopyAndFixupObjects() REQUIRES_SHARED(Locks::mutator_lock_);
462   void CopyAndFixupObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_);
463   void CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy, const ImageInfo& image_info)
464       REQUIRES_SHARED(Locks::mutator_lock_);
465   void CopyAndFixupImTable(ImTable* orig, ImTable* copy) REQUIRES_SHARED(Locks::mutator_lock_);
466   void CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy)
467       REQUIRES_SHARED(Locks::mutator_lock_);
468   void FixupClass(mirror::Class* orig, mirror::Class* copy)
469       REQUIRES_SHARED(Locks::mutator_lock_);
470   void FixupObject(mirror::Object* orig, mirror::Object* copy)
471       REQUIRES_SHARED(Locks::mutator_lock_);
472   void FixupDexCache(mirror::DexCache* orig_dex_cache, mirror::DexCache* copy_dex_cache)
473       REQUIRES_SHARED(Locks::mutator_lock_);
474   void FixupPointerArray(mirror::Object* dst,
475                          mirror::PointerArray* arr,
476                          mirror::Class* klass,
477                          Bin array_type)
478       REQUIRES_SHARED(Locks::mutator_lock_);
479 
480   // Get quick code for non-resolution/imt_conflict/abstract method.
481   const uint8_t* GetQuickCode(ArtMethod* method,
482                               const ImageInfo& image_info,
483                               bool* quick_is_interpreted)
484       REQUIRES_SHARED(Locks::mutator_lock_);
485 
486   // Return true if a method is likely to be dirtied at runtime.
487   bool WillMethodBeDirty(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_);
488 
489   // Assign the offset for an ArtMethod.
490   void AssignMethodOffset(ArtMethod* method,
491                           NativeObjectRelocationType type,
492                           size_t oat_index)
493       REQUIRES_SHARED(Locks::mutator_lock_);
494 
495   // Return true if imt was newly inserted.
496   bool TryAssignImTableOffset(ImTable* imt, size_t oat_index) REQUIRES_SHARED(Locks::mutator_lock_);
497 
498   // Assign the offset for an IMT conflict table. Does nothing if the table already has a native
499   // relocation.
500   void TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index)
501       REQUIRES_SHARED(Locks::mutator_lock_);
502 
503   // Return true if klass is loaded by the boot class loader but not in the boot image.
504   bool IsBootClassLoaderNonImageClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_);
505 
506   // Return true if klass depends on a boot class loader non image class. We want to prune these
507   // classes since we do not want any boot class loader classes in the image. This means that
508   // we also cannot have any classes which refer to these boot class loader non image classes.
509   // PruneAppImageClass also prunes if klass depends on a non-image class according to the compiler
510   // driver.
511   bool PruneAppImageClass(ObjPtr<mirror::Class> klass)
512       REQUIRES_SHARED(Locks::mutator_lock_);
513 
514   // early_exit is true if we had a cyclic dependency anywhere down the chain.
515   bool PruneAppImageClassInternal(ObjPtr<mirror::Class> klass,
516                                   bool* early_exit,
517                                   std::unordered_set<mirror::Object*>* visited)
518       REQUIRES_SHARED(Locks::mutator_lock_);
519 
IsMultiImage()520   bool IsMultiImage() const {
521     return image_infos_.size() > 1;
522   }
523 
524   static Bin BinTypeForNativeRelocationType(NativeObjectRelocationType type);
525 
526   uintptr_t NativeOffsetInImage(void* obj) REQUIRES_SHARED(Locks::mutator_lock_);
527 
528   // Location of where the object will be when the image is loaded at runtime.
529   template <typename T>
530   T* NativeLocationInImage(T* obj) REQUIRES_SHARED(Locks::mutator_lock_);
531 
532   // Location of where the temporary copy of the object currently is.
533   template <typename T>
534   T* NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) REQUIRES_SHARED(Locks::mutator_lock_);
535 
536   // Return true of obj is inside of the boot image space. This may only return true if we are
537   // compiling an app image.
538   bool IsInBootImage(const void* obj) const;
539 
540   // Return true if ptr is within the boot oat file.
541   bool IsInBootOatFile(const void* ptr) const;
542 
543   // Get the index of the oat file associated with the object.
544   size_t GetOatIndex(mirror::Object* object) const REQUIRES_SHARED(Locks::mutator_lock_);
545 
546   // The oat index for shared data in multi-image and all data in single-image compilation.
GetDefaultOatIndex()547   size_t GetDefaultOatIndex() const {
548     return 0u;
549   }
550 
GetImageInfo(size_t oat_index)551   ImageInfo& GetImageInfo(size_t oat_index) {
552     return image_infos_[oat_index];
553   }
554 
GetImageInfo(size_t oat_index)555   const ImageInfo& GetImageInfo(size_t oat_index) const {
556     return image_infos_[oat_index];
557   }
558 
559   // Find an already strong interned string in the other images or in the boot image. Used to
560   // remove duplicates in the multi image and app image case.
561   mirror::String* FindInternedString(mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_);
562 
563   // Return true if there already exists a native allocation for an object.
564   bool NativeRelocationAssigned(void* ptr) const;
565 
566   void CopyReference(mirror::HeapReference<mirror::Object>* dest, ObjPtr<mirror::Object> src)
567       REQUIRES_SHARED(Locks::mutator_lock_);
568 
569   void CopyReference(mirror::CompressedReference<mirror::Object>* dest, ObjPtr<mirror::Object> src)
570       REQUIRES_SHARED(Locks::mutator_lock_);
571 
572   void CopyAndFixupPointer(void** target, void* value);
573 
574   const CompilerDriver& compiler_driver_;
575 
576   // Beginning target image address for the first image.
577   uint8_t* global_image_begin_;
578 
579   // Offset from image_begin_ to where the first object is in image_.
580   size_t image_objects_offset_begin_;
581 
582   // Pointer arrays that need to be updated. Since these are only some int and long arrays, we need
583   // to keep track. These include vtable arrays, iftable arrays, and dex caches.
584   std::unordered_map<mirror::PointerArray*, Bin> pointer_arrays_;
585 
586   // Saved hash codes. We use these to restore lockwords which were temporarily used to have
587   // forwarding addresses as well as copying over hash codes.
588   std::unordered_map<mirror::Object*, uint32_t> saved_hashcode_map_;
589 
590   // Oat index map for objects.
591   std::unordered_map<mirror::Object*, uint32_t> oat_index_map_;
592 
593   // Boolean flags.
594   const bool compile_pic_;
595   const bool compile_app_image_;
596 
597   // Size of pointers on the target architecture.
598   PointerSize target_ptr_size_;
599 
600   // Image data indexed by the oat file index.
601   dchecked_vector<ImageInfo> image_infos_;
602 
603   // ArtField, ArtMethod relocating map. These are allocated as array of structs but we want to
604   // have one entry per art field for convenience. ArtFields are placed right after the end of the
605   // image objects (aka sum of bin_slot_sizes_). ArtMethods are placed right after the ArtFields.
606   struct NativeObjectRelocation {
607     size_t oat_index;
608     uintptr_t offset;
609     NativeObjectRelocationType type;
610 
IsArtMethodRelocationNativeObjectRelocation611     bool IsArtMethodRelocation() const {
612       return type == NativeObjectRelocationType::kArtMethodClean ||
613           type == NativeObjectRelocationType::kArtMethodDirty ||
614           type == NativeObjectRelocationType::kRuntimeMethod;
615     }
616   };
617   std::unordered_map<void*, NativeObjectRelocation> native_object_relocations_;
618 
619   // Runtime ArtMethods which aren't reachable from any Class but need to be copied into the image.
620   ArtMethod* image_methods_[ImageHeader::kImageMethodsCount];
621 
622   // Counters for measurements, used for logging only.
623   uint64_t dirty_methods_;
624   uint64_t clean_methods_;
625 
626   // Prune class memoization table to speed up ContainsBootClassLoaderNonImageClass.
627   std::unordered_map<mirror::Class*, bool> prune_class_memo_;
628 
629   // Class loaders with a class table to write out. There should only be one class loader because
630   // dex2oat loads the dex files to be compiled into a single class loader. For the boot image,
631   // null is a valid entry.
632   std::unordered_set<mirror::ClassLoader*> class_loaders_;
633 
634   // Which mode the image is stored as, see image.h
635   const ImageHeader::StorageMode image_storage_mode_;
636 
637   // The file names of oat files.
638   const std::vector<const char*>& oat_filenames_;
639 
640   // Map of dex files to the indexes of oat files that they were compiled into.
641   const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map_;
642 
643   // Set of objects known to be dirty in the image. Can be nullptr if there are none.
644   const std::unordered_set<std::string>* dirty_image_objects_;
645 
646   class ComputeLazyFieldsForClassesVisitor;
647   class FixupClassVisitor;
648   class FixupRootVisitor;
649   class FixupVisitor;
650   class GetRootsVisitor;
651   class ImageAddressVisitorForDexCacheArray;
652   class NativeLocationVisitor;
653   class PruneClassesVisitor;
654   class PruneClassLoaderClassesVisitor;
655   class RegisterBootClassPathClassesVisitor;
656   class VisitReferencesVisitor;
657   class PruneObjectReferenceVisitor;
658 
659   DISALLOW_COPY_AND_ASSIGN(ImageWriter);
660 };
661 
662 }  // namespace linker
663 }  // namespace art
664 
665 #endif  // ART_DEX2OAT_LINKER_IMAGE_WRITER_H_
666