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/unix_file/fd_file.h"
35 #include "base/hash_map.h"
36 #include "base/hash_set.h"
37 #include "base/length_prefixed_array.h"
38 #include "base/macros.h"
39 #include "base/mem_map.h"
40 #include "base/os.h"
41 #include "base/safe_map.h"
42 #include "base/utils.h"
43 #include "class_table.h"
44 #include "gc/accounting/space_bitmap.h"
45 #include "image.h"
46 #include "intern_table.h"
47 #include "lock_word.h"
48 #include "mirror/dex_cache.h"
49 #include "oat_file.h"
50 #include "obj_ptr.h"
51 
52 namespace art {
53 namespace gc {
54 namespace accounting {
55 template <size_t kAlignment> class SpaceBitmap;
56 typedef SpaceBitmap<kObjectAlignment> ContinuousSpaceBitmap;
57 }  // namespace accounting
58 namespace space {
59 class ImageSpace;
60 }  // namespace space
61 }  // namespace gc
62 
63 namespace mirror {
64 class ClassLoader;
65 }  // namespace mirror
66 
67 class ClassLoaderVisitor;
68 class CompilerOptions;
69 template<class T> class Handle;
70 class ImTable;
71 class ImtConflictTable;
72 class TimingLogger;
73 
74 namespace linker {
75 
76 // Write a Space built during compilation for use during execution.
77 class ImageWriter final {
78  public:
79   ImageWriter(const CompilerOptions& compiler_options,
80               uintptr_t image_begin,
81               ImageHeader::StorageMode image_storage_mode,
82               const std::vector<std::string>& oat_filenames,
83               const HashMap<const DexFile*, size_t>& dex_file_oat_index_map,
84               jobject class_loader,
85               const HashSet<std::string>* dirty_image_objects);
86 
87   /*
88    * Modifies the heap and collects information about objects and code so that
89    * they can be written to the boot or app image later.
90    *
91    * First, unneeded classes are removed from the managed heap.  Next, we
92    * remove cached values and calculate necessary metadata for later in the
93    * process. Optionally some debugging information is collected and used to
94    * verify the state of the heap at this point.  Next, metadata from earlier
95    * is used to calculate offsets of references to strings to speed up string
96    * interning when the image is loaded.  Lastly, we allocate enough memory to
97    * fit all image data minus the bitmap and relocation sections.
98    *
99    * This function should only be called when all objects to be included in the
100    * image have been initialized and all native methods have been generated.  In
101    * addition, no other thread should be modifying the heap.
102    */
103   bool PrepareImageAddressSpace(TimingLogger* timings);
104 
IsImageAddressSpaceReady()105   bool IsImageAddressSpaceReady() const {
106     DCHECK(!image_infos_.empty());
107     for (const ImageInfo& image_info : image_infos_) {
108       if (image_info.image_roots_address_ == 0u) {
109         return false;
110       }
111     }
112     return true;
113   }
114 
115   ObjPtr<mirror::ClassLoader> GetAppClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_);
116 
117   template <typename T>
GetImageAddress(T * object)118   T* GetImageAddress(T* object) const REQUIRES_SHARED(Locks::mutator_lock_) {
119     if (object == nullptr || IsInBootImage(object)) {
120       return object;
121     } else {
122       size_t oat_index = GetOatIndex(object);
123       const ImageInfo& image_info = GetImageInfo(oat_index);
124       return reinterpret_cast<T*>(image_info.image_begin_ + GetImageOffset(object, oat_index));
125     }
126   }
127 
128   ArtMethod* GetImageMethodAddress(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
129   const void* GetIntrinsicReferenceAddress(uint32_t intrinsic_data)
130       REQUIRES_SHARED(Locks::mutator_lock_);
131 
GetOatFileOffset(size_t oat_index)132   size_t GetOatFileOffset(size_t oat_index) const {
133     return GetImageInfo(oat_index).oat_offset_;
134   }
135 
GetOatFileBegin(size_t oat_index)136   const uint8_t* GetOatFileBegin(size_t oat_index) const {
137     return GetImageInfo(oat_index).oat_file_begin_;
138   }
139 
140   // If image_fd is not File::kInvalidFd, then we use that for the image file. Otherwise we open
141   // the names in image_filenames.
142   // If oat_fd is not File::kInvalidFd, then we use that for the oat file. Otherwise we open
143   // the names in oat_filenames.
144   bool Write(int image_fd,
145              const std::vector<std::string>& image_filenames,
146              size_t component_count)
147       REQUIRES(!Locks::mutator_lock_);
148 
GetOatDataBegin(size_t oat_index)149   uintptr_t GetOatDataBegin(size_t oat_index) {
150     return reinterpret_cast<uintptr_t>(GetImageInfo(oat_index).oat_data_begin_);
151   }
152 
153   // Get the index of the oat file containing the dex file.
154   //
155   // This "oat_index" is used to retrieve information about the the memory layout
156   // of the oat file and its associated image file, needed for link-time patching
157   // of references to the image or across oat files.
158   size_t GetOatIndexForDexFile(const DexFile* dex_file) const;
159 
160   // Get the index of the oat file containing the definition of the class.
161   size_t GetOatIndexForClass(ObjPtr<mirror::Class> klass) const
162       REQUIRES_SHARED(Locks::mutator_lock_);
163 
164   // Update the oat layout for the given oat file.
165   // This will make the oat_offset for the next oat file valid.
166   void UpdateOatFileLayout(size_t oat_index,
167                            size_t oat_loaded_size,
168                            size_t oat_data_offset,
169                            size_t oat_data_size);
170   // Update information about the oat header, i.e. checksum and trampoline offsets.
171   void UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header);
172 
173  private:
174   bool AllocMemory();
175 
176   // Mark the objects defined in this space in the given live bitmap.
177   void RecordImageAllocations() REQUIRES_SHARED(Locks::mutator_lock_);
178 
179   // Classify different kinds of bins that objects end up getting packed into during image writing.
180   // Ordered from dirtiest to cleanest (until ArtMethods).
181   enum class Bin {
182     kKnownDirty,                  // Known dirty objects from --dirty-image-objects list
183     kMiscDirty,                   // Dex caches, object locks, etc...
184     kClassVerified,               // Class verified, but initializers haven't been run
185     // Unknown mix of clean/dirty:
186     kRegular,
187     kClassInitialized,            // Class initializers have been run
188     // All classes get their own bins since their fields often dirty
189     kClassInitializedFinalStatics,  // Class initializers have been run, no non-final statics
190     // Likely-clean:
191     kString,                      // [String] Almost always immutable (except for obj header).
192     // Definitely clean:
193     kMethodPointerArray,          // ART internal vtables and interface method tables, int[]/long[].
194     // Add more bins here if we add more segregation code.
195     // Non mirror fields must be below.
196     // ArtFields should be always clean.
197     kArtField,
198     // If the class is initialized, then the ArtMethods are probably clean.
199     kArtMethodClean,
200     // ArtMethods may be dirty if the class has native methods or a declaring class that isn't
201     // initialized.
202     kArtMethodDirty,
203     // IMT (clean)
204     kImTable,
205     // Conflict tables (clean).
206     kIMTConflictTable,
207     // Runtime methods (always clean, do not have a length prefix array).
208     kRuntimeMethod,
209     // Metadata bin for data that is temporary during image lifetime.
210     kMetadata,
211     kLast = kMetadata,
212     // Number of bins which are for mirror objects.
213     kMirrorCount = kArtField,
214   };
215   friend std::ostream& operator<<(std::ostream& stream, Bin bin);
216 
217   enum class NativeObjectRelocationType {
218     kArtFieldArray,
219     kArtMethodClean,
220     kArtMethodArrayClean,
221     kArtMethodDirty,
222     kArtMethodArrayDirty,
223     kGcRootPointer,
224     kRuntimeMethod,
225     kIMTable,
226     kIMTConflictTable,
227   };
228   friend std::ostream& operator<<(std::ostream& stream, NativeObjectRelocationType type);
229 
230   enum class StubType {
231     kJNIDlsymLookupTrampoline,
232     kJNIDlsymLookupCriticalTrampoline,
233     kQuickGenericJNITrampoline,
234     kQuickIMTConflictTrampoline,
235     kQuickResolutionTrampoline,
236     kQuickToInterpreterBridge,
237     kNterpTrampoline,
238     kLast = kNterpTrampoline,
239   };
240   friend std::ostream& operator<<(std::ostream& stream, StubType stub_type);
241 
242   static constexpr size_t kBinBits =
243       MinimumBitsToStore<uint32_t>(static_cast<size_t>(Bin::kMirrorCount) - 1);
244   // uint32 = typeof(lockword_)
245   // Subtract read barrier bits since we want these to remain 0, or else it may result in DCHECK
246   // failures due to invalid read barrier bits during object field reads.
247   static const size_t kBinShift = BitSizeOf<uint32_t>() - kBinBits - LockWord::kGCStateSize;
248   // 111000.....0
249   static const size_t kBinMask = ((static_cast<size_t>(1) << kBinBits) - 1) << kBinShift;
250 
251   // Number of bins, including non-mirror bins.
252   static constexpr size_t kNumberOfBins = static_cast<size_t>(Bin::kLast) + 1u;
253 
254   // Number of stub types.
255   static constexpr size_t kNumberOfStubTypes = static_cast<size_t>(StubType::kLast) + 1u;
256 
257   // We use the lock word to store the bin # and bin index of the object in the image.
258   //
259   // The struct size must be exactly sizeof(LockWord), currently 32-bits, since this will end up
260   // stored in the lock word bit-for-bit when object forwarding addresses are being calculated.
261   struct BinSlot {
262     explicit BinSlot(uint32_t lockword);
263     BinSlot(Bin bin, uint32_t index);
264 
265     // The bin an object belongs to, i.e. regular, class/verified, class/initialized, etc.
266     Bin GetBin() const;
267     // The offset in bytes from the beginning of the bin. Aligned to object size.
268     uint32_t GetOffset() const;
269     // Pack into a single uint32_t, for storing into a lock word.
Uint32ValueBinSlot270     uint32_t Uint32Value() const { return lockword_; }
271     // Comparison operator for map support
272     bool operator<(const BinSlot& other) const  { return lockword_ < other.lockword_; }
273 
274    private:
275     // Must be the same size as LockWord, any larger and we would truncate the data.
276     uint32_t lockword_;
277   };
278 
279   struct ImageInfo {
280     ImageInfo();
281     ImageInfo(ImageInfo&&) = default;
282 
283     /*
284      * Creates ImageSection objects that describe most of the sections of a
285      * boot or AppImage. The following sections are not included:
286      *   - ImageHeader::kSectionImageBitmap
287      *
288      * In addition, the ImageHeader is not covered here.
289      *
290      * This function will return the total size of the covered sections as well
291      * as a vector containing the individual ImageSection objects.
292      */
293     std::pair<size_t, std::vector<ImageSection>> CreateImageSections() const;
294 
GetStubOffsetImageInfo295     size_t GetStubOffset(StubType stub_type) const {
296       DCHECK_LT(static_cast<size_t>(stub_type), kNumberOfStubTypes);
297       return stub_offsets_[static_cast<size_t>(stub_type)];
298     }
299 
SetStubOffsetImageInfo300     void SetStubOffset(StubType stub_type, size_t offset) {
301       DCHECK_LT(static_cast<size_t>(stub_type), kNumberOfStubTypes);
302       stub_offsets_[static_cast<size_t>(stub_type)] = offset;
303     }
304 
GetBinSlotOffsetImageInfo305     size_t GetBinSlotOffset(Bin bin) const {
306       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
307       return bin_slot_offsets_[static_cast<size_t>(bin)];
308     }
309 
IncrementBinSlotSizeImageInfo310     void IncrementBinSlotSize(Bin bin, size_t size_to_add) {
311       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
312       bin_slot_sizes_[static_cast<size_t>(bin)] += size_to_add;
313     }
314 
GetBinSlotSizeImageInfo315     size_t GetBinSlotSize(Bin bin) const {
316       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
317       return bin_slot_sizes_[static_cast<size_t>(bin)];
318     }
319 
IncrementBinSlotCountImageInfo320     void IncrementBinSlotCount(Bin bin, size_t count_to_add) {
321       DCHECK_LT(static_cast<size_t>(bin), kNumberOfBins);
322       bin_slot_count_[static_cast<size_t>(bin)] += count_to_add;
323     }
324 
325     // Calculate the sum total of the bin slot sizes in [0, up_to). Defaults to all bins.
326     size_t GetBinSizeSum(Bin up_to) const;
327 
328     MemMap image_;  // Memory mapped for generating the image.
329 
330     // Target begin of this image. Notes: It is not valid to write here, this is the address
331     // of the target image, not necessarily where image_ is mapped. The address is only valid
332     // after layouting (otherwise null).
333     uint8_t* image_begin_ = nullptr;
334 
335     // Offset to the free space in image_, initially size of image header.
336     size_t image_end_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);
337     uint32_t image_roots_address_ = 0;  // The image roots address in the image.
338     size_t image_offset_ = 0;  // Offset of this image from the start of the first image.
339 
340     // Image size is the *address space* covered by this image. As the live bitmap is aligned
341     // to the page size, the live bitmap will cover more address space than necessary. But live
342     // bitmaps may not overlap, so an image has a "shadow," which is accounted for in the size.
343     // The next image may only start at image_begin_ + image_size_ (which is guaranteed to be
344     // page-aligned).
345     size_t image_size_ = 0;
346 
347     // Oat data.
348     // Offset of the oat file for this image from start of oat files. This is
349     // valid when the previous oat file has been written.
350     size_t oat_offset_ = 0;
351     // Layout of the loaded ELF file containing the oat file, valid after UpdateOatFileLayout().
352     const uint8_t* oat_file_begin_ = nullptr;
353     size_t oat_loaded_size_ = 0;
354     const uint8_t* oat_data_begin_ = nullptr;
355     size_t oat_size_ = 0;  // Size of the corresponding oat data.
356     // The oat header checksum, valid after UpdateOatFileHeader().
357     uint32_t oat_checksum_ = 0u;
358 
359     // Image bitmap which lets us know where the objects inside of the image reside.
360     gc::accounting::ContinuousSpaceBitmap image_bitmap_;
361 
362     // The start offsets of the dex cache arrays.
363     SafeMap<const DexFile*, size_t> dex_cache_array_starts_;
364 
365     // Offset from oat_data_begin_ to the stubs.
366     uint32_t stub_offsets_[kNumberOfStubTypes] = {};
367 
368     // Bin slot tracking for dirty object packing.
369     size_t bin_slot_sizes_[kNumberOfBins] = {};  // Number of bytes in a bin.
370     size_t bin_slot_offsets_[kNumberOfBins] = {};  // Number of bytes in previous bins.
371     size_t bin_slot_count_[kNumberOfBins] = {};  // Number of objects in a bin.
372 
373     // Cached size of the intern table for when we allocate memory.
374     size_t intern_table_bytes_ = 0;
375 
376     // Number of image class table bytes.
377     size_t class_table_bytes_ = 0;
378 
379     // Number of object fixup bytes.
380     size_t object_fixup_bytes_ = 0;
381 
382     // Number of pointer fixup bytes.
383     size_t pointer_fixup_bytes_ = 0;
384 
385     // Number of offsets to string references that will be written to the
386     // StringFieldOffsets section.
387     size_t num_string_references_ = 0;
388 
389     // Offsets into the image that indicate where string references are recorded.
390     std::vector<AppImageReferenceOffsetInfo> string_reference_offsets_;
391 
392     // Intern table associated with this image for serialization.
393     size_t intern_table_size_ = 0;
394     std::unique_ptr<GcRoot<mirror::String>[]> intern_table_buffer_;
395     std::optional<InternTable::UnorderedSet> intern_table_;
396 
397     // Class table associated with this image for serialization.
398     size_t class_table_size_ = 0;
399     std::unique_ptr<ClassTable::ClassSet::value_type[]> class_table_buffer_;
400     std::optional<ClassTable::ClassSet> class_table_;
401 
402     // Padding offsets to ensure region alignment (if required).
403     // Objects need to be added from the recorded offset until the end of the region.
404     std::vector<size_t> padding_offsets_;
405   };
406 
407   // We use the lock word to store the offset of the object in the image.
408   size_t GetImageOffset(mirror::Object* object, size_t oat_index) const
409       REQUIRES_SHARED(Locks::mutator_lock_);
410 
411   Bin AssignImageBinSlot(mirror::Object* object, size_t oat_index)
412       REQUIRES_SHARED(Locks::mutator_lock_);
413   void AssignImageBinSlot(mirror::Object* object, size_t oat_index, Bin bin)
414       REQUIRES_SHARED(Locks::mutator_lock_);
415   void RecordNativeRelocations(ObjPtr<mirror::Class> klass, size_t oat_index)
416       REQUIRES_SHARED(Locks::mutator_lock_);
417   void SetImageBinSlot(mirror::Object* object, BinSlot bin_slot)
418       REQUIRES_SHARED(Locks::mutator_lock_);
419   bool IsImageBinSlotAssigned(mirror::Object* object) const
420       REQUIRES_SHARED(Locks::mutator_lock_);
421   BinSlot GetImageBinSlot(mirror::Object* object, size_t oat_index) const
422       REQUIRES_SHARED(Locks::mutator_lock_);
423   void UpdateImageBinSlotOffset(mirror::Object* object, size_t oat_index, size_t new_offset)
424       REQUIRES_SHARED(Locks::mutator_lock_);
425 
426   // Returns the address in the boot image if we are compiling the app image.
427   const uint8_t* GetOatAddress(StubType type) const;
428 
GetOatAddressForOffset(uint32_t offset,const ImageInfo & image_info)429   const uint8_t* GetOatAddressForOffset(uint32_t offset, const ImageInfo& image_info) const {
430     // With Quick, code is within the OatFile, as there are all in one
431     // .o ELF object. But interpret it as signed.
432     DCHECK_LE(static_cast<int32_t>(offset), static_cast<int32_t>(image_info.oat_size_));
433     DCHECK(image_info.oat_data_begin_ != nullptr);
434     return offset == 0u ? nullptr : image_info.oat_data_begin_ + static_cast<int32_t>(offset);
435   }
436 
437   // Returns true if the class was in the original requested image classes list.
438   bool KeepClass(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
439 
440   // Debug aid that list of requested image classes.
441   void DumpImageClasses();
442 
443   // Visit all class loaders.
444   void VisitClassLoaders(ClassLoaderVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_);
445 
446   // Remove unwanted classes from various roots.
447   void PruneNonImageClasses() REQUIRES_SHARED(Locks::mutator_lock_);
448 
449   // Remove everything from the DexCache.
450   void ClearDexCache(ObjPtr<mirror::DexCache> dex_cache)
451       REQUIRES_SHARED(Locks::mutator_lock_);
452 
453   // Find dex caches for pruning or preloading.
454   std::vector<ObjPtr<mirror::DexCache>> FindDexCaches(Thread* self)
455       REQUIRES_SHARED(Locks::mutator_lock_)
456       REQUIRES(!Locks::classlinker_classes_lock_);
457 
458   // Verify unwanted classes removed.
459   void CheckNonImageClassesRemoved() REQUIRES_SHARED(Locks::mutator_lock_);
460 
461   // Lays out where the image objects will be at runtime.
462   void CalculateNewObjectOffsets()
463       REQUIRES_SHARED(Locks::mutator_lock_);
464   void CreateHeader(size_t oat_index, size_t component_count)
465       REQUIRES_SHARED(Locks::mutator_lock_);
466   ObjPtr<mirror::ObjectArray<mirror::Object>> CollectDexCaches(Thread* self, size_t oat_index) const
467       REQUIRES_SHARED(Locks::mutator_lock_);
468   ObjPtr<mirror::ObjectArray<mirror::Object>> CreateImageRoots(
469       size_t oat_index,
470       Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects) const
471       REQUIRES_SHARED(Locks::mutator_lock_);
472   void CalculateObjectBinSlots(mirror::Object* obj)
473       REQUIRES_SHARED(Locks::mutator_lock_);
474 
475   // Creates the contiguous image in memory and adjusts pointers.
476   void CopyAndFixupNativeData(size_t oat_index) REQUIRES_SHARED(Locks::mutator_lock_);
477   void CopyAndFixupObjects() REQUIRES_SHARED(Locks::mutator_lock_);
478   void CopyAndFixupObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_);
479   template <bool kCheckIfDone>
480   mirror::Object* CopyObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_);
481   void CopyAndFixupMethodPointerArray(mirror::PointerArray* arr)
482       REQUIRES_SHARED(Locks::mutator_lock_);
483   void CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy, size_t oat_index)
484       REQUIRES_SHARED(Locks::mutator_lock_);
485   void CopyAndFixupImTable(ImTable* orig, ImTable* copy)
486       REQUIRES_SHARED(Locks::mutator_lock_);
487   void CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy)
488       REQUIRES_SHARED(Locks::mutator_lock_);
489 
490   /*
491    * Copies metadata from the heap into a buffer that will be compressed and
492    * written to the image.
493    *
494    * This function copies the string offset metadata from a local vector to an
495    * offset inside the image_ field of an ImageInfo struct.  The offset into the
496    * memory pointed to by the image_ field is obtained from the ImageSection
497    * object for the String Offsets section.
498    *
499    * All data for the image, besides the object bitmap and the relocation data,
500    * will also be copied into the memory region pointed to by image_.
501    */
502   void CopyMetadata();
503 
504   void FixupClass(mirror::Class* orig, mirror::Class* copy)
505       REQUIRES_SHARED(Locks::mutator_lock_);
506   void FixupObject(mirror::Object* orig, mirror::Object* copy)
507       REQUIRES_SHARED(Locks::mutator_lock_);
508 
509   // Get quick code for non-resolution/imt_conflict/abstract method.
510   const uint8_t* GetQuickCode(ArtMethod* method, const ImageInfo& image_info)
511       REQUIRES_SHARED(Locks::mutator_lock_);
512 
513   // Return true if a method is likely to be dirtied at runtime.
514   bool WillMethodBeDirty(ArtMethod* m) const REQUIRES_SHARED(Locks::mutator_lock_);
515 
516   // Assign the offset for an ArtMethod.
517   void AssignMethodOffset(ArtMethod* method,
518                           NativeObjectRelocationType type,
519                           size_t oat_index)
520       REQUIRES_SHARED(Locks::mutator_lock_);
521 
522   // Return true if imt was newly inserted.
523   bool TryAssignImTableOffset(ImTable* imt, size_t oat_index) REQUIRES_SHARED(Locks::mutator_lock_);
524 
525   // Assign the offset for an IMT conflict table. Does nothing if the table already has a native
526   // relocation.
527   void TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index)
528       REQUIRES_SHARED(Locks::mutator_lock_);
529 
530   // Return true if klass is loaded by the boot class loader but not in the boot image.
531   bool IsBootClassLoaderNonImageClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_);
532 
533   // Return true if `klass` depends on a class defined by the boot class path
534   // we're compiling against but not present in the boot image spaces. We want
535   // to prune these classes since we cannot guarantee that they will not be
536   // already loaded at run time when loading this image. This means that we
537   // also cannot have any classes which refer to these non image classes.
538   bool PruneImageClass(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
539 
540   // early_exit is true if we had a cyclic dependency anywhere down the chain.
541   bool PruneImageClassInternal(ObjPtr<mirror::Class> klass,
542                                bool* early_exit,
543                                HashSet<mirror::Object*>* visited)
544       REQUIRES_SHARED(Locks::mutator_lock_);
545 
IsMultiImage()546   bool IsMultiImage() const {
547     return image_infos_.size() > 1;
548   }
549 
550   static Bin BinTypeForNativeRelocationType(NativeObjectRelocationType type);
551 
552   struct NativeObjectRelocation {
553     size_t oat_index;
554     uintptr_t offset;
555     NativeObjectRelocationType type;
556 
IsArtMethodRelocationNativeObjectRelocation557     bool IsArtMethodRelocation() const {
558       return type == NativeObjectRelocationType::kArtMethodClean ||
559           type == NativeObjectRelocationType::kArtMethodDirty ||
560           type == NativeObjectRelocationType::kRuntimeMethod;
561     }
562   };
563 
564   NativeObjectRelocation GetNativeRelocation(void* obj) REQUIRES_SHARED(Locks::mutator_lock_);
565 
566   // Location of where the object will be when the image is loaded at runtime.
567   template <typename T>
568   T* NativeLocationInImage(T* obj) REQUIRES_SHARED(Locks::mutator_lock_);
569 
570   // Return true if `dex_cache` belongs to the image we're writing.
571   // For a boot image, this is true for all dex caches.
572   // For an app image, boot class path dex caches are excluded.
573   bool IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const
574       REQUIRES_SHARED(Locks::mutator_lock_);
575 
576   // Return true if `obj` is inside of a boot image space that we're compiling against.
577   // (Always false when compiling the boot image.)
IsInBootImage(const void * obj)578   ALWAYS_INLINE bool IsInBootImage(const void* obj) const {
579     return reinterpret_cast<uintptr_t>(obj) - boot_image_begin_ < boot_image_size_;
580   }
581 
582   // Get the index of the oat file associated with the object.
583   size_t GetOatIndex(mirror::Object* object) const REQUIRES_SHARED(Locks::mutator_lock_);
584 
585   // The oat index for shared data in multi-image and all data in single-image compilation.
GetDefaultOatIndex()586   static constexpr size_t GetDefaultOatIndex() {
587     return 0u;
588   }
589 
GetImageInfo(size_t oat_index)590   ImageInfo& GetImageInfo(size_t oat_index) {
591     return image_infos_[oat_index];
592   }
593 
GetImageInfo(size_t oat_index)594   const ImageInfo& GetImageInfo(size_t oat_index) const {
595     return image_infos_[oat_index];
596   }
597 
598   // Return true if there already exists a native allocation for an object.
599   bool NativeRelocationAssigned(void* ptr) const;
600 
601   // Copy a reference and record image relocation.
602   template <typename DestType>
603   void CopyAndFixupReference(DestType* dest, ObjPtr<mirror::Object> src)
604       REQUIRES_SHARED(Locks::mutator_lock_);
605 
606   // Copy a native pointer and record image relocation.
607   void CopyAndFixupPointer(void** target, void* value, PointerSize pointer_size)
608       REQUIRES_SHARED(Locks::mutator_lock_);
609   void CopyAndFixupPointer(void** target, void* value)
610       REQUIRES_SHARED(Locks::mutator_lock_);
611   void CopyAndFixupPointer(
612       void* object, MemberOffset offset, void* value, PointerSize pointer_size)
613       REQUIRES_SHARED(Locks::mutator_lock_);
614   void CopyAndFixupPointer(void* object, MemberOffset offset, void* value)
615       REQUIRES_SHARED(Locks::mutator_lock_);
616 
617   /*
618    * Tests an object to see if it will be contained in an AppImage.
619    *
620    * An object reference is considered to be a AppImage String reference iff:
621    *   - It isn't null
622    *   - The referred-object isn't in the boot image
623    *   - The referred-object is a Java String
624    */
625   ALWAYS_INLINE
626   bool IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const
627       REQUIRES_SHARED(Locks::mutator_lock_);
628 
629   const CompilerOptions& compiler_options_;
630 
631   // Cached boot image begin and size. This includes heap, native objects and oat files.
632   const uint32_t boot_image_begin_;
633   const uint32_t boot_image_size_;
634 
635   // Beginning target image address for the first image.
636   uint8_t* global_image_begin_;
637 
638   // Offset from image_begin_ to where the first object is in image_.
639   size_t image_objects_offset_begin_;
640 
641   // Saved hash codes. We use these to restore lockwords which were temporarily used to have
642   // forwarding addresses as well as copying over hash codes.
643   HashMap<mirror::Object*, uint32_t> saved_hashcode_map_;
644 
645   // Oat index map for objects.
646   HashMap<mirror::Object*, uint32_t> oat_index_map_;
647 
648   // Size of pointers on the target architecture.
649   PointerSize target_ptr_size_;
650 
651   // Image data indexed by the oat file index.
652   dchecked_vector<ImageInfo> image_infos_;
653 
654   // ArtField, ArtMethod relocating map. These are allocated as array of structs but we want to
655   // have one entry per art field for convenience. ArtFields are placed right after the end of the
656   // image objects (aka sum of bin_slot_sizes_). ArtMethods are placed right after the ArtFields.
657   HashMap<void*, NativeObjectRelocation> native_object_relocations_;
658 
659   // Runtime ArtMethods which aren't reachable from any Class but need to be copied into the image.
660   ArtMethod* image_methods_[ImageHeader::kImageMethodsCount];
661 
662   // Counters for measurements, used for logging only.
663   uint64_t dirty_methods_;
664   uint64_t clean_methods_;
665 
666   // Prune class memoization table to speed up ContainsBootClassLoaderNonImageClass.
667   HashMap<mirror::Class*, bool> prune_class_memo_;
668 
669   // The application class loader. Null for boot image.
670   jobject app_class_loader_;
671 
672   // Boot image live objects, null for app image.
673   mirror::ObjectArray<mirror::Object>* boot_image_live_objects_;
674 
675   // Which mode the image is stored as, see image.h
676   const ImageHeader::StorageMode image_storage_mode_;
677 
678   // The file names of oat files.
679   const std::vector<std::string>& oat_filenames_;
680 
681   // Map of dex files to the indexes of oat files that they were compiled into.
682   const HashMap<const DexFile*, size_t>& dex_file_oat_index_map_;
683 
684   // Set of objects known to be dirty in the image. Can be nullptr if there are none.
685   const HashSet<std::string>* dirty_image_objects_;
686 
687   // Objects are guaranteed to not cross the region size boundary.
688   size_t region_size_ = 0u;
689 
690   // Region alignment bytes wasted.
691   size_t region_alignment_wasted_ = 0u;
692 
693   class FixupClassVisitor;
694   class FixupRootVisitor;
695   class FixupVisitor;
696   class ImageFileGuard;
697   class LayoutHelper;
698   class NativeLocationVisitor;
699   class PruneClassesVisitor;
700   class PruneClassLoaderClassesVisitor;
701   class PruneObjectReferenceVisitor;
702 
703   // A visitor used by the VerifyNativeGCRootInvariants() function.
704   class NativeGCRootInvariantVisitor;
705 
706   DISALLOW_COPY_AND_ASSIGN(ImageWriter);
707 };
708 
709 std::ostream& operator<<(std::ostream& stream, ImageWriter::Bin bin);
710 std::ostream& operator<<(std::ostream& stream, ImageWriter::NativeObjectRelocationType type);
711 std::ostream& operator<<(std::ostream& stream, ImageWriter::StubType stub_type);
712 
713 }  // namespace linker
714 }  // namespace art
715 
716 #endif  // ART_DEX2OAT_LINKER_IMAGE_WRITER_H_
717