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 #include "image_writer.h"
18 
19 #include <lz4.h>
20 #include <lz4hc.h>
21 #include <sys/stat.h>
22 #include <zlib.h>
23 
24 #include <memory>
25 #include <numeric>
26 #include <vector>
27 
28 #include "art_field-inl.h"
29 #include "art_method-inl.h"
30 #include "base/callee_save_type.h"
31 #include "base/enums.h"
32 #include "base/globals.h"
33 #include "base/logging.h"  // For VLOG.
34 #include "base/stl_util.h"
35 #include "base/unix_file/fd_file.h"
36 #include "class_linker-inl.h"
37 #include "class_root-inl.h"
38 #include "compiled_method.h"
39 #include "dex/dex_file-inl.h"
40 #include "dex/dex_file_types.h"
41 #include "driver/compiler_options.h"
42 #include "elf/elf_utils.h"
43 #include "elf_file.h"
44 #include "entrypoints/entrypoint_utils-inl.h"
45 #include "gc/accounting/card_table-inl.h"
46 #include "gc/accounting/heap_bitmap.h"
47 #include "gc/accounting/space_bitmap-inl.h"
48 #include "gc/collector/concurrent_copying.h"
49 #include "gc/heap-visit-objects-inl.h"
50 #include "gc/heap.h"
51 #include "gc/space/large_object_space.h"
52 #include "gc/space/region_space.h"
53 #include "gc/space/space-inl.h"
54 #include "gc/verification.h"
55 #include "handle_scope-inl.h"
56 #include "image-inl.h"
57 #include "imt_conflict_table.h"
58 #include "intern_table-inl.h"
59 #include "jni/jni_internal.h"
60 #include "linear_alloc.h"
61 #include "lock_word.h"
62 #include "mirror/array-inl.h"
63 #include "mirror/class-inl.h"
64 #include "mirror/class_ext-inl.h"
65 #include "mirror/class_loader.h"
66 #include "mirror/dex_cache-inl.h"
67 #include "mirror/dex_cache.h"
68 #include "mirror/executable.h"
69 #include "mirror/method.h"
70 #include "mirror/object-inl.h"
71 #include "mirror/object-refvisitor-inl.h"
72 #include "mirror/object_array-alloc-inl.h"
73 #include "mirror/object_array-inl.h"
74 #include "mirror/string-inl.h"
75 #include "nterp_helpers.h"
76 #include "oat.h"
77 #include "oat_file.h"
78 #include "oat_file_manager.h"
79 #include "optimizing/intrinsic_objects.h"
80 #include "runtime.h"
81 #include "scoped_thread_state_change-inl.h"
82 #include "subtype_check.h"
83 #include "well_known_classes.h"
84 
85 using ::art::mirror::Class;
86 using ::art::mirror::DexCache;
87 using ::art::mirror::Object;
88 using ::art::mirror::ObjectArray;
89 using ::art::mirror::String;
90 
91 namespace art {
92 namespace linker {
93 
94 // The actual value of `kImageClassTableMinLoadFactor` is irrelevant because image class tables
95 // are never resized, but we still need to pass a reasonable value to the constructor.
96 constexpr double kImageClassTableMinLoadFactor = 0.5;
97 // We use `kImageClassTableMaxLoadFactor` to determine the buffer size for image class tables
98 // to make them full. We never insert additional elements to them, so we do not want to waste
99 // extra memory. And unlike runtime class tables, we do not want this to depend on runtime
100 // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
101 constexpr double kImageClassTableMaxLoadFactor = 0.7;
102 
103 // The actual value of `kImageInternTableMinLoadFactor` is irrelevant because image intern tables
104 // are never resized, but we still need to pass a reasonable value to the constructor.
105 constexpr double kImageInternTableMinLoadFactor = 0.5;
106 // We use `kImageInternTableMaxLoadFactor` to determine the buffer size for image intern tables
107 // to make them full. We never insert additional elements to them, so we do not want to waste
108 // extra memory. And unlike runtime intern tables, we do not want this to depend on runtime
109 // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
110 constexpr double kImageInternTableMaxLoadFactor = 0.7;
111 
MaybeCompressData(ArrayRef<const uint8_t> source,ImageHeader::StorageMode image_storage_mode,std::vector<uint8_t> * storage)112 static ArrayRef<const uint8_t> MaybeCompressData(ArrayRef<const uint8_t> source,
113                                                  ImageHeader::StorageMode image_storage_mode,
114                                                  /*out*/ std::vector<uint8_t>* storage) {
115   const uint64_t compress_start_time = NanoTime();
116 
117   switch (image_storage_mode) {
118     case ImageHeader::kStorageModeLZ4: {
119       storage->resize(LZ4_compressBound(source.size()));
120       size_t data_size = LZ4_compress_default(
121           reinterpret_cast<char*>(const_cast<uint8_t*>(source.data())),
122           reinterpret_cast<char*>(storage->data()),
123           source.size(),
124           storage->size());
125       storage->resize(data_size);
126       break;
127     }
128     case ImageHeader::kStorageModeLZ4HC: {
129       // Bound is same as non HC.
130       storage->resize(LZ4_compressBound(source.size()));
131       size_t data_size = LZ4_compress_HC(
132           reinterpret_cast<const char*>(const_cast<uint8_t*>(source.data())),
133           reinterpret_cast<char*>(storage->data()),
134           source.size(),
135           storage->size(),
136           LZ4HC_CLEVEL_MAX);
137       storage->resize(data_size);
138       break;
139     }
140     case ImageHeader::kStorageModeUncompressed: {
141       return source;
142     }
143     default: {
144       LOG(FATAL) << "Unsupported";
145       UNREACHABLE();
146     }
147   }
148 
149   DCHECK(image_storage_mode == ImageHeader::kStorageModeLZ4 ||
150          image_storage_mode == ImageHeader::kStorageModeLZ4HC);
151   VLOG(compiler) << "Compressed from " << source.size() << " to " << storage->size() << " in "
152                  << PrettyDuration(NanoTime() - compress_start_time);
153   if (kIsDebugBuild) {
154     std::vector<uint8_t> decompressed(source.size());
155     const size_t decompressed_size = LZ4_decompress_safe(
156         reinterpret_cast<char*>(storage->data()),
157         reinterpret_cast<char*>(decompressed.data()),
158         storage->size(),
159         decompressed.size());
160     CHECK_EQ(decompressed_size, decompressed.size());
161     CHECK_EQ(memcmp(source.data(), decompressed.data(), source.size()), 0) << image_storage_mode;
162   }
163   return ArrayRef<const uint8_t>(*storage);
164 }
165 
166 // Separate objects into multiple bins to optimize dirty memory use.
167 static constexpr bool kBinObjects = true;
168 
AllocateBootImageLiveObjects(Thread * self,Runtime * runtime)169 ObjPtr<mirror::ObjectArray<mirror::Object>> AllocateBootImageLiveObjects(
170     Thread* self, Runtime* runtime) REQUIRES_SHARED(Locks::mutator_lock_) {
171   ClassLinker* class_linker = runtime->GetClassLinker();
172   // The objects used for the Integer.valueOf() intrinsic must remain live even if references
173   // to them are removed using reflection. Image roots are not accessible through reflection,
174   // so the array we construct here shall keep them alive.
175   StackHandleScope<1> hs(self);
176   Handle<mirror::ObjectArray<mirror::Object>> integer_cache =
177       hs.NewHandle(IntrinsicObjects::LookupIntegerCache(self, class_linker));
178   size_t live_objects_size =
179       enum_cast<size_t>(ImageHeader::kIntrinsicObjectsStart) +
180       ((integer_cache != nullptr) ? (/* cache */ 1u + integer_cache->GetLength()) : 0u);
181   ObjPtr<mirror::ObjectArray<mirror::Object>> live_objects =
182       mirror::ObjectArray<mirror::Object>::Alloc(
183           self, GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker), live_objects_size);
184   int32_t index = 0u;
185   auto set_entry = [&](ImageHeader::BootImageLiveObjects entry,
186                        ObjPtr<mirror::Object> value) REQUIRES_SHARED(Locks::mutator_lock_) {
187     DCHECK_EQ(index, enum_cast<int32_t>(entry));
188     live_objects->Set</*kTransacrionActive=*/ false>(index, value);
189     ++index;
190   };
191   set_entry(ImageHeader::kOomeWhenThrowingException,
192             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
193   set_entry(ImageHeader::kOomeWhenThrowingOome,
194             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
195   set_entry(ImageHeader::kOomeWhenHandlingStackOverflow,
196             runtime->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
197   set_entry(ImageHeader::kNoClassDefFoundError, runtime->GetPreAllocatedNoClassDefFoundError());
198   set_entry(ImageHeader::kClearedJniWeakSentinel, runtime->GetSentinel().Read());
199 
200   DCHECK_EQ(index, enum_cast<int32_t>(ImageHeader::kIntrinsicObjectsStart));
201   if (integer_cache != nullptr) {
202     live_objects->Set(index++, integer_cache.Get());
203     for (int32_t i = 0, length = integer_cache->GetLength(); i != length; ++i) {
204       live_objects->Set(index++, integer_cache->Get(i));
205     }
206   }
207   CHECK_EQ(index, live_objects->GetLength());
208 
209   if (kIsDebugBuild && integer_cache != nullptr) {
210     CHECK_EQ(integer_cache.Get(), IntrinsicObjects::GetIntegerValueOfCache(live_objects));
211     for (int32_t i = 0, len = integer_cache->GetLength(); i != len; ++i) {
212       CHECK_EQ(integer_cache->GetWithoutChecks(i),
213                IntrinsicObjects::GetIntegerValueOfObject(live_objects, i));
214     }
215   }
216   return live_objects;
217 }
218 
GetAppClassLoader() const219 ObjPtr<mirror::ClassLoader> ImageWriter::GetAppClassLoader() const
220     REQUIRES_SHARED(Locks::mutator_lock_) {
221   return compiler_options_.IsAppImage()
222       ? ObjPtr<mirror::ClassLoader>::DownCast(Thread::Current()->DecodeJObject(app_class_loader_))
223       : nullptr;
224 }
225 
IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const226 bool ImageWriter::IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
227   // For boot image, we keep all dex caches.
228   if (compiler_options_.IsBootImage()) {
229     return true;
230   }
231   // Dex caches already in the boot image do not belong to the image being written.
232   if (IsInBootImage(dex_cache.Ptr())) {
233     return false;
234   }
235   // Dex caches for the boot class path components that are not part of the boot image
236   // cannot be garbage collected in PrepareImageAddressSpace() but we do not want to
237   // include them in the app image.
238   if (!ContainsElement(compiler_options_.GetDexFilesForOatFile(), dex_cache->GetDexFile())) {
239     return false;
240   }
241   return true;
242 }
243 
ClearDexFileCookies()244 static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
245   auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
246     DCHECK(obj != nullptr);
247     Class* klass = obj->GetClass();
248     if (klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile)) {
249       ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
250       // Null out the cookie to enable determinism. b/34090128
251       field->SetObject</*kTransactionActive*/false>(obj, nullptr);
252     }
253   };
254   Runtime::Current()->GetHeap()->VisitObjects(visitor);
255 }
256 
PrepareImageAddressSpace(TimingLogger * timings)257 bool ImageWriter::PrepareImageAddressSpace(TimingLogger* timings) {
258   target_ptr_size_ = InstructionSetPointerSize(compiler_options_.GetInstructionSet());
259 
260   Thread* const self = Thread::Current();
261 
262   gc::Heap* const heap = Runtime::Current()->GetHeap();
263   {
264     ScopedObjectAccess soa(self);
265     {
266       TimingLogger::ScopedTiming t("PruneNonImageClasses", timings);
267       PruneNonImageClasses();  // Remove junk
268     }
269 
270     if (compiler_options_.IsAppImage()) {
271       TimingLogger::ScopedTiming t("ClearDexFileCookies", timings);
272       // Clear dex file cookies for app images to enable app image determinism. This is required
273       // since the cookie field contains long pointers to DexFiles which are not deterministic.
274       // b/34090128
275       ClearDexFileCookies();
276     }
277   }
278 
279   {
280     TimingLogger::ScopedTiming t("CollectGarbage", timings);
281     heap->CollectGarbage(/* clear_soft_references */ false);  // Remove garbage.
282   }
283 
284   if (kIsDebugBuild) {
285     ScopedObjectAccess soa(self);
286     CheckNonImageClassesRemoved();
287   }
288 
289   {
290     // All remaining weak interns are referenced. Promote them to strong interns. Whether a
291     // string was strongly or weakly interned, we shall make it strongly interned in the image.
292     TimingLogger::ScopedTiming t("PromoteInterns", timings);
293     ScopedObjectAccess soa(self);
294     Runtime::Current()->GetInternTable()->PromoteWeakToStrong();
295   }
296 
297   {
298     TimingLogger::ScopedTiming t("CalculateNewObjectOffsets", timings);
299     ScopedObjectAccess soa(self);
300     CalculateNewObjectOffsets();
301   }
302 
303   // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
304   // bin size sums being calculated.
305   TimingLogger::ScopedTiming t("AllocMemory", timings);
306   return AllocMemory();
307 }
308 
CopyMetadata()309 void ImageWriter::CopyMetadata() {
310   DCHECK(compiler_options_.IsAppImage());
311   CHECK_EQ(image_infos_.size(), 1u);
312 
313   const ImageInfo& image_info = image_infos_.back();
314   std::vector<ImageSection> image_sections = image_info.CreateImageSections().second;
315 
316   auto* sfo_section_base = reinterpret_cast<AppImageReferenceOffsetInfo*>(
317       image_info.image_.Begin() +
318       image_sections[ImageHeader::kSectionStringReferenceOffsets].Offset());
319 
320   std::copy(image_info.string_reference_offsets_.begin(),
321             image_info.string_reference_offsets_.end(),
322             sfo_section_base);
323 }
324 
IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const325 bool ImageWriter::IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const {
326   return referred_obj != nullptr &&
327          !IsInBootImage(referred_obj.Ptr()) &&
328          referred_obj->IsString() &&
329          referred_obj == Runtime::Current()->GetInternTable()->LookupStrong(
330              Thread::Current(), referred_obj->AsString());
331 }
332 
333 // Helper class that erases the image file if it isn't properly flushed and closed.
334 class ImageWriter::ImageFileGuard {
335  public:
336   ImageFileGuard() noexcept = default;
337   ImageFileGuard(ImageFileGuard&& other) noexcept = default;
338   ImageFileGuard& operator=(ImageFileGuard&& other) noexcept = default;
339 
~ImageFileGuard()340   ~ImageFileGuard() {
341     if (image_file_ != nullptr) {
342       // Failure, erase the image file.
343       image_file_->Erase();
344     }
345   }
346 
reset(File * image_file)347   void reset(File* image_file) {
348     image_file_.reset(image_file);
349   }
350 
operator ==(std::nullptr_t)351   bool operator==(std::nullptr_t) {
352     return image_file_ == nullptr;
353   }
354 
operator !=(std::nullptr_t)355   bool operator!=(std::nullptr_t) {
356     return image_file_ != nullptr;
357   }
358 
operator ->() const359   File* operator->() const {
360     return image_file_.get();
361   }
362 
WriteHeaderAndClose(const std::string & image_filename,const ImageHeader * image_header)363   bool WriteHeaderAndClose(const std::string& image_filename, const ImageHeader* image_header) {
364     // The header is uncompressed since it contains whether the image is compressed or not.
365     if (!image_file_->PwriteFully(image_header, sizeof(ImageHeader), 0)) {
366       PLOG(ERROR) << "Failed to write image file header " << image_filename;
367       return false;
368     }
369 
370     // FlushCloseOrErase() takes care of erasing, so the destructor does not need
371     // to do that whether the FlushCloseOrErase() succeeds or fails.
372     std::unique_ptr<File> image_file = std::move(image_file_);
373     if (image_file->FlushCloseOrErase() != 0) {
374       PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
375       return false;
376     }
377 
378     return true;
379   }
380 
381  private:
382   std::unique_ptr<File> image_file_;
383 };
384 
Write(int image_fd,const std::vector<std::string> & image_filenames,size_t component_count)385 bool ImageWriter::Write(int image_fd,
386                         const std::vector<std::string>& image_filenames,
387                         size_t component_count) {
388   // If image_fd or oat_fd are not File::kInvalidFd then we may have empty strings in
389   // image_filenames or oat_filenames.
390   CHECK(!image_filenames.empty());
391   if (image_fd != File::kInvalidFd) {
392     CHECK_EQ(image_filenames.size(), 1u);
393   }
394   DCHECK(!oat_filenames_.empty());
395   CHECK_EQ(image_filenames.size(), oat_filenames_.size());
396 
397   Thread* const self = Thread::Current();
398   {
399     ScopedObjectAccess soa(self);
400     for (size_t i = 0; i < oat_filenames_.size(); ++i) {
401       CreateHeader(i, component_count);
402       CopyAndFixupNativeData(i);
403     }
404   }
405 
406   {
407     // TODO: heap validation can't handle these fix up passes.
408     ScopedObjectAccess soa(self);
409     Runtime::Current()->GetHeap()->DisableObjectValidation();
410     CopyAndFixupObjects();
411   }
412 
413   if (compiler_options_.IsAppImage()) {
414     CopyMetadata();
415   }
416 
417   // Primary image header shall be written last for two reasons. First, this ensures
418   // that we shall not end up with a valid primary image and invalid secondary image.
419   // Second, its checksum shall include the checksums of the secondary images (XORed).
420   // This way only the primary image checksum needs to be checked to determine whether
421   // any of the images or oat files are out of date. (Oat file checksums are included
422   // in the image checksum calculation.)
423   ImageHeader* primary_header = reinterpret_cast<ImageHeader*>(image_infos_[0].image_.Begin());
424   ImageFileGuard primary_image_file;
425   for (size_t i = 0; i < image_filenames.size(); ++i) {
426     const std::string& image_filename = image_filenames[i];
427     ImageInfo& image_info = GetImageInfo(i);
428     ImageFileGuard image_file;
429     if (image_fd != File::kInvalidFd) {
430       // Ignore image_filename, it is supplied only for better diagnostic.
431       image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
432       // Empty the file in case it already exists.
433       if (image_file != nullptr) {
434         TEMP_FAILURE_RETRY(image_file->SetLength(0));
435         TEMP_FAILURE_RETRY(image_file->Flush());
436       }
437     } else {
438       image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
439     }
440 
441     if (image_file == nullptr) {
442       LOG(ERROR) << "Failed to open image file " << image_filename;
443       return false;
444     }
445 
446     // Make file world readable if we have created it, i.e. when not passed as file descriptor.
447     if (image_fd == -1 && !compiler_options_.IsAppImage() && fchmod(image_file->Fd(), 0644) != 0) {
448       PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
449       return false;
450     }
451 
452     // Image data size excludes the bitmap and the header.
453     ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
454 
455     // Block sources (from the image).
456     const bool is_compressed = image_storage_mode_ != ImageHeader::kStorageModeUncompressed;
457     std::vector<std::pair<uint32_t, uint32_t>> block_sources;
458     std::vector<ImageHeader::Block> blocks;
459 
460     // Add a set of solid blocks such that no block is larger than the maximum size. A solid block
461     // is a block that must be decompressed all at once.
462     auto add_blocks = [&](uint32_t offset, uint32_t size) {
463       while (size != 0u) {
464         const uint32_t cur_size = std::min(size, compiler_options_.MaxImageBlockSize());
465         block_sources.emplace_back(offset, cur_size);
466         offset += cur_size;
467         size -= cur_size;
468       }
469     };
470 
471     add_blocks(sizeof(ImageHeader), image_header->GetImageSize() - sizeof(ImageHeader));
472 
473     // Checksum of compressed image data and header.
474     uint32_t image_checksum = adler32(0L, Z_NULL, 0);
475     image_checksum = adler32(image_checksum,
476                              reinterpret_cast<const uint8_t*>(image_header),
477                              sizeof(ImageHeader));
478     // Copy and compress blocks.
479     size_t out_offset = sizeof(ImageHeader);
480     for (const std::pair<uint32_t, uint32_t> block : block_sources) {
481       ArrayRef<const uint8_t> raw_image_data(image_info.image_.Begin() + block.first,
482                                              block.second);
483       std::vector<uint8_t> compressed_data;
484       ArrayRef<const uint8_t> image_data =
485           MaybeCompressData(raw_image_data, image_storage_mode_, &compressed_data);
486 
487       if (!is_compressed) {
488         // For uncompressed, preserve alignment since the image will be directly mapped.
489         out_offset = block.first;
490       }
491 
492       // Fill in the compressed location of the block.
493       blocks.emplace_back(ImageHeader::Block(
494           image_storage_mode_,
495           /*data_offset=*/ out_offset,
496           /*data_size=*/ image_data.size(),
497           /*image_offset=*/ block.first,
498           /*image_size=*/ block.second));
499 
500       // Write out the image + fields + methods.
501       if (!image_file->PwriteFully(image_data.data(), image_data.size(), out_offset)) {
502         PLOG(ERROR) << "Failed to write image file data " << image_filename;
503         image_file->Erase();
504         return false;
505       }
506       out_offset += image_data.size();
507       image_checksum = adler32(image_checksum, image_data.data(), image_data.size());
508     }
509 
510     // Write the block metadata directly after the image sections.
511     // Note: This is not part of the mapped image and is not preserved after decompressing, it's
512     // only used for image loading. For this reason, only write it out for compressed images.
513     if (is_compressed) {
514       // Align up since the compressed data is not necessarily aligned.
515       out_offset = RoundUp(out_offset, alignof(ImageHeader::Block));
516       CHECK(!blocks.empty());
517       const size_t blocks_bytes = blocks.size() * sizeof(blocks[0]);
518       if (!image_file->PwriteFully(&blocks[0], blocks_bytes, out_offset)) {
519         PLOG(ERROR) << "Failed to write image blocks " << image_filename;
520         image_file->Erase();
521         return false;
522       }
523       image_header->blocks_offset_ = out_offset;
524       image_header->blocks_count_ = blocks.size();
525       out_offset += blocks_bytes;
526     }
527 
528     // Data size includes everything except the bitmap.
529     image_header->data_size_ = out_offset - sizeof(ImageHeader);
530 
531     // Update and write the bitmap section. Note that the bitmap section is relative to the
532     // possibly compressed image.
533     ImageSection& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
534     // Align up since data size may be unaligned if the image is compressed.
535     out_offset = RoundUp(out_offset, kPageSize);
536     bitmap_section = ImageSection(out_offset, bitmap_section.Size());
537 
538     if (!image_file->PwriteFully(image_info.image_bitmap_.Begin(),
539                                  bitmap_section.Size(),
540                                  bitmap_section.Offset())) {
541       PLOG(ERROR) << "Failed to write image file bitmap " << image_filename;
542       return false;
543     }
544 
545     int err = image_file->Flush();
546     if (err < 0) {
547       PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
548       return false;
549     }
550 
551     // Calculate the image checksum of the remaining data.
552     image_checksum = adler32(image_checksum,
553                              reinterpret_cast<const uint8_t*>(image_info.image_bitmap_.Begin()),
554                              bitmap_section.Size());
555     image_header->SetImageChecksum(image_checksum);
556 
557     if (VLOG_IS_ON(compiler)) {
558       const size_t separately_written_section_size = bitmap_section.Size();
559       const size_t total_uncompressed_size = image_info.image_size_ +
560           separately_written_section_size;
561       const size_t total_compressed_size = out_offset + separately_written_section_size;
562 
563       VLOG(compiler) << "Dex2Oat:uncompressedImageSize = " << total_uncompressed_size;
564       if (total_uncompressed_size != total_compressed_size) {
565         VLOG(compiler) << "Dex2Oat:compressedImageSize = " << total_compressed_size;
566       }
567     }
568 
569     CHECK_EQ(bitmap_section.End(), static_cast<size_t>(image_file->GetLength()))
570         << "Bitmap should be at the end of the file";
571 
572     // Write header last in case the compiler gets killed in the middle of image writing.
573     // We do not want to have a corrupted image with a valid header.
574     // Delay the writing of the primary image header until after writing secondary images.
575     if (i == 0u) {
576       primary_image_file = std::move(image_file);
577     } else {
578       if (!image_file.WriteHeaderAndClose(image_filename, image_header)) {
579         return false;
580       }
581       // Update the primary image checksum with the secondary image checksum.
582       primary_header->SetImageChecksum(primary_header->GetImageChecksum() ^ image_checksum);
583     }
584   }
585   DCHECK(primary_image_file != nullptr);
586   if (!primary_image_file.WriteHeaderAndClose(image_filenames[0], primary_header)) {
587     return false;
588   }
589 
590   return true;
591 }
592 
GetImageOffset(mirror::Object * object,size_t oat_index) const593 size_t ImageWriter::GetImageOffset(mirror::Object* object, size_t oat_index) const {
594   BinSlot bin_slot = GetImageBinSlot(object, oat_index);
595   const ImageInfo& image_info = GetImageInfo(oat_index);
596   size_t offset = image_info.GetBinSlotOffset(bin_slot.GetBin()) + bin_slot.GetOffset();
597   DCHECK_LT(offset, image_info.image_end_);
598   return offset;
599 }
600 
SetImageBinSlot(mirror::Object * object,BinSlot bin_slot)601 void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
602   DCHECK(object != nullptr);
603   DCHECK(!IsImageBinSlotAssigned(object));
604 
605   // Before we stomp over the lock word, save the hash code for later.
606   LockWord lw(object->GetLockWord(false));
607   switch (lw.GetState()) {
608     case LockWord::kFatLocked:
609       FALLTHROUGH_INTENDED;
610     case LockWord::kThinLocked: {
611       std::ostringstream oss;
612       bool thin = (lw.GetState() == LockWord::kThinLocked);
613       oss << (thin ? "Thin" : "Fat")
614           << " locked object " << object << "(" << object->PrettyTypeOf()
615           << ") found during object copy";
616       if (thin) {
617         oss << ". Lock owner:" << lw.ThinLockOwner();
618       }
619       LOG(FATAL) << oss.str();
620       UNREACHABLE();
621     }
622     case LockWord::kUnlocked:
623       // No hash, don't need to save it.
624       break;
625     case LockWord::kHashCode:
626       DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
627       saved_hashcode_map_.insert(std::make_pair(object, lw.GetHashCode()));
628       break;
629     default:
630       LOG(FATAL) << "Unreachable.";
631       UNREACHABLE();
632   }
633   object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()),
634                       /*as_volatile=*/ false);
635   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
636   DCHECK(IsImageBinSlotAssigned(object));
637 }
638 
AssignImageBinSlot(mirror::Object * object,size_t oat_index)639 ImageWriter::Bin ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
640   DCHECK(object != nullptr);
641 
642   // The magic happens here. We segregate objects into different bins based
643   // on how likely they are to get dirty at runtime.
644   //
645   // Likely-to-dirty objects get packed together into the same bin so that
646   // at runtime their page dirtiness ratio (how many dirty objects a page has) is
647   // maximized.
648   //
649   // This means more pages will stay either clean or shared dirty (with zygote) and
650   // the app will use less of its own (private) memory.
651   Bin bin = Bin::kRegular;
652 
653   if (kBinObjects) {
654     //
655     // Changing the bin of an object is purely a memory-use tuning.
656     // It has no change on runtime correctness.
657     //
658     // Memory analysis has determined that the following types of objects get dirtied
659     // the most:
660     //
661     // * Class'es which are verified [their clinit runs only at runtime]
662     //   - classes in general [because their static fields get overwritten]
663     //   - initialized classes with all-final statics are unlikely to be ever dirty,
664     //     so bin them separately
665     // * Art Methods that are:
666     //   - native [their native entry point is not looked up until runtime]
667     //   - have declaring classes that aren't initialized
668     //            [their interpreter/quick entry points are trampolines until the class
669     //             becomes initialized]
670     //
671     // We also assume the following objects get dirtied either never or extremely rarely:
672     //  * Strings (they are immutable)
673     //  * Art methods that aren't native and have initialized declared classes
674     //
675     // We assume that "regular" bin objects are highly unlikely to become dirtied,
676     // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
677     //
678     if (object->IsClass()) {
679       bin = Bin::kClassVerified;
680       ObjPtr<mirror::Class> klass = object->AsClass();
681 
682       // Move known dirty objects into their own sections. This includes:
683       //   - classes with dirty static fields.
684       auto is_dirty = [&](ObjPtr<mirror::Class> k) REQUIRES_SHARED(Locks::mutator_lock_) {
685         std::string temp;
686         std::string_view descriptor = k->GetDescriptor(&temp);
687         return dirty_image_objects_->find(descriptor) != dirty_image_objects_->end();
688       };
689       if (dirty_image_objects_ != nullptr && is_dirty(klass)) {
690         bin = Bin::kKnownDirty;
691       } else if (klass->GetStatus() == ClassStatus::kVisiblyInitialized) {
692         bin = Bin::kClassInitialized;
693 
694         // If the class's static fields are all final, put it into a separate bin
695         // since it's very likely it will stay clean.
696         uint32_t num_static_fields = klass->NumStaticFields();
697         if (num_static_fields == 0) {
698           bin = Bin::kClassInitializedFinalStatics;
699         } else {
700           // Maybe all the statics are final?
701           bool all_final = true;
702           for (uint32_t i = 0; i < num_static_fields; ++i) {
703             ArtField* field = klass->GetStaticField(i);
704             if (!field->IsFinal()) {
705               all_final = false;
706               break;
707             }
708           }
709 
710           if (all_final) {
711             bin = Bin::kClassInitializedFinalStatics;
712           }
713         }
714       }
715     } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
716       bin = Bin::kString;  // Strings are almost always immutable (except for object header).
717     } else if (object->GetClass<kVerifyNone>() == GetClassRoot<mirror::Object>()) {
718       // Instance of java lang object, probably a lock object. This means it will be dirty when we
719       // synchronize on it.
720       bin = Bin::kMiscDirty;
721     } else if (object->IsDexCache()) {
722       // Dex file field becomes dirty when the image is loaded.
723       bin = Bin::kMiscDirty;
724     }
725     // else bin = kBinRegular
726   }
727 
728   AssignImageBinSlot(object, oat_index, bin);
729   return bin;
730 }
731 
AssignImageBinSlot(mirror::Object * object,size_t oat_index,Bin bin)732 void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index, Bin bin) {
733   DCHECK(object != nullptr);
734   size_t object_size = object->SizeOf();
735 
736   // Assign the oat index too.
737   if (IsMultiImage()) {
738     DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
739     oat_index_map_.insert(std::make_pair(object, oat_index));
740   } else {
741     DCHECK(oat_index_map_.empty());
742   }
743 
744   ImageInfo& image_info = GetImageInfo(oat_index);
745 
746   size_t offset_delta = RoundUp(object_size, kObjectAlignment);  // 64-bit alignment
747   // How many bytes the current bin is at (aligned).
748   size_t current_offset = image_info.GetBinSlotSize(bin);
749   // Move the current bin size up to accommodate the object we just assigned a bin slot.
750   image_info.IncrementBinSlotSize(bin, offset_delta);
751 
752   BinSlot new_bin_slot(bin, current_offset);
753   SetImageBinSlot(object, new_bin_slot);
754 
755   image_info.IncrementBinSlotCount(bin, 1u);
756 
757   // Grow the image closer to the end by the object we just assigned.
758   image_info.image_end_ += offset_delta;
759 }
760 
WillMethodBeDirty(ArtMethod * m) const761 bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
762   if (m->IsNative()) {
763     return true;
764   }
765   ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
766   // Initialized is highly unlikely to dirty since there's no entry points to mutate.
767   return declaring_class == nullptr ||
768          declaring_class->GetStatus() != ClassStatus::kVisiblyInitialized;
769 }
770 
IsImageBinSlotAssigned(mirror::Object * object) const771 bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
772   DCHECK(object != nullptr);
773 
774   // We always stash the bin slot into a lockword, in the 'forwarding address' state.
775   // If it's in some other state, then we haven't yet assigned an image bin slot.
776   if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
777     return false;
778   } else if (kIsDebugBuild) {
779     LockWord lock_word = object->GetLockWord(false);
780     size_t offset = lock_word.ForwardingAddress();
781     BinSlot bin_slot(offset);
782     size_t oat_index = GetOatIndex(object);
783     const ImageInfo& image_info = GetImageInfo(oat_index);
784     DCHECK_LT(bin_slot.GetOffset(), image_info.GetBinSlotSize(bin_slot.GetBin()))
785         << "bin slot offset should not exceed the size of that bin";
786   }
787   return true;
788 }
789 
GetImageBinSlot(mirror::Object * object,size_t oat_index) const790 ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object, size_t oat_index) const {
791   DCHECK(object != nullptr);
792   DCHECK(IsImageBinSlotAssigned(object));
793 
794   LockWord lock_word = object->GetLockWord(false);
795   size_t offset = lock_word.ForwardingAddress();  // TODO: ForwardingAddress should be uint32_t
796   DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
797 
798   BinSlot bin_slot(static_cast<uint32_t>(offset));
799   DCHECK_LT(bin_slot.GetOffset(), GetImageInfo(oat_index).GetBinSlotSize(bin_slot.GetBin()));
800 
801   return bin_slot;
802 }
803 
UpdateImageBinSlotOffset(mirror::Object * object,size_t oat_index,size_t new_offset)804 void ImageWriter::UpdateImageBinSlotOffset(mirror::Object* object,
805                                            size_t oat_index,
806                                            size_t new_offset) {
807   BinSlot old_bin_slot = GetImageBinSlot(object, oat_index);
808   DCHECK_LT(new_offset, GetImageInfo(oat_index).GetBinSlotSize(old_bin_slot.GetBin()));
809   BinSlot new_bin_slot(old_bin_slot.GetBin(), new_offset);
810   object->SetLockWord(LockWord::FromForwardingAddress(new_bin_slot.Uint32Value()),
811                       /*as_volatile=*/ false);
812   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
813   DCHECK(IsImageBinSlotAssigned(object));
814 }
815 
AllocMemory()816 bool ImageWriter::AllocMemory() {
817   for (ImageInfo& image_info : image_infos_) {
818     const size_t length = RoundUp(image_info.CreateImageSections().first, kPageSize);
819 
820     std::string error_msg;
821     image_info.image_ = MemMap::MapAnonymous("image writer image",
822                                              length,
823                                              PROT_READ | PROT_WRITE,
824                                              /*low_4gb=*/ false,
825                                              &error_msg);
826     if (UNLIKELY(!image_info.image_.IsValid())) {
827       LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
828       return false;
829     }
830 
831     // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
832     CHECK_LE(image_info.image_end_, length);
833     image_info.image_bitmap_ = gc::accounting::ContinuousSpaceBitmap::Create(
834         "image bitmap", image_info.image_.Begin(), RoundUp(image_info.image_end_, kPageSize));
835     if (!image_info.image_bitmap_.IsValid()) {
836       LOG(ERROR) << "Failed to allocate memory for image bitmap";
837       return false;
838     }
839   }
840   return true;
841 }
842 
IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)843 static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
844     REQUIRES_SHARED(Locks::mutator_lock_) {
845   return klass->GetClassLoader() == nullptr;
846 }
847 
IsBootClassLoaderNonImageClass(mirror::Class * klass)848 bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
849   return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
850 }
851 
852 // This visitor follows the references of an instance, recursively then prune this class
853 // if a type of any field is pruned.
854 class ImageWriter::PruneObjectReferenceVisitor {
855  public:
PruneObjectReferenceVisitor(ImageWriter * image_writer,bool * early_exit,HashSet<mirror::Object * > * visited,bool * result)856   PruneObjectReferenceVisitor(ImageWriter* image_writer,
857                         bool* early_exit,
858                         HashSet<mirror::Object*>* visited,
859                         bool* result)
860       : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
861 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const862   ALWAYS_INLINE void VisitRootIfNonNull(
863       mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
864       REQUIRES_SHARED(Locks::mutator_lock_) { }
865 
VisitRoot(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const866   ALWAYS_INLINE void VisitRoot(
867       mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
868       REQUIRES_SHARED(Locks::mutator_lock_) { }
869 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const870   ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
871                                  MemberOffset offset,
872                                  bool is_static ATTRIBUTE_UNUSED) const
873       REQUIRES_SHARED(Locks::mutator_lock_) {
874     mirror::Object* ref =
875         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
876     if (ref == nullptr || visited_->find(ref) != visited_->end()) {
877       return;
878     }
879 
880     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
881         Runtime::Current()->GetClassLinker()->GetClassRoots();
882     ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
883     if (klass == GetClassRoot<mirror::Method>(class_roots) ||
884         klass == GetClassRoot<mirror::Constructor>(class_roots)) {
885       // Prune all classes using reflection because the content they held will not be fixup.
886       *result_ = true;
887     }
888 
889     if (ref->IsClass()) {
890       *result_ = *result_ ||
891           image_writer_->PruneImageClassInternal(ref->AsClass(), early_exit_, visited_);
892     } else {
893       // Record the object visited in case of circular reference.
894       visited_->insert(ref);
895       *result_ = *result_ ||
896           image_writer_->PruneImageClassInternal(klass, early_exit_, visited_);
897       ref->VisitReferences(*this, *this);
898       // Clean up before exit for next call of this function.
899       auto it = visited_->find(ref);
900       DCHECK(it != visited_->end());
901       visited_->erase(it);
902     }
903   }
904 
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const905   ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
906                                  ObjPtr<mirror::Reference> ref) const
907       REQUIRES_SHARED(Locks::mutator_lock_) {
908     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
909   }
910 
911  private:
912   ImageWriter* image_writer_;
913   bool* early_exit_;
914   HashSet<mirror::Object*>* visited_;
915   bool* const result_;
916 };
917 
918 
PruneImageClass(ObjPtr<mirror::Class> klass)919 bool ImageWriter::PruneImageClass(ObjPtr<mirror::Class> klass) {
920   bool early_exit = false;
921   HashSet<mirror::Object*> visited;
922   return PruneImageClassInternal(klass, &early_exit, &visited);
923 }
924 
PruneImageClassInternal(ObjPtr<mirror::Class> klass,bool * early_exit,HashSet<mirror::Object * > * visited)925 bool ImageWriter::PruneImageClassInternal(
926     ObjPtr<mirror::Class> klass,
927     bool* early_exit,
928     HashSet<mirror::Object*>* visited) {
929   DCHECK(early_exit != nullptr);
930   DCHECK(visited != nullptr);
931   DCHECK(compiler_options_.IsAppImage() || compiler_options_.IsBootImageExtension());
932   if (klass == nullptr || IsInBootImage(klass.Ptr())) {
933     return false;
934   }
935   auto found = prune_class_memo_.find(klass.Ptr());
936   if (found != prune_class_memo_.end()) {
937     // Already computed, return the found value.
938     return found->second;
939   }
940   // Circular dependencies, return false but do not store the result in the memoization table.
941   if (visited->find(klass.Ptr()) != visited->end()) {
942     *early_exit = true;
943     return false;
944   }
945   visited->insert(klass.Ptr());
946   bool result = IsBootClassLoaderClass(klass);
947   std::string temp;
948   // Prune if not an image class, this handles any broken sets of image classes such as having a
949   // class in the set but not it's superclass.
950   result = result || !compiler_options_.IsImageClass(klass->GetDescriptor(&temp));
951   bool my_early_exit = false;  // Only for ourselves, ignore caller.
952   // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
953   // app image.
954   if (klass->IsErroneous()) {
955     result = true;
956   } else {
957     ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
958     CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
959   }
960   if (!result) {
961     // Check interfaces since these wont be visited through VisitReferences.)
962     ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
963     for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
964       result = result || PruneImageClassInternal(if_table->GetInterface(i),
965                                                  &my_early_exit,
966                                                  visited);
967     }
968   }
969   if (klass->IsObjectArrayClass()) {
970     result = result || PruneImageClassInternal(klass->GetComponentType(),
971                                                &my_early_exit,
972                                                visited);
973   }
974   // Check static fields and their classes.
975   if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
976     size_t num_static_fields = klass->NumReferenceStaticFields();
977     // Presumably GC can happen when we are cross compiling, it should not cause performance
978     // problems to do pointer size logic.
979     MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
980         Runtime::Current()->GetClassLinker()->GetImagePointerSize());
981     for (size_t i = 0u; i < num_static_fields; ++i) {
982       mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
983       if (ref != nullptr) {
984         if (ref->IsClass()) {
985           result = result || PruneImageClassInternal(ref->AsClass(), &my_early_exit, visited);
986         } else {
987           mirror::Class* type = ref->GetClass();
988           result = result || PruneImageClassInternal(type, &my_early_exit, visited);
989           if (!result) {
990             // For non-class case, also go through all the types mentioned by it's fields'
991             // references recursively to decide whether to keep this class.
992             bool tmp = false;
993             PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
994             ref->VisitReferences(visitor, visitor);
995             result = result || tmp;
996           }
997         }
998       }
999       field_offset = MemberOffset(field_offset.Uint32Value() +
1000                                   sizeof(mirror::HeapReference<mirror::Object>));
1001     }
1002   }
1003   result = result || PruneImageClassInternal(klass->GetSuperClass(), &my_early_exit, visited);
1004   // Remove the class if the dex file is not in the set of dex files. This happens for classes that
1005   // are from uses-library if there is no profile. b/30688277
1006   ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
1007   if (dex_cache != nullptr) {
1008     result = result ||
1009         dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
1010   }
1011   // Erase the element we stored earlier since we are exiting the function.
1012   auto it = visited->find(klass.Ptr());
1013   DCHECK(it != visited->end());
1014   visited->erase(it);
1015   // Only store result if it is true or none of the calls early exited due to circular
1016   // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
1017   // a child call and we can remember the result.
1018   if (result == true || !my_early_exit || visited->empty()) {
1019     prune_class_memo_.Overwrite(klass.Ptr(), result);
1020   }
1021   *early_exit |= my_early_exit;
1022   return result;
1023 }
1024 
KeepClass(ObjPtr<mirror::Class> klass)1025 bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
1026   if (klass == nullptr) {
1027     return false;
1028   }
1029   if (IsInBootImage(klass.Ptr())) {
1030     // Already in boot image, return true.
1031     DCHECK(!compiler_options_.IsBootImage());
1032     return true;
1033   }
1034   std::string temp;
1035   if (!compiler_options_.IsImageClass(klass->GetDescriptor(&temp))) {
1036     return false;
1037   }
1038   if (compiler_options_.IsAppImage()) {
1039     // For app images, we need to prune classes that
1040     // are defined by the boot class path we're compiling against but not in
1041     // the boot image spaces since these may have already been loaded at
1042     // run time when this image is loaded. Keep classes in the boot image
1043     // spaces we're compiling against since we don't want to re-resolve these.
1044     return !PruneImageClass(klass);
1045   }
1046   return true;
1047 }
1048 
1049 class ImageWriter::PruneClassesVisitor : public ClassVisitor {
1050  public:
PruneClassesVisitor(ImageWriter * image_writer,ObjPtr<mirror::ClassLoader> class_loader)1051   PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
1052       : image_writer_(image_writer),
1053         class_loader_(class_loader),
1054         classes_to_prune_(),
1055         defined_class_count_(0u) { }
1056 
operator ()(ObjPtr<mirror::Class> klass)1057   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1058     if (!image_writer_->KeepClass(klass.Ptr())) {
1059       classes_to_prune_.insert(klass.Ptr());
1060       if (klass->GetClassLoader() == class_loader_) {
1061         ++defined_class_count_;
1062       }
1063     }
1064     return true;
1065   }
1066 
Prune()1067   size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
1068     ClassTable* class_table =
1069         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
1070     for (mirror::Class* klass : classes_to_prune_) {
1071       std::string storage;
1072       const char* descriptor = klass->GetDescriptor(&storage);
1073       bool result = class_table->Remove(descriptor);
1074       DCHECK(result);
1075       DCHECK(!class_table->Remove(descriptor)) << descriptor;
1076     }
1077     return defined_class_count_;
1078   }
1079 
1080  private:
1081   ImageWriter* const image_writer_;
1082   const ObjPtr<mirror::ClassLoader> class_loader_;
1083   HashSet<mirror::Class*> classes_to_prune_;
1084   size_t defined_class_count_;
1085 };
1086 
1087 class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
1088  public:
PruneClassLoaderClassesVisitor(ImageWriter * image_writer)1089   explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
1090       : image_writer_(image_writer), removed_class_count_(0) {}
1091 
Visit(ObjPtr<mirror::ClassLoader> class_loader)1092   void Visit(ObjPtr<mirror::ClassLoader> class_loader) override
1093       REQUIRES_SHARED(Locks::mutator_lock_) {
1094     PruneClassesVisitor classes_visitor(image_writer_, class_loader);
1095     ClassTable* class_table =
1096         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
1097     class_table->Visit(classes_visitor);
1098     removed_class_count_ += classes_visitor.Prune();
1099   }
1100 
GetRemovedClassCount() const1101   size_t GetRemovedClassCount() const {
1102     return removed_class_count_;
1103   }
1104 
1105  private:
1106   ImageWriter* const image_writer_;
1107   size_t removed_class_count_;
1108 };
1109 
VisitClassLoaders(ClassLoaderVisitor * visitor)1110 void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1111   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1112   visitor->Visit(nullptr);  // Visit boot class loader.
1113   Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1114 }
1115 
ClearDexCache(ObjPtr<mirror::DexCache> dex_cache)1116 void ImageWriter::ClearDexCache(ObjPtr<mirror::DexCache> dex_cache) {
1117   // Clear methods.
1118   mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
1119   for (size_t slot_idx = 0, num = dex_cache->NumResolvedMethods(); slot_idx != num; ++slot_idx) {
1120     mirror::MethodDexCachePair invalid(nullptr,
1121                                        mirror::MethodDexCachePair::InvalidIndexForSlot(slot_idx));
1122     mirror::DexCache::SetNativePair(resolved_methods, slot_idx, invalid);
1123   }
1124   // Clear fields.
1125   mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
1126   for (size_t slot_idx = 0, num = dex_cache->NumResolvedFields(); slot_idx != num; ++slot_idx) {
1127     mirror::FieldDexCachePair invalid(nullptr,
1128                                       mirror::FieldDexCachePair::InvalidIndexForSlot(slot_idx));
1129     mirror::DexCache::SetNativePair(resolved_fields, slot_idx, invalid);
1130   }
1131   // Clear types.
1132   mirror::TypeDexCacheType* resolved_types = dex_cache->GetResolvedTypes();
1133   for (size_t slot_idx = 0, num = dex_cache->NumResolvedTypes(); slot_idx != num; ++slot_idx) {
1134     mirror::TypeDexCachePair invalid(nullptr,
1135                                      mirror::TypeDexCachePair::InvalidIndexForSlot(slot_idx));
1136     resolved_types[slot_idx].store(invalid, std::memory_order_relaxed);
1137   }
1138   // Clear strings.
1139   mirror::StringDexCacheType* resolved_strings = dex_cache->GetStrings();
1140   for (size_t slot_idx = 0, num = dex_cache->NumStrings(); slot_idx != num; ++slot_idx) {
1141     mirror::StringDexCachePair invalid(nullptr,
1142                                        mirror::StringDexCachePair::InvalidIndexForSlot(slot_idx));
1143     resolved_strings[slot_idx].store(invalid, std::memory_order_relaxed);
1144   }
1145   // Clear method types.
1146   mirror::MethodTypeDexCacheType* resolved_method_types = dex_cache->GetResolvedMethodTypes();
1147   size_t num_resolved_method_types = dex_cache->NumResolvedMethodTypes();
1148   for (size_t slot_idx = 0; slot_idx != num_resolved_method_types; ++slot_idx) {
1149     mirror::MethodTypeDexCachePair invalid(
1150         nullptr, mirror::MethodTypeDexCachePair::InvalidIndexForSlot(slot_idx));
1151     resolved_method_types[slot_idx].store(invalid, std::memory_order_relaxed);
1152   }
1153   // Clear call sites.
1154   std::fill_n(dex_cache->GetResolvedCallSites(),
1155               dex_cache->NumResolvedCallSites(),
1156               GcRoot<mirror::CallSite>(nullptr));
1157 }
1158 
PruneNonImageClasses()1159 void ImageWriter::PruneNonImageClasses() {
1160   Runtime* runtime = Runtime::Current();
1161   ClassLinker* class_linker = runtime->GetClassLinker();
1162   Thread* self = Thread::Current();
1163   ScopedAssertNoThreadSuspension sa(__FUNCTION__);
1164 
1165   // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1166   // sure the other ones don't get unloaded before the OatWriter runs.
1167   class_linker->VisitClassTables(
1168       [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1169     table->RemoveStrongRoots(
1170         [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1171       ObjPtr<mirror::Object> obj = root.Read();
1172       if (obj->IsDexCache()) {
1173         // Return true if the dex file is not one of the ones in the map.
1174         return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1175             dex_file_oat_index_map_.end();
1176       }
1177       // Return false to avoid removing.
1178       return false;
1179     });
1180   });
1181 
1182   // Remove the undesired classes from the class roots.
1183   {
1184     PruneClassLoaderClassesVisitor class_loader_visitor(this);
1185     VisitClassLoaders(&class_loader_visitor);
1186     VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
1187   }
1188 
1189   // Completely clear DexCaches.
1190   std::vector<ObjPtr<mirror::DexCache>> dex_caches = FindDexCaches(self);
1191   for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1192     ClearDexCache(dex_cache);
1193   }
1194 
1195   // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1196   class_linker->DropFindArrayClassCache();
1197 
1198   // Clear to save RAM.
1199   prune_class_memo_.clear();
1200 }
1201 
FindDexCaches(Thread * self)1202 std::vector<ObjPtr<mirror::DexCache>> ImageWriter::FindDexCaches(Thread* self) {
1203   std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1204   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1205   ReaderMutexLock mu2(self, *Locks::dex_lock_);
1206   dex_caches.reserve(class_linker->GetDexCachesData().size());
1207   for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1208     if (self->IsJWeakCleared(data.weak_root)) {
1209       continue;
1210     }
1211     dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
1212   }
1213   return dex_caches;
1214 }
1215 
CheckNonImageClassesRemoved()1216 void ImageWriter::CheckNonImageClassesRemoved() {
1217   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1218     if (obj->IsClass() && !IsInBootImage(obj)) {
1219       ObjPtr<Class> klass = obj->AsClass();
1220       if (!KeepClass(klass)) {
1221         DumpImageClasses();
1222         CHECK(KeepClass(klass))
1223             << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1224       }
1225     }
1226   };
1227   gc::Heap* heap = Runtime::Current()->GetHeap();
1228   heap->VisitObjects(visitor);
1229 }
1230 
DumpImageClasses()1231 void ImageWriter::DumpImageClasses() {
1232   for (const std::string& image_class : compiler_options_.GetImageClasses()) {
1233     LOG(INFO) << " " << image_class;
1234   }
1235 }
1236 
CollectDexCaches(Thread * self,size_t oat_index) const1237 ObjPtr<mirror::ObjectArray<mirror::Object>> ImageWriter::CollectDexCaches(Thread* self,
1238                                                                           size_t oat_index) const {
1239   HashSet<const DexFile*> image_dex_files;
1240   for (auto& pair : dex_file_oat_index_map_) {
1241     const DexFile* image_dex_file = pair.first;
1242     size_t image_oat_index = pair.second;
1243     if (oat_index == image_oat_index) {
1244       image_dex_files.insert(image_dex_file);
1245     }
1246   }
1247 
1248   // build an Object[] of all the DexCaches used in the source_space_.
1249   // Since we can't hold the dex lock when allocating the dex_caches
1250   // ObjectArray, we lock the dex lock twice, first to get the number
1251   // of dex caches first and then lock it again to copy the dex
1252   // caches. We check that the number of dex caches does not change.
1253   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1254   size_t dex_cache_count = 0;
1255   {
1256     ReaderMutexLock mu(self, *Locks::dex_lock_);
1257     // Count number of dex caches not in the boot image.
1258     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1259       ObjPtr<mirror::DexCache> dex_cache =
1260           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
1261       if (dex_cache == nullptr) {
1262         continue;
1263       }
1264       const DexFile* dex_file = dex_cache->GetDexFile();
1265       if (IsImageDexCache(dex_cache)) {
1266         dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1267       }
1268     }
1269   }
1270   ObjPtr<ObjectArray<Object>> dex_caches = ObjectArray<Object>::Alloc(
1271       self, GetClassRoot<ObjectArray<Object>>(class_linker), dex_cache_count);
1272   CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
1273   {
1274     ReaderMutexLock mu(self, *Locks::dex_lock_);
1275     size_t non_image_dex_caches = 0;
1276     // Re-count number of non image dex caches.
1277     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1278       ObjPtr<mirror::DexCache> dex_cache =
1279           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
1280       if (dex_cache == nullptr) {
1281         continue;
1282       }
1283       const DexFile* dex_file = dex_cache->GetDexFile();
1284       if (IsImageDexCache(dex_cache)) {
1285         non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1286       }
1287     }
1288     CHECK_EQ(dex_cache_count, non_image_dex_caches)
1289         << "The number of non-image dex caches changed.";
1290     size_t i = 0;
1291     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1292       ObjPtr<mirror::DexCache> dex_cache =
1293           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
1294       if (dex_cache == nullptr) {
1295         continue;
1296       }
1297       const DexFile* dex_file = dex_cache->GetDexFile();
1298       if (IsImageDexCache(dex_cache) &&
1299           image_dex_files.find(dex_file) != image_dex_files.end()) {
1300         dex_caches->Set<false>(i, dex_cache.Ptr());
1301         ++i;
1302       }
1303     }
1304   }
1305   return dex_caches;
1306 }
1307 
CreateImageRoots(size_t oat_index,Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects) const1308 ObjPtr<ObjectArray<Object>> ImageWriter::CreateImageRoots(
1309     size_t oat_index,
1310     Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects) const {
1311   Runtime* runtime = Runtime::Current();
1312   ClassLinker* class_linker = runtime->GetClassLinker();
1313   Thread* self = Thread::Current();
1314   StackHandleScope<2> hs(self);
1315 
1316   Handle<ObjectArray<Object>> dex_caches(hs.NewHandle(CollectDexCaches(self, oat_index)));
1317 
1318   // build an Object[] of the roots needed to restore the runtime
1319   int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compiler_options_.IsAppImage());
1320   Handle<ObjectArray<Object>> image_roots(hs.NewHandle(ObjectArray<Object>::Alloc(
1321       self, GetClassRoot<ObjectArray<Object>>(class_linker), image_roots_size)));
1322   image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
1323   image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
1324   if (!compiler_options_.IsAppImage()) {
1325     DCHECK(boot_image_live_objects != nullptr);
1326     image_roots->Set<false>(ImageHeader::kBootImageLiveObjects, boot_image_live_objects.Get());
1327   } else {
1328     DCHECK(boot_image_live_objects == nullptr);
1329     image_roots->Set<false>(ImageHeader::kAppImageClassLoader, GetAppClassLoader());
1330   }
1331   for (int32_t i = 0; i != image_roots_size; ++i) {
1332     CHECK(image_roots->Get(i) != nullptr);
1333   }
1334   return image_roots.Get();
1335 }
1336 
RecordNativeRelocations(ObjPtr<mirror::Class> klass,size_t oat_index)1337 void ImageWriter::RecordNativeRelocations(ObjPtr<mirror::Class> klass, size_t oat_index) {
1338   // Visit and assign offsets for fields and field arrays.
1339   DCHECK_EQ(oat_index, GetOatIndexForClass(klass));
1340   DCHECK(!klass->IsErroneous()) << klass->GetStatus();
1341   if (compiler_options_.IsAppImage()) {
1342     // Extra consistency check: no boot loader classes should be left!
1343     CHECK(!IsBootClassLoaderClass(klass)) << klass->PrettyClass();
1344   }
1345   LengthPrefixedArray<ArtField>* fields[] = {
1346       klass->GetSFieldsPtr(), klass->GetIFieldsPtr(),
1347   };
1348   ImageInfo& image_info = GetImageInfo(oat_index);
1349   for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1350     // Total array length including header.
1351     if (cur_fields != nullptr) {
1352       // Forward the entire array at once.
1353       size_t offset = image_info.GetBinSlotSize(Bin::kArtField);
1354       DCHECK(!IsInBootImage(cur_fields));
1355       bool inserted =
1356           native_object_relocations_.insert(std::make_pair(
1357               cur_fields,
1358               NativeObjectRelocation {
1359                   oat_index, offset, NativeObjectRelocationType::kArtFieldArray
1360               })).second;
1361       CHECK(inserted) << "Field array " << cur_fields << " already forwarded";
1362       const size_t size = LengthPrefixedArray<ArtField>::ComputeSize(cur_fields->size());
1363       offset += size;
1364       image_info.IncrementBinSlotSize(Bin::kArtField, size);
1365       DCHECK_EQ(offset, image_info.GetBinSlotSize(Bin::kArtField));
1366     }
1367   }
1368   // Visit and assign offsets for methods.
1369   size_t num_methods = klass->NumMethods();
1370   if (num_methods != 0) {
1371     bool any_dirty = false;
1372     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1373       if (WillMethodBeDirty(&m)) {
1374         any_dirty = true;
1375         break;
1376       }
1377     }
1378     NativeObjectRelocationType type = any_dirty
1379         ? NativeObjectRelocationType::kArtMethodDirty
1380         : NativeObjectRelocationType::kArtMethodClean;
1381     Bin bin_type = BinTypeForNativeRelocationType(type);
1382     // Forward the entire array at once, but header first.
1383     const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1384     const size_t method_size = ArtMethod::Size(target_ptr_size_);
1385     const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1386                                                                            method_size,
1387                                                                            method_alignment);
1388     LengthPrefixedArray<ArtMethod>* array = klass->GetMethodsPtr();
1389     size_t offset = image_info.GetBinSlotSize(bin_type);
1390     DCHECK(!IsInBootImage(array));
1391     bool inserted =
1392         native_object_relocations_.insert(std::make_pair(
1393             array,
1394             NativeObjectRelocation {
1395                   oat_index,
1396                   offset,
1397                   any_dirty ? NativeObjectRelocationType::kArtMethodArrayDirty
1398                             : NativeObjectRelocationType::kArtMethodArrayClean
1399               })).second;
1400     CHECK(inserted) << "Method array " << array << " already forwarded";
1401     image_info.IncrementBinSlotSize(bin_type, header_size);
1402     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1403       AssignMethodOffset(&m, type, oat_index);
1404     }
1405     (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
1406   }
1407   // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1408   // live.
1409   if (klass->ShouldHaveImt()) {
1410     ImTable* imt = klass->GetImt(target_ptr_size_);
1411     if (TryAssignImTableOffset(imt, oat_index)) {
1412       // Since imt's can be shared only do this the first time to not double count imt method
1413       // fixups.
1414       for (size_t i = 0; i < ImTable::kSize; ++i) {
1415         ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1416         DCHECK(imt_method != nullptr);
1417         if (imt_method->IsRuntimeMethod() &&
1418             !IsInBootImage(imt_method) &&
1419             !NativeRelocationAssigned(imt_method)) {
1420           AssignMethodOffset(imt_method, NativeObjectRelocationType::kRuntimeMethod, oat_index);
1421         }
1422       }
1423     }
1424   }
1425 }
1426 
NativeRelocationAssigned(void * ptr) const1427 bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1428   return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1429 }
1430 
TryAssignImTableOffset(ImTable * imt,size_t oat_index)1431 bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1432   // No offset, or already assigned.
1433   if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1434     return false;
1435   }
1436   // If the method is a conflict method we also want to assign the conflict table offset.
1437   ImageInfo& image_info = GetImageInfo(oat_index);
1438   const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1439   native_object_relocations_.insert(std::make_pair(
1440       imt,
1441       NativeObjectRelocation {
1442           oat_index,
1443           image_info.GetBinSlotSize(Bin::kImTable),
1444           NativeObjectRelocationType::kIMTable
1445       }));
1446   image_info.IncrementBinSlotSize(Bin::kImTable, size);
1447   return true;
1448 }
1449 
TryAssignConflictTableOffset(ImtConflictTable * table,size_t oat_index)1450 void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1451   // No offset, or already assigned.
1452   if (table == nullptr || NativeRelocationAssigned(table)) {
1453     return;
1454   }
1455   CHECK(!IsInBootImage(table));
1456   // If the method is a conflict method we also want to assign the conflict table offset.
1457   ImageInfo& image_info = GetImageInfo(oat_index);
1458   const size_t size = table->ComputeSize(target_ptr_size_);
1459   native_object_relocations_.insert(std::make_pair(
1460       table,
1461       NativeObjectRelocation {
1462           oat_index,
1463           image_info.GetBinSlotSize(Bin::kIMTConflictTable),
1464           NativeObjectRelocationType::kIMTConflictTable
1465       }));
1466   image_info.IncrementBinSlotSize(Bin::kIMTConflictTable, size);
1467 }
1468 
AssignMethodOffset(ArtMethod * method,NativeObjectRelocationType type,size_t oat_index)1469 void ImageWriter::AssignMethodOffset(ArtMethod* method,
1470                                      NativeObjectRelocationType type,
1471                                      size_t oat_index) {
1472   DCHECK(!IsInBootImage(method));
1473   CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
1474       << ArtMethod::PrettyMethod(method);
1475   if (method->IsRuntimeMethod()) {
1476     TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1477   }
1478   ImageInfo& image_info = GetImageInfo(oat_index);
1479   Bin bin_type = BinTypeForNativeRelocationType(type);
1480   size_t offset = image_info.GetBinSlotSize(bin_type);
1481   native_object_relocations_.insert(
1482       std::make_pair(method, NativeObjectRelocation { oat_index, offset, type }));
1483   image_info.IncrementBinSlotSize(bin_type, ArtMethod::Size(target_ptr_size_));
1484 }
1485 
1486 class ImageWriter::LayoutHelper {
1487  public:
LayoutHelper(ImageWriter * image_writer)1488   explicit LayoutHelper(ImageWriter* image_writer)
1489       : image_writer_(image_writer) {
1490     bin_objects_.resize(image_writer_->image_infos_.size());
1491     for (auto& inner : bin_objects_) {
1492       inner.resize(enum_cast<size_t>(Bin::kMirrorCount));
1493     }
1494   }
1495 
1496   void ProcessDexFileObjects(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1497   void ProcessRoots(VariableSizedHandleScope* handles) REQUIRES_SHARED(Locks::mutator_lock_);
1498   void FinalizeInternTables() REQUIRES_SHARED(Locks::mutator_lock_);
1499 
1500   void VerifyImageBinSlotsAssigned() REQUIRES_SHARED(Locks::mutator_lock_);
1501 
1502   void FinalizeBinSlotOffsets() REQUIRES_SHARED(Locks::mutator_lock_);
1503 
1504   /*
1505    * Collects the string reference info necessary for loading app images.
1506    *
1507    * Because AppImages may contain interned strings that must be deduplicated
1508    * with previously interned strings when loading the app image, we need to
1509    * visit references to these strings and update them to point to the correct
1510    * string. To speed up the visiting of references at load time we include
1511    * a list of offsets to string references in the AppImage.
1512    */
1513   void CollectStringReferenceInfo() REQUIRES_SHARED(Locks::mutator_lock_);
1514 
1515  private:
1516   class CollectClassesVisitor;
1517   class CollectRootsVisitor;
1518   class CollectStringReferenceVisitor;
1519   class VisitReferencesVisitor;
1520 
1521   void ProcessInterns(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1522   void ProcessWorkQueue() REQUIRES_SHARED(Locks::mutator_lock_);
1523 
1524   using WorkQueue = std::deque<std::pair<ObjPtr<mirror::Object>, size_t>>;
1525 
1526   void VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index)
1527       REQUIRES_SHARED(Locks::mutator_lock_);
1528   bool TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index)
1529       REQUIRES_SHARED(Locks::mutator_lock_);
1530 
1531   ImageWriter* const image_writer_;
1532 
1533   // Work list of <object, oat_index> for objects. Everything in the queue must already be
1534   // assigned a bin slot.
1535   WorkQueue work_queue_;
1536 
1537   // Objects for individual bins. Indexed by `oat_index` and `bin`.
1538   // Cannot use ObjPtr<> because of invalidation in Heap::VisitObjects().
1539   dchecked_vector<dchecked_vector<dchecked_vector<mirror::Object*>>> bin_objects_;
1540 
1541   // Interns that do not have a corresponding StringId in any of the input dex files.
1542   // These shall be assigned to individual images based on the `oat_index` that we
1543   // see as we visit them during the work queue processing.
1544   dchecked_vector<mirror::String*> non_dex_file_interns_;
1545 };
1546 
1547 class ImageWriter::LayoutHelper::CollectClassesVisitor : public ClassVisitor {
1548  public:
CollectClassesVisitor(ImageWriter * image_writer)1549   explicit CollectClassesVisitor(ImageWriter* image_writer)
1550       : image_writer_(image_writer),
1551         dex_files_(image_writer_->compiler_options_.GetDexFilesForOatFile()) {}
1552 
operator ()(ObjPtr<mirror::Class> klass)1553   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1554     if (!image_writer_->IsInBootImage(klass.Ptr())) {
1555       ObjPtr<mirror::Class> component_type = klass;
1556       size_t dimension = 0u;
1557       while (component_type->IsArrayClass()) {
1558         ++dimension;
1559         component_type = component_type->GetComponentType();
1560       }
1561       DCHECK(!component_type->IsProxyClass());
1562       size_t dex_file_index;
1563       uint32_t class_def_index = 0u;
1564       if (UNLIKELY(component_type->IsPrimitive())) {
1565         DCHECK(image_writer_->compiler_options_.IsBootImage());
1566         dex_file_index = 0u;
1567         class_def_index = enum_cast<uint32_t>(component_type->GetPrimitiveType());
1568       } else {
1569         auto it = std::find(dex_files_.begin(), dex_files_.end(), &component_type->GetDexFile());
1570         DCHECK(it != dex_files_.end()) << klass->PrettyDescriptor();
1571         dex_file_index = std::distance(dex_files_.begin(), it) + 1u;  // 0 is for primitive types.
1572         class_def_index = component_type->GetDexClassDefIndex();
1573       }
1574       klasses_.push_back({klass, dex_file_index, class_def_index, dimension});
1575     }
1576     return true;
1577   }
1578 
ProcessCollectedClasses(Thread * self)1579   WorkQueue ProcessCollectedClasses(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
1580     std::sort(klasses_.begin(), klasses_.end());
1581 
1582     ImageWriter* image_writer = image_writer_;
1583     WorkQueue work_queue;
1584     size_t last_dex_file_index = static_cast<size_t>(-1);
1585     size_t last_oat_index = static_cast<size_t>(-1);
1586     for (const ClassEntry& entry : klasses_) {
1587       if (last_dex_file_index != entry.dex_file_index) {
1588         if (UNLIKELY(entry.dex_file_index == 0u)) {
1589           last_oat_index = GetDefaultOatIndex();  // Primitive type.
1590         } else {
1591           uint32_t dex_file_index = entry.dex_file_index - 1u;  // 0 is for primitive types.
1592           last_oat_index = image_writer->GetOatIndexForDexFile(dex_files_[dex_file_index]);
1593         }
1594         last_dex_file_index = entry.dex_file_index;
1595       }
1596       // Count the number of classes for class tables.
1597       image_writer->image_infos_[last_oat_index].class_table_size_ += 1u;
1598       work_queue.emplace_back(entry.klass, last_oat_index);
1599     }
1600     klasses_.clear();
1601 
1602     // Prepare image class tables.
1603     std::vector<mirror::Class*> boot_image_classes;
1604     if (image_writer->compiler_options_.IsAppImage()) {
1605       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1606       ImageInfo& image_info = image_writer->image_infos_[0];
1607       // Log the non-boot image class count for app image for debugging purposes.
1608       VLOG(compiler) << "Dex2Oat:AppImage:classCount = " << image_info.class_table_size_;
1609       // Collect boot image classes referenced by app class loader's class table.
1610       ClassTable* app_class_table = image_writer->GetAppClassLoader()->GetClassTable();
1611       ReaderMutexLock lock(self, app_class_table->lock_);
1612       DCHECK_EQ(app_class_table->classes_.size(), 1u);
1613       const ClassTable::ClassSet& app_class_set = app_class_table->classes_[0];
1614       DCHECK_GE(app_class_set.size(), image_info.class_table_size_);
1615       boot_image_classes.reserve(app_class_set.size() - image_info.class_table_size_);
1616       for (const ClassTable::TableSlot& slot : app_class_set) {
1617         mirror::Class* klass = slot.Read<kWithoutReadBarrier>().Ptr();
1618         if (image_writer->IsInBootImage(klass)) {
1619           boot_image_classes.push_back(klass);
1620         }
1621       }
1622       DCHECK_EQ(app_class_set.size() - image_info.class_table_size_, boot_image_classes.size());
1623       // Increase the app class table size to include referenced boot image classes.
1624       image_info.class_table_size_ = app_class_set.size();
1625     }
1626     for (ImageInfo& image_info : image_writer->image_infos_) {
1627       if (image_info.class_table_size_ != 0u) {
1628         // Make sure the class table shall be full by allocating a buffer of the right size.
1629         size_t buffer_size = static_cast<size_t>(
1630             ceil(image_info.class_table_size_ / kImageClassTableMaxLoadFactor));
1631         image_info.class_table_buffer_.reset(new ClassTable::TableSlot[buffer_size]);
1632         DCHECK(image_info.class_table_buffer_ != nullptr);
1633         image_info.class_table_.emplace(kImageClassTableMinLoadFactor,
1634                                         kImageClassTableMaxLoadFactor,
1635                                         image_info.class_table_buffer_.get(),
1636                                         buffer_size);
1637       }
1638     }
1639     for (const auto& pair : work_queue) {
1640       ObjPtr<mirror::Class> klass = pair.first->AsClass();
1641       size_t oat_index = pair.second;
1642       DCHECK(image_writer->image_infos_[oat_index].class_table_.has_value());
1643       ClassTable::ClassSet& class_table = *image_writer->image_infos_[oat_index].class_table_;
1644       uint32_t hash = ClassTable::TableSlot::HashDescriptor(klass);
1645       bool inserted = class_table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1646       DCHECK(inserted) << "Class " << klass->PrettyDescriptor()
1647           << " (" << klass.Ptr() << ") already inserted";
1648     }
1649     if (image_writer->compiler_options_.IsAppImage()) {
1650       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1651       ImageInfo& image_info = image_writer->image_infos_[0];
1652       if (image_info.class_table_size_ != 0u) {
1653         // Insert boot image class references to the app class table.
1654         // The order of insertion into the app class loader's ClassTable is non-deterministic,
1655         // so sort the boot image classes by the boot image address to get deterministic table.
1656         std::sort(boot_image_classes.begin(), boot_image_classes.end());
1657         DCHECK(image_info.class_table_.has_value());
1658         ClassTable::ClassSet& table = *image_info.class_table_;
1659         for (mirror::Class* klass : boot_image_classes) {
1660           uint32_t hash = ClassTable::TableSlot::HashDescriptor(klass);
1661           bool inserted = table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1662           DCHECK(inserted) << "Boot image class " << klass->PrettyDescriptor()
1663               << " (" << klass << ") already inserted";
1664         }
1665         DCHECK_EQ(table.size(), image_info.class_table_size_);
1666       }
1667     }
1668     for (ImageInfo& image_info : image_writer->image_infos_) {
1669       DCHECK_EQ(image_info.class_table_bytes_, 0u);
1670       if (image_info.class_table_size_ != 0u) {
1671         DCHECK(image_info.class_table_.has_value());
1672         DCHECK_EQ(image_info.class_table_->size(), image_info.class_table_size_);
1673         image_info.class_table_bytes_ = image_info.class_table_->WriteToMemory(nullptr);
1674         DCHECK_NE(image_info.class_table_bytes_, 0u);
1675       } else {
1676         DCHECK(!image_info.class_table_.has_value());
1677       }
1678     }
1679 
1680     return work_queue;
1681   }
1682 
1683  private:
1684   struct ClassEntry {
1685     ObjPtr<mirror::Class> klass;
1686     // We shall sort classes by dex file, class def index and array dimension.
1687     size_t dex_file_index;
1688     uint32_t class_def_index;
1689     size_t dimension;
1690 
operator <art::linker::ImageWriter::LayoutHelper::CollectClassesVisitor::ClassEntry1691     bool operator<(const ClassEntry& other) const {
1692       return std::tie(dex_file_index, class_def_index, dimension) <
1693              std::tie(other.dex_file_index, other.class_def_index, other.dimension);
1694     }
1695   };
1696 
1697   ImageWriter* const image_writer_;
1698   ArrayRef<const DexFile* const> dex_files_;
1699   std::deque<ClassEntry> klasses_;
1700 };
1701 
1702 class ImageWriter::LayoutHelper::CollectRootsVisitor {
1703  public:
1704   CollectRootsVisitor() = default;
1705 
ReleaseRoots()1706   std::vector<ObjPtr<mirror::Object>> ReleaseRoots() {
1707     std::vector<ObjPtr<mirror::Object>> roots;
1708     roots.swap(roots_);
1709     return roots;
1710   }
1711 
VisitRootIfNonNull(StackReference<mirror::Object> * ref)1712   void VisitRootIfNonNull(StackReference<mirror::Object>* ref) {
1713     if (!ref->IsNull()) {
1714       roots_.push_back(ref->AsMirrorPtr());
1715     }
1716   }
1717 
1718  private:
1719   std::vector<ObjPtr<mirror::Object>> roots_;
1720 };
1721 
1722 class ImageWriter::LayoutHelper::CollectStringReferenceVisitor {
1723  public:
CollectStringReferenceVisitor(const ImageWriter * image_writer,size_t oat_index,std::vector<AppImageReferenceOffsetInfo> * const string_reference_offsets,ObjPtr<mirror::Object> current_obj)1724   explicit CollectStringReferenceVisitor(
1725       const ImageWriter* image_writer,
1726       size_t oat_index,
1727       std::vector<AppImageReferenceOffsetInfo>* const string_reference_offsets,
1728       ObjPtr<mirror::Object> current_obj)
1729       : image_writer_(image_writer),
1730         oat_index_(oat_index),
1731         string_reference_offsets_(string_reference_offsets),
1732         current_obj_(current_obj) {}
1733 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1734   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1735       REQUIRES_SHARED(Locks::mutator_lock_) {
1736     if (!root->IsNull()) {
1737       VisitRoot(root);
1738     }
1739   }
1740 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1741   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1742       REQUIRES_SHARED(Locks::mutator_lock_)  {
1743     // Only dex caches have native String roots. These are collected separately.
1744     DCHECK(current_obj_->IsDexCache() ||
1745            !image_writer_->IsInternedAppImageStringReference(root->AsMirrorPtr()))
1746         << mirror::Object::PrettyTypeOf(current_obj_);
1747   }
1748 
1749   // Collects info for managed fields that reference managed Strings.
operator ()(ObjPtr<mirror::Object> obj,MemberOffset member_offset,bool is_static ATTRIBUTE_UNUSED) const1750   void operator() (ObjPtr<mirror::Object> obj,
1751                    MemberOffset member_offset,
1752                    bool is_static ATTRIBUTE_UNUSED) const
1753       REQUIRES_SHARED(Locks::mutator_lock_) {
1754     ObjPtr<mirror::Object> referred_obj =
1755         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(member_offset);
1756 
1757     if (image_writer_->IsInternedAppImageStringReference(referred_obj)) {
1758       size_t base_offset = image_writer_->GetImageOffset(current_obj_.Ptr(), oat_index_);
1759       string_reference_offsets_->emplace_back(base_offset, member_offset.Uint32Value());
1760     }
1761   }
1762 
1763   ALWAYS_INLINE
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const1764   void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1765                    ObjPtr<mirror::Reference> ref) const
1766       REQUIRES_SHARED(Locks::mutator_lock_) {
1767     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1768   }
1769 
1770  private:
1771   const ImageWriter* const image_writer_;
1772   const size_t oat_index_;
1773   std::vector<AppImageReferenceOffsetInfo>* const string_reference_offsets_;
1774   const ObjPtr<mirror::Object> current_obj_;
1775 };
1776 
1777 class ImageWriter::LayoutHelper::VisitReferencesVisitor {
1778  public:
VisitReferencesVisitor(LayoutHelper * helper,size_t oat_index)1779   VisitReferencesVisitor(LayoutHelper* helper, size_t oat_index)
1780       : helper_(helper), oat_index_(oat_index) {}
1781 
1782   // Fix up separately since we also need to fix up method entrypoints.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1783   ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1784       REQUIRES_SHARED(Locks::mutator_lock_) {
1785     if (!root->IsNull()) {
1786       VisitRoot(root);
1787     }
1788   }
1789 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1790   ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1791       REQUIRES_SHARED(Locks::mutator_lock_) {
1792     root->Assign(VisitReference(root->AsMirrorPtr()));
1793   }
1794 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const1795   ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
1796                                  MemberOffset offset,
1797                                  bool is_static ATTRIBUTE_UNUSED) const
1798       REQUIRES_SHARED(Locks::mutator_lock_) {
1799     mirror::Object* ref =
1800         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1801     obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1802   }
1803 
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const1804   ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1805                                  ObjPtr<mirror::Reference> ref) const
1806       REQUIRES_SHARED(Locks::mutator_lock_) {
1807     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1808   }
1809 
1810  private:
VisitReference(mirror::Object * ref) const1811   mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1812     if (helper_->TryAssignBinSlot(ref, oat_index_)) {
1813       // Remember how many objects we're adding at the front of the queue as we want
1814       // to reverse that range to process these references in the order of addition.
1815       helper_->work_queue_.emplace_front(ref, oat_index_);
1816     }
1817     if (ClassLinker::kAppImageMayContainStrings &&
1818         helper_->image_writer_->compiler_options_.IsAppImage() &&
1819         helper_->image_writer_->IsInternedAppImageStringReference(ref)) {
1820       helper_->image_writer_->image_infos_[oat_index_].num_string_references_ += 1u;
1821     }
1822     return ref;
1823   }
1824 
1825   LayoutHelper* const helper_;
1826   const size_t oat_index_;
1827 };
1828 
1829 // Visit method pointer arrays in `klass` that were not inherited from its superclass.
1830 template <typename Visitor>
VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass,Visitor && visitor)1831 static void VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass, Visitor&& visitor)
1832     REQUIRES_SHARED(Locks::mutator_lock_) {
1833   ObjPtr<mirror::Class> super = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
1834   ObjPtr<mirror::PointerArray> vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1835   if (vtable != nullptr &&
1836       (super == nullptr || vtable != super->GetVTable<kVerifyNone, kWithoutReadBarrier>())) {
1837     visitor(vtable);
1838   }
1839   int32_t iftable_count = klass->GetIfTableCount();
1840   int32_t super_iftable_count = (super != nullptr) ? super->GetIfTableCount() : 0;
1841   ObjPtr<mirror::IfTable> iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1842   ObjPtr<mirror::IfTable> super_iftable =
1843       (super != nullptr) ? super->GetIfTable<kVerifyNone, kWithoutReadBarrier>() : nullptr;
1844   for (int32_t i = 0; i < iftable_count; ++i) {
1845     ObjPtr<mirror::PointerArray> methods =
1846         iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1847     ObjPtr<mirror::PointerArray> super_methods = (i < super_iftable_count)
1848         ? super_iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i)
1849         : nullptr;
1850     if (methods != super_methods) {
1851       DCHECK(methods != nullptr);
1852       if (i < super_iftable_count) {
1853         DCHECK(super_methods != nullptr);
1854         DCHECK_EQ(methods->GetLength(), super_methods->GetLength());
1855       }
1856       visitor(methods);
1857     }
1858   }
1859 }
1860 
ProcessDexFileObjects(Thread * self)1861 void ImageWriter::LayoutHelper::ProcessDexFileObjects(Thread* self) {
1862   Runtime* runtime = Runtime::Current();
1863   ClassLinker* class_linker = runtime->GetClassLinker();
1864 
1865   // To ensure deterministic output, populate the work queue with objects in a pre-defined order.
1866   // Note: If we decide to implement a profile-guided layout, this is the place to do so.
1867 
1868   // Get initial work queue with the image classes and assign their bin slots.
1869   CollectClassesVisitor visitor(image_writer_);
1870   class_linker->VisitClasses(&visitor);
1871   DCHECK(work_queue_.empty());
1872   work_queue_ = visitor.ProcessCollectedClasses(self);
1873   for (const std::pair<ObjPtr<mirror::Object>, size_t>& entry : work_queue_) {
1874     DCHECK(entry.first != nullptr);
1875     ObjPtr<mirror::Class> klass = entry.first->AsClass();
1876     size_t oat_index = entry.second;
1877     DCHECK(!image_writer_->IsInBootImage(klass.Ptr()));
1878     DCHECK(!image_writer_->IsImageBinSlotAssigned(klass.Ptr()));
1879     image_writer_->RecordNativeRelocations(klass, oat_index);
1880     Bin klass_bin = image_writer_->AssignImageBinSlot(klass.Ptr(), oat_index);
1881     bin_objects_[oat_index][enum_cast<size_t>(klass_bin)].push_back(klass.Ptr());
1882 
1883     auto method_pointer_array_visitor =
1884         [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
1885           Bin bin = kBinObjects ? Bin::kMethodPointerArray : Bin::kRegular;
1886           image_writer_->AssignImageBinSlot(pointer_array.Ptr(), oat_index, bin);
1887           bin_objects_[oat_index][enum_cast<size_t>(bin)].push_back(pointer_array.Ptr());
1888           // No need to add to the work queue. The class reference, if not in the boot image
1889           // (that is, when compiling the primary boot image), is already in the work queue.
1890         };
1891     VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
1892   }
1893 
1894   // Assign bin slots to dex caches.
1895   for (const DexFile* dex_file : image_writer_->compiler_options_.GetDexFilesForOatFile()) {
1896     auto it = image_writer_->dex_file_oat_index_map_.find(dex_file);
1897     DCHECK(it != image_writer_->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1898     const size_t oat_index = it->second;
1899     // Assign bin slot to this file's dex cache and add it to the end of the work queue.
1900     ObjPtr<mirror::DexCache> dex_cache = class_linker->FindDexCache(self, *dex_file);
1901     DCHECK(dex_cache != nullptr);
1902     bool assigned = TryAssignBinSlot(dex_cache, oat_index);
1903     DCHECK(assigned);
1904     work_queue_.emplace_back(dex_cache, oat_index);
1905   }
1906 
1907   // Assign interns to images depending on the first dex file they appear in.
1908   // Record those that do not have a StringId in any dex file.
1909   ProcessInterns(self);
1910 
1911   // Since classes and dex caches have been assigned to their bins, when we process a class
1912   // we do not follow through the class references or dex caches, so we correctly process
1913   // only objects actually belonging to that class before taking a new class from the queue.
1914   // If multiple class statics reference the same object (directly or indirectly), the object
1915   // is treated as belonging to the first encountered referencing class.
1916   ProcessWorkQueue();
1917 }
1918 
ProcessRoots(VariableSizedHandleScope * handles)1919 void ImageWriter::LayoutHelper::ProcessRoots(VariableSizedHandleScope* handles) {
1920   // Assing bin slots to the image objects referenced by `handles`, add them to the work queue
1921   // and process the work queue. These objects are the image roots and boot image live objects
1922   // and they reference other objects needed for the image, for example the array of dex cache
1923   // references, or the pre-allocated exceptions for the boot image.
1924   DCHECK(work_queue_.empty());
1925   CollectRootsVisitor visitor;
1926   handles->VisitRoots(visitor);
1927   for (ObjPtr<mirror::Object> root : visitor.ReleaseRoots()) {
1928     if (TryAssignBinSlot(root, GetDefaultOatIndex())) {
1929       work_queue_.emplace_back(root, GetDefaultOatIndex());
1930     }
1931   }
1932   ProcessWorkQueue();
1933 }
1934 
ProcessInterns(Thread * self)1935 void ImageWriter::LayoutHelper::ProcessInterns(Thread* self) {
1936   // String bins are empty at this point.
1937   DCHECK(std::all_of(bin_objects_.begin(),
1938                      bin_objects_.end(),
1939                      [](const auto& bins) {
1940                        return bins[enum_cast<size_t>(Bin::kString)].empty();
1941                      }));
1942 
1943   // There is only one non-boot image intern table and it's the last one.
1944   InternTable* const intern_table = Runtime::Current()->GetInternTable();
1945   MutexLock mu(self, *Locks::intern_table_lock_);
1946   DCHECK_EQ(std::count_if(intern_table->strong_interns_.tables_.begin(),
1947                           intern_table->strong_interns_.tables_.end(),
1948                           [](const InternTable::Table::InternalTable& table) {
1949                             return !table.IsBootImage();
1950                           }),
1951             1);
1952   DCHECK(!intern_table->strong_interns_.tables_.back().IsBootImage());
1953   const InternTable::UnorderedSet& intern_set = intern_table->strong_interns_.tables_.back().set_;
1954 
1955   // Assign bin slots to all interns with a corresponding StringId in one of the input dex files.
1956   ImageWriter* image_writer = image_writer_;
1957   for (const DexFile* dex_file : image_writer->compiler_options_.GetDexFilesForOatFile()) {
1958     auto it = image_writer->dex_file_oat_index_map_.find(dex_file);
1959     DCHECK(it != image_writer->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1960     const size_t oat_index = it->second;
1961     // Assign bin slots for strings defined in this dex file in StringId (lexicographical) order.
1962     auto& string_bin_objects = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)];
1963     for (size_t i = 0, count = dex_file->NumStringIds(); i != count; ++i) {
1964       uint32_t utf16_length;
1965       const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1966                                                                       &utf16_length);
1967       int32_t hash = ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length);
1968       InternTable::Utf8String utf8_string(utf16_length, utf8_data, hash);
1969       auto intern_it = intern_set.find(utf8_string);
1970       if (intern_it != intern_set.end()) {
1971         mirror::String* string = intern_it->Read<kWithoutReadBarrier>();
1972         DCHECK(string != nullptr);
1973         DCHECK(!image_writer->IsInBootImage(string));
1974         if (!image_writer->IsImageBinSlotAssigned(string)) {
1975           Bin bin = image_writer->AssignImageBinSlot(string, oat_index);
1976           DCHECK_EQ(bin, Bin::kString);
1977           string_bin_objects.push_back(string);
1978         } else {
1979           // We have already seen this string in a previous dex file.
1980           DCHECK(dex_file != image_writer->compiler_options_.GetDexFilesForOatFile().front());
1981         }
1982       }
1983     }
1984   }
1985 
1986   // String bins have been filled with dex file interns. Record their numbers in image infos.
1987   DCHECK_EQ(bin_objects_.size(), image_writer_->image_infos_.size());
1988   size_t total_dex_file_interns = 0u;
1989   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
1990     size_t num_dex_file_interns = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)].size();
1991     ImageInfo& image_info = image_writer_->GetImageInfo(oat_index);
1992     DCHECK_EQ(image_info.intern_table_size_, 0u);
1993     image_info.intern_table_size_ = num_dex_file_interns;
1994     total_dex_file_interns += num_dex_file_interns;
1995   }
1996 
1997   // Collect interns that do not have a corresponding StringId in any of the input dex files.
1998   non_dex_file_interns_.reserve(intern_set.size() - total_dex_file_interns);
1999   for (const GcRoot<mirror::String>& root : intern_set) {
2000     mirror::String* string = root.Read<kWithoutReadBarrier>();
2001     if (!image_writer->IsImageBinSlotAssigned(string)) {
2002       non_dex_file_interns_.push_back(string);
2003     }
2004   }
2005   DCHECK_EQ(intern_set.size(), total_dex_file_interns + non_dex_file_interns_.size());
2006 }
2007 
FinalizeInternTables()2008 void ImageWriter::LayoutHelper::FinalizeInternTables() {
2009   // Remove interns that do not have a bin slot assigned. These correspond
2010   // to the DexCache locations excluded in VerifyImageBinSlotsAssigned().
2011   ImageWriter* image_writer = image_writer_;
2012   auto retained_end = std::remove_if(
2013       non_dex_file_interns_.begin(),
2014       non_dex_file_interns_.end(),
2015       [=](mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
2016         return !image_writer->IsImageBinSlotAssigned(string);
2017       });
2018   non_dex_file_interns_.resize(std::distance(non_dex_file_interns_.begin(), retained_end));
2019 
2020   // Sort `non_dex_file_interns_` based on oat index and bin offset.
2021   ArrayRef<mirror::String*> non_dex_file_interns(non_dex_file_interns_);
2022   std::sort(non_dex_file_interns.begin(),
2023             non_dex_file_interns.end(),
2024             [=](mirror::String* lhs, mirror::String* rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
2025               size_t lhs_oat_index = image_writer->GetOatIndex(lhs);
2026               size_t rhs_oat_index = image_writer->GetOatIndex(rhs);
2027               if (lhs_oat_index != rhs_oat_index) {
2028                 return lhs_oat_index < rhs_oat_index;
2029               }
2030               BinSlot lhs_bin_slot = image_writer->GetImageBinSlot(lhs, lhs_oat_index);
2031               BinSlot rhs_bin_slot = image_writer->GetImageBinSlot(rhs, rhs_oat_index);
2032               return lhs_bin_slot < rhs_bin_slot;
2033             });
2034 
2035   // Allocate and fill intern tables.
2036   size_t ndfi_index = 0u;
2037   DCHECK_EQ(bin_objects_.size(), image_writer->image_infos_.size());
2038   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
2039     // Find the end of `non_dex_file_interns` for this oat file.
2040     size_t ndfi_end = ndfi_index;
2041     while (ndfi_end != non_dex_file_interns.size() &&
2042            image_writer->GetOatIndex(non_dex_file_interns[ndfi_end]) == oat_index) {
2043       ++ndfi_end;
2044     }
2045 
2046     // Calculate final intern table size.
2047     ImageInfo& image_info = image_writer->GetImageInfo(oat_index);
2048     DCHECK_EQ(image_info.intern_table_bytes_, 0u);
2049     size_t num_dex_file_interns = image_info.intern_table_size_;
2050     size_t num_non_dex_file_interns = ndfi_end - ndfi_index;
2051     image_info.intern_table_size_ = num_dex_file_interns + num_non_dex_file_interns;
2052     if (image_info.intern_table_size_ != 0u) {
2053       // Make sure the intern table shall be full by allocating a buffer of the right size.
2054       size_t buffer_size = static_cast<size_t>(
2055           ceil(image_info.intern_table_size_ / kImageInternTableMaxLoadFactor));
2056       image_info.intern_table_buffer_.reset(new GcRoot<mirror::String>[buffer_size]);
2057       DCHECK(image_info.intern_table_buffer_ != nullptr);
2058       image_info.intern_table_.emplace(kImageInternTableMinLoadFactor,
2059                                        kImageInternTableMaxLoadFactor,
2060                                        image_info.intern_table_buffer_.get(),
2061                                        buffer_size);
2062 
2063       // Fill the intern table. Dex file interns are at the start of the bin_objects[.][kString].
2064       InternTable::UnorderedSet& table = *image_info.intern_table_;
2065       const auto& oat_file_strings = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)];
2066       DCHECK_LE(num_dex_file_interns, oat_file_strings.size());
2067       ArrayRef<mirror::Object* const> dex_file_interns(
2068           oat_file_strings.data(), num_dex_file_interns);
2069       for (mirror::Object* string : dex_file_interns) {
2070         bool inserted = table.insert(GcRoot<mirror::String>(string->AsString())).second;
2071         DCHECK(inserted) << "String already inserted: " << string->AsString()->ToModifiedUtf8();
2072       }
2073       ArrayRef<mirror::String*> current_non_dex_file_interns =
2074           non_dex_file_interns.SubArray(ndfi_index, num_non_dex_file_interns);
2075       for (mirror::String* string : current_non_dex_file_interns) {
2076         bool inserted = table.insert(GcRoot<mirror::String>(string)).second;
2077         DCHECK(inserted) << "String already inserted: " << string->ToModifiedUtf8();
2078       }
2079 
2080       // Record the intern table size in bytes.
2081       image_info.intern_table_bytes_ = table.WriteToMemory(nullptr);
2082     }
2083 
2084     ndfi_index = ndfi_end;
2085   }
2086 }
2087 
ProcessWorkQueue()2088 void ImageWriter::LayoutHelper::ProcessWorkQueue() {
2089   while (!work_queue_.empty()) {
2090     std::pair<ObjPtr<mirror::Object>, size_t> pair = work_queue_.front();
2091     work_queue_.pop_front();
2092     VisitReferences(/*obj=*/ pair.first, /*oat_index=*/ pair.second);
2093   }
2094 }
2095 
VerifyImageBinSlotsAssigned()2096 void ImageWriter::LayoutHelper::VerifyImageBinSlotsAssigned() {
2097   std::vector<mirror::Object*> carveout;
2098   if (image_writer_->compiler_options_.IsAppImage()) {
2099     // Exclude boot class path dex caches that are not part of the boot image.
2100     // Also exclude their locations if they have not been visited through another path.
2101     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2102     Thread* self = Thread::Current();
2103     ReaderMutexLock mu(self, *Locks::dex_lock_);
2104     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
2105       ObjPtr<mirror::DexCache> dex_cache =
2106           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
2107       if (dex_cache == nullptr ||
2108           image_writer_->IsInBootImage(dex_cache.Ptr()) ||
2109           ContainsElement(image_writer_->compiler_options_.GetDexFilesForOatFile(),
2110                           dex_cache->GetDexFile())) {
2111         continue;
2112       }
2113       CHECK(!image_writer_->IsImageBinSlotAssigned(dex_cache.Ptr()));
2114       carveout.push_back(dex_cache.Ptr());
2115       ObjPtr<mirror::String> location = dex_cache->GetLocation();
2116       if (!image_writer_->IsImageBinSlotAssigned(location.Ptr())) {
2117         carveout.push_back(location.Ptr());
2118       }
2119     }
2120   }
2121 
2122   std::vector<mirror::Object*> missed_objects;
2123   auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
2124       REQUIRES_SHARED(Locks::mutator_lock_) {
2125     if (!image_writer_->IsInBootImage(obj)) {
2126       if (!UNLIKELY(image_writer_->IsImageBinSlotAssigned(obj))) {
2127         // Ignore the `carveout` objects.
2128         if (ContainsElement(carveout, obj)) {
2129           return;
2130         }
2131         // Ignore finalizer references for the dalvik.system.DexFile objects referenced by
2132         // the app class loader.
2133         if (obj->IsFinalizerReferenceInstance()) {
2134           ArtField* ref_field =
2135               obj->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;");
2136           CHECK(ref_field != nullptr);
2137           ObjPtr<mirror::Object> ref = ref_field->GetObject(obj);
2138           CHECK(ref != nullptr);
2139           CHECK(image_writer_->IsImageBinSlotAssigned(ref.Ptr()));
2140           ObjPtr<mirror::Class> klass = ref->GetClass();
2141           CHECK(klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile));
2142           // Note: The app class loader is used only for checking against the runtime
2143           // class loader, the dex file cookie is cleared and therefore we do not need
2144           // to run the finalizer even if we implement app image objects collection.
2145           ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
2146           CHECK(field->GetObject(ref) == nullptr);
2147           return;
2148         }
2149         if (obj->IsString()) {
2150           // Ignore interned strings. These may come from reflection interning method names.
2151           // TODO: Make dex file strings weak interns and GC them before writing the image.
2152           Runtime* runtime = Runtime::Current();
2153           ObjPtr<mirror::String> interned =
2154               runtime->GetInternTable()->LookupStrong(Thread::Current(), obj->AsString());
2155           if (interned == obj) {
2156             return;
2157           }
2158         }
2159         missed_objects.push_back(obj);
2160       }
2161     }
2162   };
2163   Runtime::Current()->GetHeap()->VisitObjects(ensure_bin_slots_assigned);
2164   if (!missed_objects.empty()) {
2165     const gc::Verification* v = Runtime::Current()->GetHeap()->GetVerification();
2166     size_t num_missed_objects = missed_objects.size();
2167     size_t num_paths = std::min<size_t>(num_missed_objects, 5u);  // Do not flood the output.
2168     ArrayRef<mirror::Object*> missed_objects_head =
2169         ArrayRef<mirror::Object*>(missed_objects).SubArray(/*pos=*/ 0u, /*length=*/ num_paths);
2170     for (mirror::Object* obj : missed_objects_head) {
2171       LOG(ERROR) << "Image object without assigned bin slot: "
2172           << mirror::Object::PrettyTypeOf(obj) << " " << obj
2173           << " " << v->FirstPathFromRootSet(obj);
2174     }
2175     LOG(FATAL) << "Found " << num_missed_objects << " objects without assigned bin slots.";
2176   }
2177 }
2178 
FinalizeBinSlotOffsets()2179 void ImageWriter::LayoutHelper::FinalizeBinSlotOffsets() {
2180   // Calculate bin slot offsets and adjust for region padding if needed.
2181   const size_t region_size = image_writer_->region_size_;
2182   const size_t num_image_infos = image_writer_->image_infos_.size();
2183   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2184     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2185     size_t bin_offset = image_writer_->image_objects_offset_begin_;
2186 
2187     for (size_t i = 0; i != kNumberOfBins; ++i) {
2188       Bin bin = enum_cast<Bin>(i);
2189       switch (bin) {
2190         case Bin::kArtMethodClean:
2191         case Bin::kArtMethodDirty: {
2192           bin_offset = RoundUp(bin_offset, ArtMethod::Alignment(image_writer_->target_ptr_size_));
2193           break;
2194         }
2195         case Bin::kImTable:
2196         case Bin::kIMTConflictTable: {
2197           bin_offset = RoundUp(bin_offset, static_cast<size_t>(image_writer_->target_ptr_size_));
2198           break;
2199         }
2200         default: {
2201           // Normal alignment.
2202         }
2203       }
2204       image_info.bin_slot_offsets_[i] = bin_offset;
2205 
2206       // If the bin is for mirror objects, we may need to add region padding and update offsets.
2207       if (i < enum_cast<size_t>(Bin::kMirrorCount) && region_size != 0u) {
2208         const size_t offset_after_header = bin_offset - sizeof(ImageHeader);
2209         size_t remaining_space =
2210             RoundUp(offset_after_header + 1u, region_size) - offset_after_header;
2211         // Exercise the loop below in debug builds to get coverage.
2212         if (kIsDebugBuild || remaining_space < image_info.bin_slot_sizes_[i]) {
2213           // The bin crosses a region boundary. Add padding if needed.
2214           size_t object_offset = 0u;
2215           size_t padding = 0u;
2216           for (mirror::Object* object : bin_objects_[oat_index][i]) {
2217             BinSlot bin_slot = image_writer_->GetImageBinSlot(object, oat_index);
2218             DCHECK_EQ(enum_cast<size_t>(bin_slot.GetBin()), i);
2219             DCHECK_EQ(bin_slot.GetOffset() + padding, object_offset);
2220             size_t object_size = RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
2221 
2222             auto add_padding = [&](bool tail_region) {
2223               DCHECK_NE(remaining_space, 0u);
2224               DCHECK_LT(remaining_space, region_size);
2225               DCHECK_ALIGNED(remaining_space, kObjectAlignment);
2226               // TODO When copying to heap regions, leave the tail region padding zero-filled.
2227               if (!tail_region || true) {
2228                 image_info.padding_offsets_.push_back(bin_offset + object_offset);
2229               }
2230               image_info.bin_slot_sizes_[i] += remaining_space;
2231               padding += remaining_space;
2232               object_offset += remaining_space;
2233               remaining_space = region_size;
2234             };
2235             if (object_size > remaining_space) {
2236               // Padding needed if we're not at region boundary (with a multi-region object).
2237               if (remaining_space != region_size) {
2238                 // TODO: Instead of adding padding, we should consider reordering the bins
2239                 // or objects to reduce wasted space.
2240                 add_padding(/*tail_region=*/ false);
2241               }
2242               DCHECK_EQ(remaining_space, region_size);
2243               // For huge objects, adjust the remaining space to hold the object and some more.
2244               if (object_size > region_size) {
2245                 remaining_space = RoundUp(object_size + 1u, region_size);
2246               }
2247             } else if (remaining_space == object_size) {
2248               // Move to the next region, no padding needed.
2249               remaining_space += region_size;
2250             }
2251             DCHECK_GT(remaining_space, object_size);
2252             remaining_space -= object_size;
2253             image_writer_->UpdateImageBinSlotOffset(object, oat_index, object_offset);
2254             object_offset += object_size;
2255             // Add padding to the tail region of huge objects if not region-aligned.
2256             if (object_size > region_size && remaining_space != region_size) {
2257               DCHECK(!IsAlignedParam(object_size, region_size));
2258               add_padding(/*tail_region=*/ true);
2259             }
2260           }
2261           image_writer_->region_alignment_wasted_ += padding;
2262           image_info.image_end_ += padding;
2263         }
2264       }
2265       bin_offset += image_info.bin_slot_sizes_[i];
2266     }
2267     // NOTE: There may be additional padding between the bin slots and the intern table.
2268     DCHECK_EQ(
2269         image_info.image_end_,
2270         image_info.GetBinSizeSum(Bin::kMirrorCount) + image_writer_->image_objects_offset_begin_);
2271   }
2272 
2273   VLOG(image) << "Space wasted for region alignment " << image_writer_->region_alignment_wasted_;
2274 }
2275 
CollectStringReferenceInfo()2276 void ImageWriter::LayoutHelper::CollectStringReferenceInfo() {
2277   size_t total_string_refs = 0u;
2278 
2279   const size_t num_image_infos = image_writer_->image_infos_.size();
2280   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2281     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2282     DCHECK(image_info.string_reference_offsets_.empty());
2283     image_info.string_reference_offsets_.reserve(image_info.num_string_references_);
2284 
2285     for (size_t i = 0; i < enum_cast<size_t>(Bin::kMirrorCount); ++i) {
2286       for (mirror::Object* obj : bin_objects_[oat_index][i]) {
2287         CollectStringReferenceVisitor visitor(image_writer_,
2288                                               oat_index,
2289                                               &image_info.string_reference_offsets_,
2290                                               obj);
2291         /*
2292          * References to managed strings can occur either in the managed heap or in
2293          * native memory regions. Information about managed references is collected
2294          * by the CollectStringReferenceVisitor and directly added to the image info.
2295          *
2296          * Native references to managed strings can only occur through DexCache
2297          * objects. This is verified by the visitor in debug mode and the references
2298          * are collected separately below.
2299          */
2300         obj->VisitReferences</*kVisitNativeRoots=*/ kIsDebugBuild,
2301                              kVerifyNone,
2302                              kWithoutReadBarrier>(visitor, visitor);
2303       }
2304     }
2305 
2306     total_string_refs += image_info.string_reference_offsets_.size();
2307 
2308     // Check that we collected the same number of string references as we saw in the previous pass.
2309     CHECK_EQ(image_info.string_reference_offsets_.size(), image_info.num_string_references_);
2310   }
2311 
2312   VLOG(compiler) << "Dex2Oat:AppImage:stringReferences = " << total_string_refs;
2313 }
2314 
VisitReferences(ObjPtr<mirror::Object> obj,size_t oat_index)2315 void ImageWriter::LayoutHelper::VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index) {
2316   size_t old_work_queue_size = work_queue_.size();
2317   VisitReferencesVisitor visitor(this, oat_index);
2318   // Walk references and assign bin slots for them.
2319   obj->VisitReferences</*kVisitNativeRoots=*/ true, kVerifyNone, kWithoutReadBarrier>(
2320       visitor,
2321       visitor);
2322   // Put the added references in the queue in the order in which they were added.
2323   // The visitor just pushes them to the front as it visits them.
2324   DCHECK_LE(old_work_queue_size, work_queue_.size());
2325   size_t num_added = work_queue_.size() - old_work_queue_size;
2326   std::reverse(work_queue_.begin(), work_queue_.begin() + num_added);
2327 }
2328 
TryAssignBinSlot(ObjPtr<mirror::Object> obj,size_t oat_index)2329 bool ImageWriter::LayoutHelper::TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index) {
2330   if (obj == nullptr || image_writer_->IsInBootImage(obj.Ptr())) {
2331     // Object is null or already in the image, there is no work to do.
2332     return false;
2333   }
2334   bool assigned = false;
2335   if (!image_writer_->IsImageBinSlotAssigned(obj.Ptr())) {
2336     Bin bin = image_writer_->AssignImageBinSlot(obj.Ptr(), oat_index);
2337     bin_objects_[oat_index][enum_cast<size_t>(bin)].push_back(obj.Ptr());
2338     assigned = true;
2339   }
2340   return assigned;
2341 }
2342 
GetBootImageLiveObjects()2343 static ObjPtr<ObjectArray<Object>> GetBootImageLiveObjects() REQUIRES_SHARED(Locks::mutator_lock_) {
2344   gc::Heap* heap = Runtime::Current()->GetHeap();
2345   DCHECK(!heap->GetBootImageSpaces().empty());
2346   const ImageHeader& primary_header = heap->GetBootImageSpaces().front()->GetImageHeader();
2347   return ObjPtr<ObjectArray<Object>>::DownCast(
2348       primary_header.GetImageRoot<kWithReadBarrier>(ImageHeader::kBootImageLiveObjects));
2349 }
2350 
CalculateNewObjectOffsets()2351 void ImageWriter::CalculateNewObjectOffsets() {
2352   Thread* const self = Thread::Current();
2353   Runtime* const runtime = Runtime::Current();
2354   VariableSizedHandleScope handles(self);
2355   MutableHandle<ObjectArray<Object>> boot_image_live_objects = handles.NewHandle(
2356       compiler_options_.IsBootImage()
2357           ? AllocateBootImageLiveObjects(self, runtime)
2358           : (compiler_options_.IsBootImageExtension() ? GetBootImageLiveObjects() : nullptr));
2359   std::vector<Handle<ObjectArray<Object>>> image_roots;
2360   for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2361     image_roots.push_back(handles.NewHandle(CreateImageRoots(i, boot_image_live_objects)));
2362   }
2363 
2364   gc::Heap* const heap = runtime->GetHeap();
2365 
2366   // Leave space for the header, but do not write it yet, we need to
2367   // know where image_roots is going to end up
2368   image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);  // 64-bit-alignment
2369 
2370   // Write the image runtime methods.
2371   image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
2372   image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
2373   image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
2374   image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
2375       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
2376   image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
2377       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
2378   image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
2379       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
2380   image_methods_[ImageHeader::kSaveEverythingMethod] =
2381       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
2382   image_methods_[ImageHeader::kSaveEverythingMethodForClinit] =
2383       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit);
2384   image_methods_[ImageHeader::kSaveEverythingMethodForSuspendCheck] =
2385       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck);
2386   // Visit image methods first to have the main runtime methods in the first image.
2387   for (auto* m : image_methods_) {
2388     CHECK(m != nullptr);
2389     CHECK(m->IsRuntimeMethod());
2390     DCHECK_EQ(!compiler_options_.IsBootImage(), IsInBootImage(m))
2391         << "Trampolines should be in boot image";
2392     if (!IsInBootImage(m)) {
2393       AssignMethodOffset(m, NativeObjectRelocationType::kRuntimeMethod, GetDefaultOatIndex());
2394     }
2395   }
2396 
2397   // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
2398   // this lock while holding other locks may cause lock order violations.
2399   {
2400     auto deflate_monitor = [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2401       Monitor::Deflate(Thread::Current(), obj);
2402     };
2403     heap->VisitObjects(deflate_monitor);
2404   }
2405 
2406   // From this point on, there shall be no GC anymore and no objects shall be allocated.
2407   // We can now assign a BitSlot to each object and store it in its lockword.
2408 
2409   LayoutHelper layout_helper(this);
2410   layout_helper.ProcessDexFileObjects(self);
2411   layout_helper.ProcessRoots(&handles);
2412   layout_helper.FinalizeInternTables();
2413 
2414   // Verify that all objects have assigned image bin slots.
2415   layout_helper.VerifyImageBinSlotsAssigned();
2416 
2417   // Finalize bin slot offsets. This may add padding for regions.
2418   layout_helper.FinalizeBinSlotOffsets();
2419 
2420   // Collect string reference info for app images.
2421   if (ClassLinker::kAppImageMayContainStrings && compiler_options_.IsAppImage()) {
2422     layout_helper.CollectStringReferenceInfo();
2423   }
2424 
2425   // Calculate image offsets.
2426   size_t image_offset = 0;
2427   for (ImageInfo& image_info : image_infos_) {
2428     image_info.image_begin_ = global_image_begin_ + image_offset;
2429     image_info.image_offset_ = image_offset;
2430     image_info.image_size_ = RoundUp(image_info.CreateImageSections().first, kPageSize);
2431     // There should be no gaps until the next image.
2432     image_offset += image_info.image_size_;
2433   }
2434 
2435   size_t i = 0;
2436   for (ImageInfo& image_info : image_infos_) {
2437     image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
2438     i++;
2439   }
2440 
2441   // Update the native relocations by adding their bin sums.
2442   for (auto& pair : native_object_relocations_) {
2443     NativeObjectRelocation& relocation = pair.second;
2444     Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
2445     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2446     relocation.offset += image_info.GetBinSlotOffset(bin_type);
2447   }
2448 
2449   // Remember the boot image live objects as raw pointer. No GC can happen anymore.
2450   boot_image_live_objects_ = boot_image_live_objects.Get();
2451 }
2452 
CreateImageSections() const2453 std::pair<size_t, std::vector<ImageSection>> ImageWriter::ImageInfo::CreateImageSections() const {
2454   std::vector<ImageSection> sections(ImageHeader::kSectionCount);
2455 
2456   // Do not round up any sections here that are represented by the bins since it
2457   // will break offsets.
2458 
2459   /*
2460    * Objects section
2461    */
2462   sections[ImageHeader::kSectionObjects] =
2463       ImageSection(0u, image_end_);
2464 
2465   /*
2466    * Field section
2467    */
2468   sections[ImageHeader::kSectionArtFields] =
2469       ImageSection(GetBinSlotOffset(Bin::kArtField), GetBinSlotSize(Bin::kArtField));
2470 
2471   /*
2472    * Method section
2473    */
2474   sections[ImageHeader::kSectionArtMethods] =
2475       ImageSection(GetBinSlotOffset(Bin::kArtMethodClean),
2476                    GetBinSlotSize(Bin::kArtMethodClean) +
2477                    GetBinSlotSize(Bin::kArtMethodDirty));
2478 
2479   /*
2480    * IMT section
2481    */
2482   sections[ImageHeader::kSectionImTables] =
2483       ImageSection(GetBinSlotOffset(Bin::kImTable), GetBinSlotSize(Bin::kImTable));
2484 
2485   /*
2486    * Conflict Tables section
2487    */
2488   sections[ImageHeader::kSectionIMTConflictTables] =
2489       ImageSection(GetBinSlotOffset(Bin::kIMTConflictTable), GetBinSlotSize(Bin::kIMTConflictTable));
2490 
2491   /*
2492    * Runtime Methods section
2493    */
2494   sections[ImageHeader::kSectionRuntimeMethods] =
2495       ImageSection(GetBinSlotOffset(Bin::kRuntimeMethod), GetBinSlotSize(Bin::kRuntimeMethod));
2496 
2497   /*
2498    * Interned Strings section
2499    */
2500 
2501   // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
2502   size_t cur_pos = RoundUp(sections[ImageHeader::kSectionRuntimeMethods].End(), sizeof(uint64_t));
2503 
2504   const ImageSection& interned_strings_section =
2505       sections[ImageHeader::kSectionInternedStrings] =
2506           ImageSection(cur_pos, intern_table_bytes_);
2507 
2508   /*
2509    * Class Table section
2510    */
2511 
2512   // Obtain the new position and round it up to the appropriate alignment.
2513   cur_pos = RoundUp(interned_strings_section.End(), sizeof(uint64_t));
2514 
2515   const ImageSection& class_table_section =
2516       sections[ImageHeader::kSectionClassTable] =
2517           ImageSection(cur_pos, class_table_bytes_);
2518 
2519   /*
2520    * String Field Offsets section
2521    */
2522 
2523   // Round up to the alignment of the offsets we are going to store.
2524   cur_pos = RoundUp(class_table_section.End(), sizeof(uint32_t));
2525 
2526   // The size of string_reference_offsets_ can't be used here because it hasn't
2527   // been filled with AppImageReferenceOffsetInfo objects yet.  The
2528   // num_string_references_ value is calculated separately, before we can
2529   // compute the actual offsets.
2530   const ImageSection& string_reference_offsets =
2531       sections[ImageHeader::kSectionStringReferenceOffsets] =
2532           ImageSection(cur_pos, sizeof(string_reference_offsets_[0]) * num_string_references_);
2533 
2534   /*
2535    * Metadata section.
2536    */
2537 
2538   // Round up to the alignment of the offsets we are going to store.
2539   cur_pos = RoundUp(string_reference_offsets.End(), sizeof(uint32_t));
2540 
2541   const ImageSection& metadata_section =
2542       sections[ImageHeader::kSectionMetadata] =
2543           ImageSection(cur_pos, GetBinSlotSize(Bin::kMetadata));
2544 
2545   // Return the number of bytes described by these sections, and the sections
2546   // themselves.
2547   return make_pair(metadata_section.End(), std::move(sections));
2548 }
2549 
CreateHeader(size_t oat_index,size_t component_count)2550 void ImageWriter::CreateHeader(size_t oat_index, size_t component_count) {
2551   ImageInfo& image_info = GetImageInfo(oat_index);
2552   const uint8_t* oat_file_begin = image_info.oat_file_begin_;
2553   const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
2554   const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
2555 
2556   uint32_t image_reservation_size = image_info.image_size_;
2557   DCHECK_ALIGNED(image_reservation_size, kPageSize);
2558   uint32_t current_component_count = 1u;
2559   if (compiler_options_.IsAppImage()) {
2560     DCHECK_EQ(oat_index, 0u);
2561     DCHECK_EQ(component_count, current_component_count);
2562   } else {
2563     DCHECK(image_infos_.size() == 1u || image_infos_.size() == component_count)
2564         << image_infos_.size() << " " << component_count;
2565     if (oat_index == 0u) {
2566       const ImageInfo& last_info = image_infos_.back();
2567       const uint8_t* end = last_info.oat_file_begin_ + last_info.oat_loaded_size_;
2568       DCHECK_ALIGNED(image_info.image_begin_, kPageSize);
2569       image_reservation_size =
2570           dchecked_integral_cast<uint32_t>(RoundUp(end - image_info.image_begin_, kPageSize));
2571       current_component_count = component_count;
2572     } else {
2573       image_reservation_size = 0u;
2574       current_component_count = 0u;
2575     }
2576   }
2577 
2578   // Compute boot image checksums for the primary component, leave as 0 otherwise.
2579   uint32_t boot_image_components = 0u;
2580   uint32_t boot_image_checksums = 0u;
2581   if (oat_index == 0u) {
2582     const std::vector<gc::space::ImageSpace*>& image_spaces =
2583         Runtime::Current()->GetHeap()->GetBootImageSpaces();
2584     DCHECK_EQ(image_spaces.empty(), compiler_options_.IsBootImage());
2585     for (size_t i = 0u, size = image_spaces.size(); i != size; ) {
2586       const ImageHeader& header = image_spaces[i]->GetImageHeader();
2587       boot_image_components += header.GetComponentCount();
2588       boot_image_checksums ^= header.GetImageChecksum();
2589       DCHECK_LE(header.GetImageSpaceCount(), size - i);
2590       i += header.GetImageSpaceCount();
2591     }
2592   }
2593 
2594   // Create the image sections.
2595   auto section_info_pair = image_info.CreateImageSections();
2596   const size_t image_end = section_info_pair.first;
2597   std::vector<ImageSection>& sections = section_info_pair.second;
2598 
2599   // Finally bitmap section.
2600   const size_t bitmap_bytes = image_info.image_bitmap_.Size();
2601   auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
2602   *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
2603   if (VLOG_IS_ON(compiler)) {
2604     LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
2605     size_t idx = 0;
2606     for (const ImageSection& section : sections) {
2607       LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
2608       ++idx;
2609     }
2610     LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
2611     LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
2612     LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
2613               << " Image offset=" << image_info.image_offset_ << std::dec;
2614     LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
2615               << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
2616               << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
2617               << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
2618   }
2619 
2620   // Create the header, leave 0 for data size since we will fill this in as we are writing the
2621   // image.
2622   new (image_info.image_.Begin()) ImageHeader(
2623       image_reservation_size,
2624       current_component_count,
2625       PointerToLowMemUInt32(image_info.image_begin_),
2626       image_end,
2627       sections.data(),
2628       image_info.image_roots_address_,
2629       image_info.oat_checksum_,
2630       PointerToLowMemUInt32(oat_file_begin),
2631       PointerToLowMemUInt32(image_info.oat_data_begin_),
2632       PointerToLowMemUInt32(oat_data_end),
2633       PointerToLowMemUInt32(oat_file_end),
2634       boot_image_begin_,
2635       boot_image_size_,
2636       boot_image_components,
2637       boot_image_checksums,
2638       static_cast<uint32_t>(target_ptr_size_));
2639 }
2640 
GetImageMethodAddress(ArtMethod * method)2641 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
2642   NativeObjectRelocation relocation = GetNativeRelocation(method);
2643   const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2644   CHECK_GE(relocation.offset, image_info.image_end_) << "ArtMethods should be after Objects";
2645   return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + relocation.offset);
2646 }
2647 
GetIntrinsicReferenceAddress(uint32_t intrinsic_data)2648 const void* ImageWriter::GetIntrinsicReferenceAddress(uint32_t intrinsic_data) {
2649   DCHECK(compiler_options_.IsBootImage());
2650   switch (IntrinsicObjects::DecodePatchType(intrinsic_data)) {
2651     case IntrinsicObjects::PatchType::kIntegerValueOfArray: {
2652       const uint8_t* base_address =
2653           reinterpret_cast<const uint8_t*>(GetImageAddress(boot_image_live_objects_));
2654       MemberOffset data_offset =
2655           IntrinsicObjects::GetIntegerValueOfArrayDataOffset(boot_image_live_objects_);
2656       return base_address + data_offset.Uint32Value();
2657     }
2658     case IntrinsicObjects::PatchType::kIntegerValueOfObject: {
2659       uint32_t index = IntrinsicObjects::DecodePatchIndex(intrinsic_data);
2660       ObjPtr<mirror::Object> value =
2661           IntrinsicObjects::GetIntegerValueOfObject(boot_image_live_objects_, index);
2662       return GetImageAddress(value.Ptr());
2663     }
2664   }
2665   LOG(FATAL) << "UNREACHABLE";
2666   UNREACHABLE();
2667 }
2668 
2669 
2670 class ImageWriter::FixupRootVisitor : public RootVisitor {
2671  public:
FixupRootVisitor(ImageWriter * image_writer)2672   explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
2673   }
2674 
VisitRoots(mirror::Object *** roots ATTRIBUTE_UNUSED,size_t count ATTRIBUTE_UNUSED,const RootInfo & info ATTRIBUTE_UNUSED)2675   void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
2676                   size_t count ATTRIBUTE_UNUSED,
2677                   const RootInfo& info ATTRIBUTE_UNUSED)
2678       override REQUIRES_SHARED(Locks::mutator_lock_) {
2679     LOG(FATAL) << "Unsupported";
2680   }
2681 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)2682   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
2683                   size_t count,
2684                   const RootInfo& info ATTRIBUTE_UNUSED)
2685       override REQUIRES_SHARED(Locks::mutator_lock_) {
2686     for (size_t i = 0; i < count; ++i) {
2687       // Copy the reference. Since we do not have the address for recording the relocation,
2688       // it needs to be recorded explicitly by the user of FixupRootVisitor.
2689       ObjPtr<mirror::Object> old_ptr = roots[i]->AsMirrorPtr();
2690       roots[i]->Assign(image_writer_->GetImageAddress(old_ptr.Ptr()));
2691     }
2692   }
2693 
2694  private:
2695   ImageWriter* const image_writer_;
2696 };
2697 
CopyAndFixupImTable(ImTable * orig,ImTable * copy)2698 void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2699   for (size_t i = 0; i < ImTable::kSize; ++i) {
2700     ArtMethod* method = orig->Get(i, target_ptr_size_);
2701     void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2702     CopyAndFixupPointer(address, method);
2703     DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
2704   }
2705 }
2706 
CopyAndFixupImtConflictTable(ImtConflictTable * orig,ImtConflictTable * copy)2707 void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2708   const size_t count = orig->NumEntries(target_ptr_size_);
2709   for (size_t i = 0; i < count; ++i) {
2710     ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2711     ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
2712     CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2713     CopyAndFixupPointer(
2714         copy->AddressOfImplementationMethod(i, target_ptr_size_), implementation_method);
2715     DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2716               NativeLocationInImage(interface_method));
2717     DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2718               NativeLocationInImage(implementation_method));
2719   }
2720 }
2721 
CopyAndFixupNativeData(size_t oat_index)2722 void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
2723   const ImageInfo& image_info = GetImageInfo(oat_index);
2724   // Copy ArtFields and methods to their locations and update the array for convenience.
2725   for (auto& pair : native_object_relocations_) {
2726     NativeObjectRelocation& relocation = pair.second;
2727     // Only work with fields and methods that are in the current oat file.
2728     if (relocation.oat_index != oat_index) {
2729       continue;
2730     }
2731     auto* dest = image_info.image_.Begin() + relocation.offset;
2732     DCHECK_GE(dest, image_info.image_.Begin() + image_info.image_end_);
2733     DCHECK(!IsInBootImage(pair.first));
2734     switch (relocation.type) {
2735       case NativeObjectRelocationType::kRuntimeMethod:
2736       case NativeObjectRelocationType::kArtMethodClean:
2737       case NativeObjectRelocationType::kArtMethodDirty: {
2738         CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
2739                            reinterpret_cast<ArtMethod*>(dest),
2740                            oat_index);
2741         break;
2742       }
2743       case NativeObjectRelocationType::kArtFieldArray: {
2744         // Copy and fix up the entire field array.
2745         auto* src_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(pair.first);
2746         auto* dest_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(dest);
2747         size_t size = src_array->size();
2748         memcpy(dest_array, src_array, LengthPrefixedArray<ArtField>::ComputeSize(size));
2749         for (size_t i = 0; i != size; ++i) {
2750           CopyAndFixupReference(
2751               dest_array->At(i).GetDeclaringClassAddressWithoutBarrier(),
2752               src_array->At(i).GetDeclaringClass());
2753         }
2754         break;
2755       }
2756       case NativeObjectRelocationType::kArtMethodArrayClean:
2757       case NativeObjectRelocationType::kArtMethodArrayDirty: {
2758         // For method arrays, copy just the header since the elements will
2759         // get copied by their corresponding relocations.
2760         size_t size = ArtMethod::Size(target_ptr_size_);
2761         size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2762         memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2763         // Clear padding to avoid non-deterministic data in the image.
2764         // Historical note: We also did that to placate Valgrind.
2765         reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
2766         break;
2767       }
2768       case NativeObjectRelocationType::kIMTable: {
2769         ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
2770         ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
2771         CopyAndFixupImTable(orig_imt, dest_imt);
2772         break;
2773       }
2774       case NativeObjectRelocationType::kIMTConflictTable: {
2775         auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
2776         CopyAndFixupImtConflictTable(
2777             orig_table,
2778             new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
2779         break;
2780       }
2781       case NativeObjectRelocationType::kGcRootPointer: {
2782         auto* orig_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(pair.first);
2783         auto* dest_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(dest);
2784         CopyAndFixupReference(dest_pointer->AddressWithoutBarrier(), orig_pointer->Read());
2785         break;
2786       }
2787     }
2788   }
2789   // Fixup the image method roots.
2790   auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
2791   for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
2792     ArtMethod* method = image_methods_[i];
2793     CHECK(method != nullptr);
2794     CopyAndFixupPointer(
2795         reinterpret_cast<void**>(&image_header->image_methods_[i]), method, PointerSize::k32);
2796   }
2797   FixupRootVisitor root_visitor(this);
2798 
2799   // Write the intern table into the image.
2800   if (image_info.intern_table_bytes_ > 0) {
2801     const ImageSection& intern_table_section = image_header->GetInternedStringsSection();
2802     DCHECK(image_info.intern_table_.has_value());
2803     const InternTable::UnorderedSet& intern_table = *image_info.intern_table_;
2804     uint8_t* const intern_table_memory_ptr =
2805         image_info.image_.Begin() + intern_table_section.Offset();
2806     const size_t intern_table_bytes = intern_table.WriteToMemory(intern_table_memory_ptr);
2807     CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
2808     // Fixup the pointers in the newly written intern table to contain image addresses.
2809     InternTable temp_intern_table;
2810     // Note that we require that ReadFromMemory does not make an internal copy of the elements so
2811     // that the VisitRoots() will update the memory directly rather than the copies.
2812     // This also relies on visit roots not doing any verification which could fail after we update
2813     // the roots to be the image addresses.
2814     temp_intern_table.AddTableFromMemory(intern_table_memory_ptr,
2815                                          VoidFunctor(),
2816                                          /*is_boot_image=*/ false);
2817     CHECK_EQ(temp_intern_table.Size(), intern_table.size());
2818     temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2819 
2820     if (kIsDebugBuild) {
2821       MutexLock lock(Thread::Current(), *Locks::intern_table_lock_);
2822       CHECK(!temp_intern_table.strong_interns_.tables_.empty());
2823       // The UnorderedSet was inserted at the beginning.
2824       CHECK_EQ(temp_intern_table.strong_interns_.tables_[0].Size(), intern_table.size());
2825     }
2826   }
2827 
2828   // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2829   // class loaders. Writing multiple class tables into the image is currently unsupported.
2830   if (image_info.class_table_bytes_ > 0u) {
2831     const ImageSection& class_table_section = image_header->GetClassTableSection();
2832     uint8_t* const class_table_memory_ptr =
2833         image_info.image_.Begin() + class_table_section.Offset();
2834 
2835     DCHECK(image_info.class_table_.has_value());
2836     const ClassTable::ClassSet& table = *image_info.class_table_;
2837     CHECK_EQ(table.size(), image_info.class_table_size_);
2838     const size_t class_table_bytes = table.WriteToMemory(class_table_memory_ptr);
2839     CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2840 
2841     // Fixup the pointers in the newly written class table to contain image addresses. See
2842     // above comment for intern tables.
2843     ClassTable temp_class_table;
2844     temp_class_table.ReadFromMemory(class_table_memory_ptr);
2845     CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(), table.size());
2846     UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2847     temp_class_table.VisitRoots(visitor);
2848 
2849     if (kIsDebugBuild) {
2850       ReaderMutexLock lock(Thread::Current(), temp_class_table.lock_);
2851       CHECK(!temp_class_table.classes_.empty());
2852       // The ClassSet was inserted at the beginning.
2853       CHECK_EQ(temp_class_table.classes_[0].size(), table.size());
2854     }
2855   }
2856 }
2857 
CopyAndFixupMethodPointerArray(mirror::PointerArray * arr)2858 void ImageWriter::CopyAndFixupMethodPointerArray(mirror::PointerArray* arr) {
2859   // Pointer arrays are processed early and each is visited just once.
2860   // Therefore we know that this array has not been copied yet.
2861   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ false>(arr);
2862   DCHECK(dst != nullptr);
2863   DCHECK(arr->IsIntArray() || arr->IsLongArray()) << arr->GetClass()->PrettyClass() << " " << arr;
2864   // Fixup int and long pointers for the ArtMethod or ArtField arrays.
2865   const size_t num_elements = arr->GetLength();
2866   CopyAndFixupReference(
2867       dst->GetFieldObjectReferenceAddr<kVerifyNone>(Class::ClassOffset()), arr->GetClass());
2868   auto* dest_array = down_cast<mirror::PointerArray*>(dst);
2869   for (size_t i = 0, count = num_elements; i < count; ++i) {
2870     void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
2871     if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
2872       auto it = native_object_relocations_.find(elem);
2873       if (UNLIKELY(it == native_object_relocations_.end())) {
2874         auto* method = reinterpret_cast<ArtMethod*>(elem);
2875         LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2876                    << method << " idx=" << i << "/" << num_elements << " with declaring class "
2877                    << Class::PrettyClass(method->GetDeclaringClass());
2878         UNREACHABLE();
2879       }
2880     }
2881     CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
2882   }
2883 }
2884 
CopyAndFixupObject(Object * obj)2885 void ImageWriter::CopyAndFixupObject(Object* obj) {
2886   if (!IsImageBinSlotAssigned(obj)) {
2887     return;
2888   }
2889   // Some objects (such as method pointer arrays) may have been processed before.
2890   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ true>(obj);
2891   if (dst != nullptr) {
2892     FixupObject(obj, dst);
2893   }
2894 }
2895 
2896 template <bool kCheckIfDone>
CopyObject(Object * obj)2897 inline Object* ImageWriter::CopyObject(Object* obj) {
2898   size_t oat_index = GetOatIndex(obj);
2899   size_t offset = GetImageOffset(obj, oat_index);
2900   ImageInfo& image_info = GetImageInfo(oat_index);
2901   auto* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + offset);
2902   DCHECK_LT(offset, image_info.image_end_);
2903   const auto* src = reinterpret_cast<const uint8_t*>(obj);
2904 
2905   bool done = image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
2906   // Check if the object was already copied, unless the caller indicated that it was not.
2907   if (kCheckIfDone && done) {
2908     return nullptr;
2909   }
2910   DCHECK(!done);
2911 
2912   const size_t n = obj->SizeOf();
2913 
2914   if (kIsDebugBuild && region_size_ != 0u) {
2915     const size_t offset_after_header = offset - sizeof(ImageHeader);
2916     const size_t next_region = RoundUp(offset_after_header, region_size_);
2917     if (offset_after_header != next_region) {
2918       // If the object is not on a region bondary, it must not be cross region.
2919       CHECK_LT(offset_after_header, next_region)
2920           << "offset_after_header=" << offset_after_header << " size=" << n;
2921       CHECK_LE(offset_after_header + n, next_region)
2922           << "offset_after_header=" << offset_after_header << " size=" << n;
2923     }
2924   }
2925   DCHECK_LE(offset + n, image_info.image_.Size());
2926   memcpy(dst, src, n);
2927 
2928   // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2929   // word.
2930   const auto it = saved_hashcode_map_.find(obj);
2931   dst->SetLockWord(it != saved_hashcode_map_.end() ?
2932       LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
2933   if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2934     // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2935     // safe since we mark all of the objects that may reference non immune objects as gray.
2936     CHECK(dst->AtomicSetMarkBit(0, 1));
2937   }
2938   return dst;
2939 }
2940 
2941 // Rewrite all the references in the copied object to point to their image address equivalent
2942 class ImageWriter::FixupVisitor {
2943  public:
FixupVisitor(ImageWriter * image_writer,Object * copy)2944   FixupVisitor(ImageWriter* image_writer, Object* copy)
2945       : image_writer_(image_writer), copy_(copy) {
2946   }
2947 
2948   // Ignore class roots since we don't have a way to map them to the destination. These are handled
2949   // with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const2950   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2951       const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const2952   void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2953 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const2954   void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
2955       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
2956     ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
2957     // Copy the reference and record the fixup if necessary.
2958     image_writer_->CopyAndFixupReference(
2959         copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset), ref);
2960   }
2961 
2962   // java.lang.ref.Reference visitor.
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const2963   void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2964                   ObjPtr<mirror::Reference> ref) const
2965       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
2966     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
2967   }
2968 
2969  protected:
2970   ImageWriter* const image_writer_;
2971   mirror::Object* const copy_;
2972 };
2973 
CopyAndFixupObjects()2974 void ImageWriter::CopyAndFixupObjects() {
2975   // Copy and fix up pointer arrays first as they require special treatment.
2976   auto method_pointer_array_visitor =
2977       [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
2978         CopyAndFixupMethodPointerArray(pointer_array.Ptr());
2979       };
2980   for (ImageInfo& image_info : image_infos_) {
2981     if (image_info.class_table_size_ != 0u) {
2982       DCHECK(image_info.class_table_.has_value());
2983       for (const ClassTable::TableSlot slot : *image_info.class_table_) {
2984         ObjPtr<mirror::Class> klass = slot.Read<kWithoutReadBarrier>();
2985         DCHECK(klass != nullptr);
2986         // Do not process boot image classes present in app image class table.
2987         DCHECK(!IsInBootImage(klass.Ptr()) || compiler_options_.IsAppImage());
2988         if (!IsInBootImage(klass.Ptr())) {
2989           // Do not fix up method pointer arrays inherited from superclass. If they are part
2990           // of the current image, they were or shall be copied when visiting the superclass.
2991           VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
2992         }
2993       }
2994     }
2995   }
2996 
2997   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2998     DCHECK(obj != nullptr);
2999     CopyAndFixupObject(obj);
3000   };
3001   Runtime::Current()->GetHeap()->VisitObjects(visitor);
3002 
3003   // Fill the padding objects since they are required for in order traversal of the image space.
3004   for (ImageInfo& image_info : image_infos_) {
3005     for (const size_t start_offset : image_info.padding_offsets_) {
3006       const size_t offset_after_header = start_offset - sizeof(ImageHeader);
3007       size_t remaining_space =
3008           RoundUp(offset_after_header + 1u, region_size_) - offset_after_header;
3009       DCHECK_NE(remaining_space, 0u);
3010       DCHECK_LT(remaining_space, region_size_);
3011       Object* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + start_offset);
3012       ObjPtr<Class> object_class = GetClassRoot<mirror::Object, kWithoutReadBarrier>();
3013       DCHECK_ALIGNED_PARAM(remaining_space, object_class->GetObjectSize());
3014       Object* end = dst + remaining_space / object_class->GetObjectSize();
3015       Class* image_object_class = GetImageAddress(object_class.Ptr());
3016       while (dst != end) {
3017         dst->SetClass<kVerifyNone>(image_object_class);
3018         dst->SetLockWord<kVerifyNone>(LockWord::Default(), /*as_volatile=*/ false);
3019         image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
3020         ++dst;
3021       }
3022     }
3023   }
3024 
3025   // We no longer need the hashcode map, values have already been copied to target objects.
3026   saved_hashcode_map_.clear();
3027 }
3028 
3029 class ImageWriter::FixupClassVisitor final : public FixupVisitor {
3030  public:
FixupClassVisitor(ImageWriter * image_writer,Object * copy)3031   FixupClassVisitor(ImageWriter* image_writer, Object* copy)
3032       : FixupVisitor(image_writer, copy) {}
3033 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const3034   void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
3035       REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
3036     DCHECK(obj->IsClass());
3037     FixupVisitor::operator()(obj, offset, /*is_static*/false);
3038   }
3039 
operator ()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const3040   void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
3041                   ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
3042       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3043     LOG(FATAL) << "Reference not expected here.";
3044   }
3045 };
3046 
GetNativeRelocation(void * obj)3047 ImageWriter::NativeObjectRelocation ImageWriter::GetNativeRelocation(void* obj) {
3048   DCHECK(obj != nullptr);
3049   DCHECK(!IsInBootImage(obj));
3050   auto it = native_object_relocations_.find(obj);
3051   CHECK(it != native_object_relocations_.end()) << obj << " spaces "
3052       << Runtime::Current()->GetHeap()->DumpSpaces();
3053   return it->second;
3054 }
3055 
3056 template <typename T>
PrettyPrint(T * ptr)3057 std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
3058   std::ostringstream oss;
3059   oss << ptr;
3060   return oss.str();
3061 }
3062 
3063 template <>
PrettyPrint(ArtMethod * method)3064 std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
3065   return ArtMethod::PrettyMethod(method);
3066 }
3067 
3068 template <typename T>
NativeLocationInImage(T * obj)3069 T* ImageWriter::NativeLocationInImage(T* obj) {
3070   if (obj == nullptr || IsInBootImage(obj)) {
3071     return obj;
3072   } else {
3073     NativeObjectRelocation relocation = GetNativeRelocation(obj);
3074     const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
3075     return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
3076   }
3077 }
3078 
3079 class ImageWriter::NativeLocationVisitor {
3080  public:
NativeLocationVisitor(ImageWriter * image_writer)3081   explicit NativeLocationVisitor(ImageWriter* image_writer)
3082       : image_writer_(image_writer) {}
3083 
3084   template <typename T>
operator ()(T * ptr,void ** dest_addr) const3085   T* operator()(T* ptr, void** dest_addr) const REQUIRES_SHARED(Locks::mutator_lock_) {
3086     if (ptr != nullptr) {
3087       image_writer_->CopyAndFixupPointer(dest_addr, ptr);
3088     }
3089     // TODO: The caller shall overwrite the value stored by CopyAndFixupPointer()
3090     // with the value we return here. We should try to avoid the duplicate work.
3091     return image_writer_->NativeLocationInImage(ptr);
3092   }
3093 
3094  private:
3095   ImageWriter* const image_writer_;
3096 };
3097 
FixupClass(mirror::Class * orig,mirror::Class * copy)3098 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
3099   orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
3100   FixupClassVisitor visitor(this, copy);
3101   ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
3102 
3103   if (kBitstringSubtypeCheckEnabled && !compiler_options_.IsBootImage()) {
3104     // When we call SubtypeCheck::EnsureInitialize, it Assigns new bitstring
3105     // values to the parent of that class.
3106     //
3107     // Every time this happens, the parent class has to mutate to increment
3108     // the "Next" value.
3109     //
3110     // If any of these parents are in the boot image, the changes [in the parents]
3111     // would be lost when the app image is reloaded.
3112     //
3113     // To prevent newly loaded classes (not in the app image) from being reassigned
3114     // the same bitstring value as an existing app image class, uninitialize
3115     // all the classes in the app image.
3116     //
3117     // On startup, the class linker will then re-initialize all the app
3118     // image bitstrings. See also ClassLinker::AddImageSpace.
3119     //
3120     // FIXME: Deal with boot image extensions.
3121     MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
3122     // Lock every time to prevent a dcheck failure when we suspend with the lock held.
3123     SubtypeCheck<mirror::Class*>::ForceUninitialize(copy);
3124   }
3125 
3126   // Remove the clinitThreadId. This is required for image determinism.
3127   copy->SetClinitThreadId(static_cast<pid_t>(0));
3128   // We never emit kRetryVerificationAtRuntime, instead we mark the class as
3129   // resolved and the class will therefore be re-verified at runtime.
3130   if (orig->ShouldVerifyAtRuntime()) {
3131     copy->SetStatusInternal(ClassStatus::kResolved);
3132   }
3133 }
3134 
FixupObject(Object * orig,Object * copy)3135 void ImageWriter::FixupObject(Object* orig, Object* copy) {
3136   DCHECK(orig != nullptr);
3137   DCHECK(copy != nullptr);
3138   if (kUseBakerReadBarrier) {
3139     orig->AssertReadBarrierState();
3140   }
3141   if (orig->IsClass()) {
3142     FixupClass(orig->AsClass<kVerifyNone>().Ptr(), down_cast<mirror::Class*>(copy));
3143   } else {
3144     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
3145         Runtime::Current()->GetClassLinker()->GetClassRoots();
3146     ObjPtr<mirror::Class> klass = orig->GetClass();
3147     if (klass == GetClassRoot<mirror::Method>(class_roots) ||
3148         klass == GetClassRoot<mirror::Constructor>(class_roots)) {
3149       // Need to go update the ArtMethod.
3150       auto* dest = down_cast<mirror::Executable*>(copy);
3151       auto* src = down_cast<mirror::Executable*>(orig);
3152       ArtMethod* src_method = src->GetArtMethod();
3153       CopyAndFixupPointer(dest, mirror::Executable::ArtMethodOffset(), src_method);
3154     } else if (klass == GetClassRoot<mirror::DexCache>(class_roots)) {
3155       down_cast<mirror::DexCache*>(copy)->ResetNativeFields();
3156     } else if (klass->IsClassLoaderClass()) {
3157       mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
3158       // If src is a ClassLoader, set the class table to null so that it gets recreated by the
3159       // ClassLoader.
3160       copy_loader->SetClassTable(nullptr);
3161       // Also set allocator to null to be safe. The allocator is created when we create the class
3162       // table. We also never expect to unload things in the image since they are held live as
3163       // roots.
3164       copy_loader->SetAllocator(nullptr);
3165     }
3166     FixupVisitor visitor(this, copy);
3167     orig->VisitReferences(visitor, visitor);
3168   }
3169 }
3170 
GetOatAddress(StubType type) const3171 const uint8_t* ImageWriter::GetOatAddress(StubType type) const {
3172   DCHECK_LE(type, StubType::kLast);
3173   // If we are compiling a boot image extension or app image,
3174   // we need to use the stubs of the primary boot image.
3175   if (!compiler_options_.IsBootImage()) {
3176     // Use the current image pointers.
3177     const std::vector<gc::space::ImageSpace*>& image_spaces =
3178         Runtime::Current()->GetHeap()->GetBootImageSpaces();
3179     DCHECK(!image_spaces.empty());
3180     const OatFile* oat_file = image_spaces[0]->GetOatFile();
3181     CHECK(oat_file != nullptr);
3182     const OatHeader& header = oat_file->GetOatHeader();
3183     switch (type) {
3184       // TODO: We could maybe clean this up if we stored them in an array in the oat header.
3185       case StubType::kQuickGenericJNITrampoline:
3186         return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
3187       case StubType::kJNIDlsymLookupTrampoline:
3188         return static_cast<const uint8_t*>(header.GetJniDlsymLookupTrampoline());
3189       case StubType::kJNIDlsymLookupCriticalTrampoline:
3190         return static_cast<const uint8_t*>(header.GetJniDlsymLookupCriticalTrampoline());
3191       case StubType::kQuickIMTConflictTrampoline:
3192         return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
3193       case StubType::kQuickResolutionTrampoline:
3194         return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
3195       case StubType::kQuickToInterpreterBridge:
3196         return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
3197       case StubType::kNterpTrampoline:
3198         return static_cast<const uint8_t*>(header.GetNterpTrampoline());
3199       default:
3200         UNREACHABLE();
3201     }
3202   }
3203   const ImageInfo& primary_image_info = GetImageInfo(0);
3204   return GetOatAddressForOffset(primary_image_info.GetStubOffset(type), primary_image_info);
3205 }
3206 
GetQuickCode(ArtMethod * method,const ImageInfo & image_info)3207 const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, const ImageInfo& image_info) {
3208   DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
3209   DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
3210   DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
3211   DCHECK(method->IsInvokable()) << method->PrettyMethod();
3212   DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
3213 
3214   // Use original code if it exists. Otherwise, set the code pointer to the resolution
3215   // trampoline.
3216 
3217   // Quick entrypoint:
3218   const void* quick_oat_entry_point =
3219       method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
3220   const uint8_t* quick_code;
3221 
3222   if (UNLIKELY(IsInBootImage(method->GetDeclaringClass().Ptr()))) {
3223     DCHECK(method->IsCopied());
3224     // If the code is not in the oat file corresponding to this image (e.g. default methods)
3225     quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
3226   } else {
3227     uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
3228     quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
3229   }
3230 
3231   bool needs_clinit_check = NeedsClinitCheckBeforeCall(method) &&
3232       !method->GetDeclaringClass()->IsVisiblyInitialized();
3233 
3234   if (quick_code == nullptr) {
3235     // If we don't have code, use generic jni / interpreter.
3236     if (method->IsNative()) {
3237       // The generic JNI trampolines performs class initialization check if needed.
3238       quick_code = GetOatAddress(StubType::kQuickGenericJNITrampoline);
3239     } else if (CanMethodUseNterp(method, compiler_options_.GetInstructionSet())) {
3240       // The nterp trampoline doesn't do initialization checks, so install the
3241       // resolution stub if needed.
3242       if (needs_clinit_check) {
3243         quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3244       } else {
3245         quick_code = GetOatAddress(StubType::kNterpTrampoline);
3246       }
3247     } else {
3248       // The interpreter brige performs class initialization check if needed.
3249       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3250     }
3251   } else if (needs_clinit_check) {
3252     // If we do have code but the method needs a class initialization check before calling
3253     // that code, install the resolution stub that will perform the check.
3254     quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3255   }
3256   return quick_code;
3257 }
3258 
CopyAndFixupMethod(ArtMethod * orig,ArtMethod * copy,size_t oat_index)3259 void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
3260                                      ArtMethod* copy,
3261                                      size_t oat_index) {
3262   if (orig->IsAbstract()) {
3263     // Ignore the single-implementation info for abstract method.
3264     // Do this on orig instead of copy, otherwise there is a crash due to methods
3265     // are copied before classes.
3266     // TODO: handle fixup of single-implementation method for abstract method.
3267     orig->SetHasSingleImplementation(false);
3268     orig->SetSingleImplementation(
3269         nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
3270   }
3271 
3272   memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
3273 
3274   CopyAndFixupReference(
3275       copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
3276 
3277   // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
3278   // oat_begin_
3279 
3280   // The resolution method has a special trampoline to call.
3281   Runtime* runtime = Runtime::Current();
3282   const void* quick_code;
3283   if (orig->IsRuntimeMethod()) {
3284     ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
3285     if (orig_table != nullptr) {
3286       // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
3287       quick_code = GetOatAddress(StubType::kQuickIMTConflictTrampoline);
3288       CopyAndFixupPointer(copy, ArtMethod::DataOffset(target_ptr_size_), orig_table);
3289     } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
3290       quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3291       // Set JNI entrypoint for resolving @CriticalNative methods called from compiled code .
3292       const void* jni_code = GetOatAddress(StubType::kJNIDlsymLookupCriticalTrampoline);
3293       copy->SetEntryPointFromJniPtrSize(jni_code, target_ptr_size_);
3294     } else {
3295       bool found_one = false;
3296       for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
3297         auto idx = static_cast<CalleeSaveType>(i);
3298         if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
3299           found_one = true;
3300           break;
3301         }
3302       }
3303       CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
3304       CHECK(copy->IsRuntimeMethod());
3305       CHECK(copy->GetEntryPointFromQuickCompiledCode() == nullptr);
3306       quick_code = nullptr;
3307     }
3308   } else {
3309     // We assume all methods have code. If they don't currently then we set them to the use the
3310     // resolution trampoline. Abstract methods never have code and so we need to make sure their
3311     // use results in an AbstractMethodError. We use the interpreter to achieve this.
3312     if (UNLIKELY(!orig->IsInvokable())) {
3313       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3314     } else {
3315       const ImageInfo& image_info = image_infos_[oat_index];
3316       quick_code = GetQuickCode(orig, image_info);
3317 
3318       // JNI entrypoint:
3319       if (orig->IsNative()) {
3320         // The native method's pointer is set to a stub to lookup via dlsym.
3321         // Note this is not the code_ pointer, that is handled above.
3322         StubType stub_type = orig->IsCriticalNative() ? StubType::kJNIDlsymLookupCriticalTrampoline
3323                                                       : StubType::kJNIDlsymLookupTrampoline;
3324         copy->SetEntryPointFromJniPtrSize(GetOatAddress(stub_type), target_ptr_size_);
3325       } else if (!orig->HasCodeItem()) {
3326         CHECK(copy->GetDataPtrSize(target_ptr_size_) == nullptr);
3327       } else {
3328         CHECK(copy->GetDataPtrSize(target_ptr_size_) != nullptr);
3329       }
3330     }
3331   }
3332   if (quick_code != nullptr) {
3333     copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
3334   }
3335 }
3336 
GetBinSizeSum(Bin up_to) const3337 size_t ImageWriter::ImageInfo::GetBinSizeSum(Bin up_to) const {
3338   DCHECK_LE(static_cast<size_t>(up_to), kNumberOfBins);
3339   return std::accumulate(&bin_slot_sizes_[0],
3340                          &bin_slot_sizes_[0] + static_cast<size_t>(up_to),
3341                          /*init*/ static_cast<size_t>(0));
3342 }
3343 
BinSlot(uint32_t lockword)3344 ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
3345   // These values may need to get updated if more bins are added to the enum Bin
3346   static_assert(kBinBits == 3, "wrong number of bin bits");
3347   static_assert(kBinShift == 27, "wrong number of shift");
3348   static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
3349 
3350   DCHECK_LT(GetBin(), Bin::kMirrorCount);
3351   DCHECK_ALIGNED(GetOffset(), kObjectAlignment);
3352 }
3353 
BinSlot(Bin bin,uint32_t index)3354 ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
3355     : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
3356   DCHECK_EQ(index, GetOffset());
3357 }
3358 
GetBin() const3359 ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
3360   return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
3361 }
3362 
GetOffset() const3363 uint32_t ImageWriter::BinSlot::GetOffset() const {
3364   return lockword_ & ~kBinMask;
3365 }
3366 
BinTypeForNativeRelocationType(NativeObjectRelocationType type)3367 ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
3368   switch (type) {
3369     case NativeObjectRelocationType::kArtFieldArray:
3370       return Bin::kArtField;
3371     case NativeObjectRelocationType::kArtMethodClean:
3372     case NativeObjectRelocationType::kArtMethodArrayClean:
3373       return Bin::kArtMethodClean;
3374     case NativeObjectRelocationType::kArtMethodDirty:
3375     case NativeObjectRelocationType::kArtMethodArrayDirty:
3376       return Bin::kArtMethodDirty;
3377     case NativeObjectRelocationType::kRuntimeMethod:
3378       return Bin::kRuntimeMethod;
3379     case NativeObjectRelocationType::kIMTable:
3380       return Bin::kImTable;
3381     case NativeObjectRelocationType::kIMTConflictTable:
3382       return Bin::kIMTConflictTable;
3383     case NativeObjectRelocationType::kGcRootPointer:
3384       return Bin::kMetadata;
3385   }
3386   UNREACHABLE();
3387 }
3388 
GetOatIndex(mirror::Object * obj) const3389 size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
3390   if (!IsMultiImage()) {
3391     DCHECK(oat_index_map_.empty());
3392     return GetDefaultOatIndex();
3393   }
3394   auto it = oat_index_map_.find(obj);
3395   DCHECK(it != oat_index_map_.end()) << obj;
3396   return it->second;
3397 }
3398 
GetOatIndexForDexFile(const DexFile * dex_file) const3399 size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
3400   if (!IsMultiImage()) {
3401     return GetDefaultOatIndex();
3402   }
3403   auto it = dex_file_oat_index_map_.find(dex_file);
3404   DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
3405   return it->second;
3406 }
3407 
GetOatIndexForClass(ObjPtr<mirror::Class> klass) const3408 size_t ImageWriter::GetOatIndexForClass(ObjPtr<mirror::Class> klass) const {
3409   while (klass->IsArrayClass()) {
3410     klass = klass->GetComponentType();
3411   }
3412   if (UNLIKELY(klass->IsPrimitive())) {
3413     DCHECK(klass->GetDexCache() == nullptr);
3414     return GetDefaultOatIndex();
3415   } else {
3416     DCHECK(klass->GetDexCache() != nullptr);
3417     return GetOatIndexForDexFile(&klass->GetDexFile());
3418   }
3419 }
3420 
UpdateOatFileLayout(size_t oat_index,size_t oat_loaded_size,size_t oat_data_offset,size_t oat_data_size)3421 void ImageWriter::UpdateOatFileLayout(size_t oat_index,
3422                                       size_t oat_loaded_size,
3423                                       size_t oat_data_offset,
3424                                       size_t oat_data_size) {
3425   DCHECK_GE(oat_loaded_size, oat_data_offset);
3426   DCHECK_GE(oat_loaded_size - oat_data_offset, oat_data_size);
3427 
3428   const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
3429   DCHECK(images_end != nullptr);  // Image space must be ready.
3430   for (const ImageInfo& info : image_infos_) {
3431     DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
3432   }
3433 
3434   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3435   cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
3436   cur_image_info.oat_loaded_size_ = oat_loaded_size;
3437   cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
3438   cur_image_info.oat_size_ = oat_data_size;
3439 
3440   if (compiler_options_.IsAppImage()) {
3441     CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
3442     return;
3443   }
3444 
3445   // Update the oat_offset of the next image info.
3446   if (oat_index + 1u != oat_filenames_.size()) {
3447     // There is a following one.
3448     ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
3449     next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
3450   }
3451 }
3452 
UpdateOatFileHeader(size_t oat_index,const OatHeader & oat_header)3453 void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
3454   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3455   cur_image_info.oat_checksum_ = oat_header.GetChecksum();
3456 
3457   if (oat_index == GetDefaultOatIndex()) {
3458     // Primary oat file, read the trampolines.
3459     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupTrampoline,
3460                                  oat_header.GetJniDlsymLookupTrampolineOffset());
3461     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupCriticalTrampoline,
3462                                  oat_header.GetJniDlsymLookupCriticalTrampolineOffset());
3463     cur_image_info.SetStubOffset(StubType::kQuickGenericJNITrampoline,
3464                                  oat_header.GetQuickGenericJniTrampolineOffset());
3465     cur_image_info.SetStubOffset(StubType::kQuickIMTConflictTrampoline,
3466                                  oat_header.GetQuickImtConflictTrampolineOffset());
3467     cur_image_info.SetStubOffset(StubType::kQuickResolutionTrampoline,
3468                                  oat_header.GetQuickResolutionTrampolineOffset());
3469     cur_image_info.SetStubOffset(StubType::kQuickToInterpreterBridge,
3470                                  oat_header.GetQuickToInterpreterBridgeOffset());
3471     cur_image_info.SetStubOffset(StubType::kNterpTrampoline,
3472                                  oat_header.GetNterpTrampolineOffset());
3473   }
3474 }
3475 
ImageWriter(const CompilerOptions & compiler_options,uintptr_t image_begin,ImageHeader::StorageMode image_storage_mode,const std::vector<std::string> & oat_filenames,const HashMap<const DexFile *,size_t> & dex_file_oat_index_map,jobject class_loader,const HashSet<std::string> * dirty_image_objects)3476 ImageWriter::ImageWriter(
3477     const CompilerOptions& compiler_options,
3478     uintptr_t image_begin,
3479     ImageHeader::StorageMode image_storage_mode,
3480     const std::vector<std::string>& oat_filenames,
3481     const HashMap<const DexFile*, size_t>& dex_file_oat_index_map,
3482     jobject class_loader,
3483     const HashSet<std::string>* dirty_image_objects)
3484     : compiler_options_(compiler_options),
3485       boot_image_begin_(Runtime::Current()->GetHeap()->GetBootImagesStartAddress()),
3486       boot_image_size_(Runtime::Current()->GetHeap()->GetBootImagesSize()),
3487       global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
3488       image_objects_offset_begin_(0),
3489       target_ptr_size_(InstructionSetPointerSize(compiler_options.GetInstructionSet())),
3490       image_infos_(oat_filenames.size()),
3491       dirty_methods_(0u),
3492       clean_methods_(0u),
3493       app_class_loader_(class_loader),
3494       boot_image_live_objects_(nullptr),
3495       image_storage_mode_(image_storage_mode),
3496       oat_filenames_(oat_filenames),
3497       dex_file_oat_index_map_(dex_file_oat_index_map),
3498       dirty_image_objects_(dirty_image_objects) {
3499   DCHECK(compiler_options.IsBootImage() ||
3500          compiler_options.IsBootImageExtension() ||
3501          compiler_options.IsAppImage());
3502   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_begin_ == 0u);
3503   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_size_ == 0u);
3504   CHECK_NE(image_begin, 0U);
3505   std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
3506   CHECK_EQ(compiler_options.IsBootImage(),
3507            Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
3508       << "Compiling a boot image should occur iff there are no boot image spaces loaded";
3509   if (compiler_options_.IsAppImage()) {
3510     // Make sure objects are not crossing region boundaries for app images.
3511     region_size_ = gc::space::RegionSpace::kRegionSize;
3512   }
3513 }
3514 
ImageInfo()3515 ImageWriter::ImageInfo::ImageInfo()
3516     : intern_table_(),
3517       class_table_() {}
3518 
3519 template <typename DestType>
CopyAndFixupReference(DestType * dest,ObjPtr<mirror::Object> src)3520 void ImageWriter::CopyAndFixupReference(DestType* dest, ObjPtr<mirror::Object> src) {
3521   static_assert(std::is_same<DestType, mirror::CompressedReference<mirror::Object>>::value ||
3522                     std::is_same<DestType, mirror::HeapReference<mirror::Object>>::value,
3523                 "DestType must be a Compressed-/HeapReference<Object>.");
3524   dest->Assign(GetImageAddress(src.Ptr()));
3525 }
3526 
CopyAndFixupPointer(void ** target,void * value,PointerSize pointer_size)3527 void ImageWriter::CopyAndFixupPointer(void** target, void* value, PointerSize pointer_size) {
3528   void* new_value = NativeLocationInImage(value);
3529   if (pointer_size == PointerSize::k32) {
3530     *reinterpret_cast<uint32_t*>(target) = reinterpret_cast32<uint32_t>(new_value);
3531   } else {
3532     *reinterpret_cast<uint64_t*>(target) = reinterpret_cast64<uint64_t>(new_value);
3533   }
3534   DCHECK(value != nullptr);
3535 }
3536 
CopyAndFixupPointer(void ** target,void * value)3537 void ImageWriter::CopyAndFixupPointer(void** target, void* value)
3538     REQUIRES_SHARED(Locks::mutator_lock_) {
3539   CopyAndFixupPointer(target, value, target_ptr_size_);
3540 }
3541 
CopyAndFixupPointer(void * object,MemberOffset offset,void * value,PointerSize pointer_size)3542 void ImageWriter::CopyAndFixupPointer(
3543     void* object, MemberOffset offset, void* value, PointerSize pointer_size) {
3544   void** target =
3545       reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(object) + offset.Uint32Value());
3546   return CopyAndFixupPointer(target, value, pointer_size);
3547 }
3548 
CopyAndFixupPointer(void * object,MemberOffset offset,void * value)3549 void ImageWriter::CopyAndFixupPointer(void* object, MemberOffset offset, void* value) {
3550   return CopyAndFixupPointer(object, offset, value, target_ptr_size_);
3551 }
3552 
3553 }  // namespace linker
3554 }  // namespace art
3555