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