2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "image_writer.h"
25 #include <unordered_set>
28 #include "art_field-inl.h"
29 #include "art_method-inl.h"
30 #include "base/logging.h"
31 #include "base/unix_file/fd_file.h"
32 #include "class_linker-inl.h"
33 #include "compiled_method.h"
34 #include "dex_file-inl.h"
35 #include "driver/compiler_driver.h"
37 #include "elf_utils.h"
38 #include "elf_writer.h"
39 #include "gc/accounting/card_table-inl.h"
40 #include "gc/accounting/heap_bitmap.h"
41 #include "gc/accounting/space_bitmap-inl.h"
43 #include "gc/space/large_object_space.h"
44 #include "gc/space/space-inl.h"
47 #include "intern_table.h"
48 #include "linear_alloc.h"
49 #include "lock_word.h"
50 #include "mirror/abstract_method.h"
51 #include "mirror/array-inl.h"
52 #include "mirror/class-inl.h"
53 #include "mirror/class_loader.h"
54 #include "mirror/dex_cache-inl.h"
55 #include "mirror/method.h"
56 #include "mirror/object-inl.h"
57 #include "mirror/object_array-inl.h"
58 #include "mirror/string-inl.h"
61 #include "oat_file_manager.h"
63 #include "scoped_thread_state_change.h"
64 #include "handle_scope-inl.h"
65 #include "utils/dex_cache_arrays_layout-inl.h"
67 using ::art::mirror::Class;
68 using ::art::mirror::DexCache;
69 using ::art::mirror::Object;
70 using ::art::mirror::ObjectArray;
71 using ::art::mirror::String;
75 // Separate objects into multiple bins to optimize dirty memory use.
76 static constexpr bool kBinObjects = true;
78 // Return true if an object is already in an image space.
79 bool ImageWriter::IsInBootImage(const void* obj) const {
80 gc::Heap* const heap = Runtime::Current()->GetHeap();
81 if (!compile_app_image_) {
82 DCHECK(heap->GetBootImageSpaces().empty());
85 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
86 const uint8_t* image_begin = boot_image_space->Begin();
87 // Real image end including ArtMethods and ArtField sections.
88 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
89 if (image_begin <= obj && obj < image_end) {
96 bool ImageWriter::IsInBootOatFile(const void* ptr) const {
97 gc::Heap* const heap = Runtime::Current()->GetHeap();
98 if (!compile_app_image_) {
99 DCHECK(heap->GetBootImageSpaces().empty());
102 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
103 const ImageHeader& image_header = boot_image_space->GetImageHeader();
104 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
111 static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
112 SHARED_REQUIRES(Locks::mutator_lock_) {
113 Class* klass = obj->GetClass();
114 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
117 static void CheckNoDexObjects() {
118 ScopedObjectAccess soa(Thread::Current());
119 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
122 bool ImageWriter::PrepareImageAddressSpace() {
123 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
124 gc::Heap* const heap = Runtime::Current()->GetHeap();
126 ScopedObjectAccess soa(Thread::Current());
127 PruneNonImageClasses(); // Remove junk
128 if (!compile_app_image_) {
129 // Avoid for app image since this may increase RAM and image size.
130 ComputeLazyFieldsForImageClasses(); // Add useful information
133 heap->CollectGarbage(false); // Remove garbage.
135 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
138 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
139 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
146 ScopedObjectAccess soa(Thread::Current());
147 CheckNonImageClassesRemoved();
151 ScopedObjectAccess soa(Thread::Current());
152 CalculateNewObjectOffsets();
155 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
156 // bin size sums being calculated.
157 if (!AllocMemory()) {
164 bool ImageWriter::Write(int image_fd,
165 const std::vector<const char*>& image_filenames,
166 const std::vector<const char*>& oat_filenames) {
167 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
169 CHECK(!image_filenames.empty());
170 if (image_fd != kInvalidFd) {
171 CHECK_EQ(image_filenames.size(), 1u);
173 CHECK(!oat_filenames.empty());
174 CHECK_EQ(image_filenames.size(), oat_filenames.size());
177 ScopedObjectAccess soa(Thread::Current());
178 for (size_t i = 0; i < oat_filenames.size(); ++i) {
180 CopyAndFixupNativeData(i);
185 // TODO: heap validation can't handle these fix up passes.
186 ScopedObjectAccess soa(Thread::Current());
187 Runtime::Current()->GetHeap()->DisableObjectValidation();
188 CopyAndFixupObjects();
191 for (size_t i = 0; i < image_filenames.size(); ++i) {
192 const char* image_filename = image_filenames[i];
193 ImageInfo& image_info = GetImageInfo(i);
194 std::unique_ptr<File> image_file;
195 if (image_fd != kInvalidFd) {
196 if (strlen(image_filename) == 0u) {
197 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
198 // Empty the file in case it already exists.
199 if (image_file != nullptr) {
200 TEMP_FAILURE_RETRY(image_file->SetLength(0));
201 TEMP_FAILURE_RETRY(image_file->Flush());
204 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
207 image_file.reset(OS::CreateEmptyFile(image_filename));
210 if (image_file == nullptr) {
211 LOG(ERROR) << "Failed to open image file " << image_filename;
215 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
216 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
221 std::unique_ptr<char[]> compressed_data;
222 // Image data size excludes the bitmap and the header.
223 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
224 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
225 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
227 const char* image_data_to_write;
228 const uint64_t compress_start_time = NanoTime();
230 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
231 switch (image_storage_mode_) {
232 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
233 case ImageHeader::kStorageModeLZ4: {
234 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
235 compressed_data.reset(new char[compressed_max_size]);
236 data_size = LZ4_compress(
237 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
244 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
245 case ImageHeader::kStorageModeLZ4HC: {
246 // Bound is same as non HC.
247 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
248 compressed_data.reset(new char[compressed_max_size]);
249 data_size = LZ4_compressHC(
250 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
256 case ImageHeader::kStorageModeUncompressed: {
257 data_size = image_data_size;
258 image_data_to_write = image_data;
262 LOG(FATAL) << "Unsupported";
267 if (compressed_data != nullptr) {
268 image_data_to_write = &compressed_data[0];
269 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
270 << PrettyDuration(NanoTime() - compress_start_time);
272 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
273 const size_t decompressed_size = LZ4_decompress_safe(
274 reinterpret_cast<char*>(&compressed_data[0]),
275 reinterpret_cast<char*>(&temp[0]),
278 CHECK_EQ(decompressed_size, image_data_size);
279 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
283 // Write out the image + fields + methods.
284 const bool is_compressed = compressed_data != nullptr;
285 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
286 PLOG(ERROR) << "Failed to write image file data " << image_filename;
291 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
293 const ImageSection& bitmap_section = image_header->GetImageSection(
294 ImageHeader::kSectionImageBitmap);
295 // Align up since data size may be unaligned if the image is compressed.
296 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
297 if (!is_compressed) {
298 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
300 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
301 bitmap_section.Size(),
302 bitmap_position_in_file)) {
303 PLOG(ERROR) << "Failed to write image file " << image_filename;
308 int err = image_file->Flush();
310 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
315 // Write header last in case the compiler gets killed in the middle of image writing.
316 // We do not want to have a corrupted image with a valid header.
317 // The header is uncompressed since it contains whether the image is compressed or not.
318 image_header->data_size_ = data_size;
319 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
322 PLOG(ERROR) << "Failed to write image file header " << image_filename;
327 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
328 static_cast<size_t>(image_file->GetLength()));
329 if (image_file->FlushCloseOrErase() != 0) {
330 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
337 void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
338 DCHECK(object != nullptr);
339 DCHECK_NE(offset, 0U);
341 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
342 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
343 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
344 DCHECK(IsImageOffsetAssigned(object));
347 void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
348 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
349 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
350 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
353 void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
354 DCHECK(object != nullptr);
355 DCHECK_NE(image_objects_offset_begin_, 0u);
357 size_t oat_index = GetOatIndex(object);
358 ImageInfo& image_info = GetImageInfo(oat_index);
359 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
360 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
361 DCHECK_ALIGNED(new_offset, kObjectAlignment);
363 SetImageOffset(object, new_offset);
364 DCHECK_LT(new_offset, image_info.image_end_);
367 bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
368 // Will also return true if the bin slot was assigned since we are reusing the lock word.
369 DCHECK(object != nullptr);
370 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
373 size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
374 DCHECK(object != nullptr);
375 DCHECK(IsImageOffsetAssigned(object));
376 LockWord lock_word = object->GetLockWord(false);
377 size_t offset = lock_word.ForwardingAddress();
378 size_t oat_index = GetOatIndex(object);
379 const ImageInfo& image_info = GetImageInfo(oat_index);
380 DCHECK_LT(offset, image_info.image_end_);
384 void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
385 DCHECK(object != nullptr);
386 DCHECK(!IsImageOffsetAssigned(object));
387 DCHECK(!IsImageBinSlotAssigned(object));
389 // Before we stomp over the lock word, save the hash code for later.
390 Monitor::Deflate(Thread::Current(), object);;
391 LockWord lw(object->GetLockWord(false));
392 switch (lw.GetState()) {
393 case LockWord::kFatLocked: {
394 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
397 case LockWord::kThinLocked: {
398 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
401 case LockWord::kUnlocked:
402 // No hash, don't need to save it.
404 case LockWord::kHashCode:
405 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
406 saved_hashcode_map_.emplace(object, lw.GetHashCode());
409 LOG(FATAL) << "Unreachable.";
412 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
413 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
414 DCHECK(IsImageBinSlotAssigned(object));
417 void ImageWriter::PrepareDexCacheArraySlots() {
418 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
419 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
420 // when AssignImageBinSlot() assigns their indexes out or order.
421 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
422 auto it = dex_file_oat_index_map_.find(dex_file);
423 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
424 ImageInfo& image_info = GetImageInfo(it->second);
425 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
426 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
427 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
430 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
431 Thread* const self = Thread::Current();
432 ReaderMutexLock mu(self, *class_linker->DexLock());
433 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
434 mirror::DexCache* dex_cache =
435 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
436 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
439 const DexFile* dex_file = dex_cache->GetDexFile();
440 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
441 DCHECK(layout.Valid());
442 size_t oat_index = GetOatIndexForDexCache(dex_cache);
443 ImageInfo& image_info = GetImageInfo(oat_index);
444 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
445 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
446 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
447 start + layout.TypesOffset(),
449 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
450 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
451 start + layout.MethodsOffset(),
453 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
454 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
455 start + layout.FieldsOffset(),
457 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
458 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
462 void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
463 if (array != nullptr) {
464 DCHECK(!IsInBootImage(array));
465 size_t oat_index = GetOatIndexForDexCache(dex_cache);
466 native_object_relocations_.emplace(array,
467 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
471 void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
472 DCHECK(arr != nullptr);
474 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
475 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
476 if (method != nullptr && !method->IsRuntimeMethod()) {
477 mirror::Class* klass = method->GetDeclaringClass();
478 CHECK(klass == nullptr || KeepClass(klass))
479 << PrettyClass(klass) << " should be a kept class";
483 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
485 pointer_arrays_.emplace(arr, kBinArtMethodClean);
488 void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
489 DCHECK(object != nullptr);
490 size_t object_size = object->SizeOf();
492 // The magic happens here. We segregate objects into different bins based
493 // on how likely they are to get dirty at runtime.
495 // Likely-to-dirty objects get packed together into the same bin so that
496 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
499 // This means more pages will stay either clean or shared dirty (with zygote) and
500 // the app will use less of its own (private) memory.
501 Bin bin = kBinRegular;
502 size_t current_offset = 0u;
506 // Changing the bin of an object is purely a memory-use tuning.
507 // It has no change on runtime correctness.
509 // Memory analysis has determined that the following types of objects get dirtied
512 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
513 // a fixed layout which helps improve generated code (using PC-relative addressing),
514 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
515 // Since these arrays are huge, most pages do not overlap other objects and it's not
516 // really important where they are for the clean/dirty separation. Due to their
517 // special PC-relative addressing, we arbitrarily keep them at the end.
518 // * Class'es which are verified [their clinit runs only at runtime]
519 // - classes in general [because their static fields get overwritten]
520 // - initialized classes with all-final statics are unlikely to be ever dirty,
521 // so bin them separately
522 // * Art Methods that are:
523 // - native [their native entry point is not looked up until runtime]
524 // - have declaring classes that aren't initialized
525 // [their interpreter/quick entry points are trampolines until the class
526 // becomes initialized]
528 // We also assume the following objects get dirtied either never or extremely rarely:
529 // * Strings (they are immutable)
530 // * Art methods that aren't native and have initialized declared classes
532 // We assume that "regular" bin objects are highly unlikely to become dirtied,
533 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
535 if (object->IsClass()) {
536 bin = kBinClassVerified;
537 mirror::Class* klass = object->AsClass();
539 // Add non-embedded vtable to the pointer array table if there is one.
540 auto* vtable = klass->GetVTable();
541 if (vtable != nullptr) {
542 AddMethodPointerArray(vtable);
544 auto* iftable = klass->GetIfTable();
545 if (iftable != nullptr) {
546 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
547 if (iftable->GetMethodArrayCount(i) > 0) {
548 AddMethodPointerArray(iftable->GetMethodArray(i));
553 if (klass->GetStatus() == Class::kStatusInitialized) {
554 bin = kBinClassInitialized;
556 // If the class's static fields are all final, put it into a separate bin
557 // since it's very likely it will stay clean.
558 uint32_t num_static_fields = klass->NumStaticFields();
559 if (num_static_fields == 0) {
560 bin = kBinClassInitializedFinalStatics;
562 // Maybe all the statics are final?
563 bool all_final = true;
564 for (uint32_t i = 0; i < num_static_fields; ++i) {
565 ArtField* field = klass->GetStaticField(i);
566 if (!field->IsFinal()) {
573 bin = kBinClassInitializedFinalStatics;
577 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
578 bin = kBinString; // Strings are almost always immutable (except for object header).
579 } // else bin = kBinRegular
582 size_t oat_index = GetOatIndex(object);
583 ImageInfo& image_info = GetImageInfo(oat_index);
585 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
586 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
587 // Move the current bin size up to accommodate the object we just assigned a bin slot.
588 image_info.bin_slot_sizes_[bin] += offset_delta;
590 BinSlot new_bin_slot(bin, current_offset);
591 SetImageBinSlot(object, new_bin_slot);
593 ++image_info.bin_slot_count_[bin];
595 // Grow the image closer to the end by the object we just assigned.
596 image_info.image_end_ += offset_delta;
599 bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
603 mirror::Class* declaring_class = m->GetDeclaringClass();
604 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
605 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
608 bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
609 DCHECK(object != nullptr);
611 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
612 // If it's in some other state, then we haven't yet assigned an image bin slot.
613 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
615 } else if (kIsDebugBuild) {
616 LockWord lock_word = object->GetLockWord(false);
617 size_t offset = lock_word.ForwardingAddress();
618 BinSlot bin_slot(offset);
619 size_t oat_index = GetOatIndex(object);
620 const ImageInfo& image_info = GetImageInfo(oat_index);
621 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
622 << "bin slot offset should not exceed the size of that bin";
627 ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
628 DCHECK(object != nullptr);
629 DCHECK(IsImageBinSlotAssigned(object));
631 LockWord lock_word = object->GetLockWord(false);
632 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
633 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
635 BinSlot bin_slot(static_cast<uint32_t>(offset));
636 size_t oat_index = GetOatIndex(object);
637 const ImageInfo& image_info = GetImageInfo(oat_index);
638 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
643 bool ImageWriter::AllocMemory() {
644 for (ImageInfo& image_info : image_infos_) {
645 ImageSection unused_sections[ImageHeader::kSectionCount];
646 const size_t length = RoundUp(
647 image_info.CreateImageSections(target_ptr_size_, unused_sections),
650 std::string error_msg;
651 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
654 PROT_READ | PROT_WRITE,
658 if (UNLIKELY(image_info.image_.get() == nullptr)) {
659 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
663 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
664 CHECK_LE(image_info.image_end_, length);
665 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
666 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
667 if (image_info.image_bitmap_.get() == nullptr) {
668 LOG(ERROR) << "Failed to allocate memory for image bitmap";
675 class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
677 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
678 StackHandleScope<1> hs(Thread::Current());
679 mirror::Class::ComputeName(hs.NewHandle(c));
684 void ImageWriter::ComputeLazyFieldsForImageClasses() {
685 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
686 ComputeLazyFieldsForClassesVisitor visitor;
687 class_linker->VisitClassesWithoutClassesLock(&visitor);
690 static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
691 return klass->GetClassLoader() == nullptr;
694 bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
695 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
698 bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
699 bool early_exit = false;
700 std::unordered_set<mirror::Class*> visited;
701 return PruneAppImageClassInternal(klass, &early_exit, &visited);
704 bool ImageWriter::PruneAppImageClassInternal(
705 mirror::Class* klass,
707 std::unordered_set<mirror::Class*>* visited) {
708 DCHECK(early_exit != nullptr);
709 DCHECK(visited != nullptr);
710 DCHECK(compile_app_image_);
711 if (klass == nullptr || IsInBootImage(klass)) {
714 auto found = prune_class_memo_.find(klass);
715 if (found != prune_class_memo_.end()) {
716 // Already computed, return the found value.
717 return found->second;
719 // Circular dependencies, return false but do not store the result in the memoization table.
720 if (visited->find(klass) != visited->end()) {
724 visited->emplace(klass);
725 bool result = IsBootClassLoaderClass(klass);
727 // Prune if not an image class, this handles any broken sets of image classes such as having a
728 // class in the set but not it's superclass.
729 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
730 bool my_early_exit = false; // Only for ourselves, ignore caller.
731 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
733 if (klass->GetStatus() == mirror::Class::kStatusError) {
736 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
739 // Check interfaces since these wont be visited through VisitReferences.)
740 mirror::IfTable* if_table = klass->GetIfTable();
741 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
742 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
747 if (klass->IsObjectArrayClass()) {
748 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
752 // Check static fields and their classes.
753 size_t num_static_fields = klass->NumReferenceStaticFields();
754 if (num_static_fields != 0 && klass->IsResolved()) {
755 // Presumably GC can happen when we are cross compiling, it should not cause performance
756 // problems to do pointer size logic.
757 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
758 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
759 for (size_t i = 0u; i < num_static_fields; ++i) {
760 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
761 if (ref != nullptr) {
762 if (ref->IsClass()) {
763 result = result || PruneAppImageClassInternal(ref->AsClass(),
767 result = result || PruneAppImageClassInternal(ref->GetClass(),
772 field_offset = MemberOffset(field_offset.Uint32Value() +
773 sizeof(mirror::HeapReference<mirror::Object>));
776 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
779 // Erase the element we stored earlier since we are exiting the function.
780 auto it = visited->find(klass);
781 DCHECK(it != visited->end());
783 // Only store result if it is true or none of the calls early exited due to circular
784 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
785 // a child call and we can remember the result.
786 if (result == true || !my_early_exit || visited->empty()) {
787 prune_class_memo_[klass] = result;
789 *early_exit |= my_early_exit;
793 bool ImageWriter::KeepClass(Class* klass) {
794 if (klass == nullptr) {
797 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
798 // Already in boot image, return true.
802 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
805 if (compile_app_image_) {
806 // For app images, we need to prune boot loader classes that are not in the boot image since
807 // these may have already been loaded when the app image is loaded.
808 // Keep classes in the boot image space since we don't want to re-resolve these.
809 return !PruneAppImageClass(klass);
814 class NonImageClassesVisitor : public ClassVisitor {
816 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
818 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
819 if (!image_writer_->KeepClass(klass)) {
820 classes_to_prune_.insert(klass);
825 std::unordered_set<mirror::Class*> classes_to_prune_;
826 ImageWriter* const image_writer_;
829 void ImageWriter::PruneNonImageClasses() {
830 Runtime* runtime = Runtime::Current();
831 ClassLinker* class_linker = runtime->GetClassLinker();
832 Thread* self = Thread::Current();
834 // Make a list of classes we would like to prune.
835 NonImageClassesVisitor visitor(this);
836 class_linker->VisitClasses(&visitor);
838 // Remove the undesired classes from the class roots.
839 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
840 for (mirror::Class* klass : visitor.classes_to_prune_) {
842 const char* name = klass->GetDescriptor(&temp);
843 VLOG(compiler) << "Pruning class " << name;
844 if (!compile_app_image_) {
845 DCHECK(IsBootClassLoaderClass(klass));
847 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
851 // Clear references to removed classes from the DexCaches.
852 ArtMethod* resolution_method = runtime->GetResolutionMethod();
854 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
855 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
856 ReaderMutexLock mu2(self, *class_linker->DexLock());
857 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
858 if (self->IsJWeakCleared(data.weak_root)) {
861 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
862 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
863 Class* klass = dex_cache->GetResolvedType(i);
864 if (klass != nullptr && !KeepClass(klass)) {
865 dex_cache->SetResolvedType(i, nullptr);
868 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
869 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
871 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
872 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
873 mirror::Class* declaring_class = method->GetDeclaringClass();
874 // Copied methods may be held live by a class which was not an image class but have a
875 // declaring class which is an image class. Set it to the resolution method to be safe and
876 // prevent dangling pointers.
877 if (method->IsCopied() || !KeepClass(declaring_class)) {
878 mirror::DexCache::SetElementPtrSize(resolved_methods,
883 // Check that the class is still in the classes table.
884 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
885 << PrettyClass(declaring_class) << " not in class linker table";
888 ArtField** resolved_fields = dex_cache->GetResolvedFields();
889 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
890 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
891 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
892 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
895 // Clean the dex field. It might have been populated during the initialization phase, but
896 // contains data only valid during a real run.
897 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
900 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
901 class_linker->DropFindArrayClassCache();
903 // Clear to save RAM.
904 prune_class_memo_.clear();
907 void ImageWriter::CheckNonImageClassesRemoved() {
908 if (compiler_driver_.GetImageClasses() != nullptr) {
909 gc::Heap* heap = Runtime::Current()->GetHeap();
910 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
914 void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
915 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
916 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
917 Class* klass = obj->AsClass();
918 if (!image_writer->KeepClass(klass)) {
919 image_writer->DumpImageClasses();
921 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
922 << " " << PrettyDescriptor(klass);
927 void ImageWriter::DumpImageClasses() {
928 auto image_classes = compiler_driver_.GetImageClasses();
929 CHECK(image_classes != nullptr);
930 for (const std::string& image_class : *image_classes) {
931 LOG(INFO) << " " << image_class;
935 mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
936 Thread* const self = Thread::Current();
937 for (const ImageInfo& image_info : image_infos_) {
938 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
939 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
940 << string->ToModifiedUtf8();
941 if (found != nullptr) {
945 if (compile_app_image_) {
946 Runtime* const runtime = Runtime::Current();
947 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
948 // If we found it in the runtime intern table it could either be in the boot image or interned
949 // during app image compilation. If it was in the boot image return that, otherwise return null
950 // since it belongs to another image space.
951 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
954 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
955 << string->ToModifiedUtf8();
960 void ImageWriter::CalculateObjectBinSlots(Object* obj) {
961 DCHECK(obj != nullptr);
962 // if it is a string, we want to intern it if its not interned.
963 if (obj->GetClass()->IsStringClass()) {
964 size_t oat_index = GetOatIndex(obj);
965 ImageInfo& image_info = GetImageInfo(oat_index);
967 // we must be an interned string that was forward referenced and already assigned
968 if (IsImageBinSlotAssigned(obj)) {
969 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
972 // Need to check if the string is already interned in another image info so that we don't have
973 // the intern tables of two different images contain the same string.
974 mirror::String* interned = FindInternedString(obj->AsString());
975 if (interned == nullptr) {
976 // Not in another image space, insert to our table.
977 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
979 if (obj != interned) {
980 if (!IsImageBinSlotAssigned(interned)) {
981 // interned obj is after us, allocate its location early
982 AssignImageBinSlot(interned);
984 // point those looking for this object to the interned version.
985 SetImageBinSlot(obj, GetImageBinSlot(interned));
988 // else (obj == interned), nothing to do but fall through to the normal case
991 AssignImageBinSlot(obj);
994 ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
995 Runtime* runtime = Runtime::Current();
996 ClassLinker* class_linker = runtime->GetClassLinker();
997 Thread* self = Thread::Current();
998 StackHandleScope<3> hs(self);
999 Handle<Class> object_array_class(hs.NewHandle(
1000 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
1002 std::unordered_set<const DexFile*> image_dex_files;
1003 for (auto& pair : dex_file_oat_index_map_) {
1004 const DexFile* image_dex_file = pair.first;
1005 size_t image_oat_index = pair.second;
1006 if (oat_index == image_oat_index) {
1007 image_dex_files.insert(image_dex_file);
1011 // build an Object[] of all the DexCaches used in the source_space_.
1012 // Since we can't hold the dex lock when allocating the dex_caches
1013 // ObjectArray, we lock the dex lock twice, first to get the number
1014 // of dex caches first and then lock it again to copy the dex
1015 // caches. We check that the number of dex caches does not change.
1016 size_t dex_cache_count = 0;
1018 ReaderMutexLock mu(self, *class_linker->DexLock());
1019 // Count number of dex caches not in the boot image.
1020 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1021 mirror::DexCache* dex_cache =
1022 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1023 const DexFile* dex_file = dex_cache->GetDexFile();
1024 if (!IsInBootImage(dex_cache)) {
1025 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1029 Handle<ObjectArray<Object>> dex_caches(
1030 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
1031 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1033 ReaderMutexLock mu(self, *class_linker->DexLock());
1034 size_t non_image_dex_caches = 0;
1035 // Re-count number of non image dex caches.
1036 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1037 mirror::DexCache* dex_cache =
1038 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1039 const DexFile* dex_file = dex_cache->GetDexFile();
1040 if (!IsInBootImage(dex_cache)) {
1041 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1044 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1045 << "The number of non-image dex caches changed.";
1047 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1048 mirror::DexCache* dex_cache =
1049 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1050 const DexFile* dex_file = dex_cache->GetDexFile();
1051 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
1052 dex_caches->Set<false>(i, dex_cache);
1058 // build an Object[] of the roots needed to restore the runtime
1059 auto image_roots(hs.NewHandle(
1060 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
1061 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
1062 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
1063 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
1064 CHECK(image_roots->Get(i) != nullptr);
1066 return image_roots.Get();
1069 // Walk instance fields of the given Class. Separate function to allow recursion on the super
1071 void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1072 // Visit fields of parent classes first.
1073 StackHandleScope<1> hs(Thread::Current());
1074 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1075 mirror::Class* super = h_class->GetSuperClass();
1076 if (super != nullptr) {
1077 WalkInstanceFields(obj, super);
1080 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
1081 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
1082 for (size_t i = 0; i < num_reference_fields; ++i) {
1083 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
1084 if (value != nullptr) {
1085 WalkFieldsInOrder(value);
1087 field_offset = MemberOffset(field_offset.Uint32Value() +
1088 sizeof(mirror::HeapReference<mirror::Object>));
1092 // For an unvisited object, visit it then all its children found via fields.
1093 void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
1094 if (IsInBootImage(obj)) {
1095 // Object is in the image, don't need to fix it up.
1098 // Use our own visitor routine (instead of GC visitor) to get better locality between
1099 // an object and its fields
1100 if (!IsImageBinSlotAssigned(obj)) {
1101 // Walk instance fields of all objects
1102 StackHandleScope<2> hs(Thread::Current());
1103 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1104 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
1105 // visit the object itself.
1106 CalculateObjectBinSlots(h_obj.Get());
1107 WalkInstanceFields(h_obj.Get(), klass.Get());
1108 // Walk static fields of a Class.
1109 if (h_obj->IsClass()) {
1110 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
1111 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
1112 for (size_t i = 0; i < num_reference_static_fields; ++i) {
1113 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
1114 if (value != nullptr) {
1115 WalkFieldsInOrder(value);
1117 field_offset = MemberOffset(field_offset.Uint32Value() +
1118 sizeof(mirror::HeapReference<mirror::Object>));
1120 // Visit and assign offsets for fields and field arrays.
1121 auto* as_klass = h_obj->AsClass();
1122 mirror::DexCache* dex_cache = as_klass->GetDexCache();
1123 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1124 if (compile_app_image_) {
1125 // Extra sanity, no boot loader classes should be left!
1126 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1128 LengthPrefixedArray<ArtField>* fields[] = {
1129 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1131 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1132 ImageInfo& image_info = GetImageInfo(oat_index);
1134 // Note: This table is only accessed from the image writer, so the lock is technically
1136 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1137 // Insert in the class table for this iamge.
1138 image_info.class_table_->Insert(as_klass);
1140 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1141 // Total array length including header.
1142 if (cur_fields != nullptr) {
1143 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1144 // Forward the entire array at once.
1145 auto it = native_object_relocations_.find(cur_fields);
1146 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1147 << " already forwarded";
1148 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
1149 DCHECK(!IsInBootImage(cur_fields));
1150 native_object_relocations_.emplace(
1152 NativeObjectRelocation {
1153 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1155 offset += header_size;
1156 // Forward individual fields so that we can quickly find where they belong.
1157 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
1158 // Need to forward arrays separate of fields.
1159 ArtField* field = &cur_fields->At(i);
1160 auto it2 = native_object_relocations_.find(field);
1161 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1162 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
1163 DCHECK(!IsInBootImage(field));
1164 native_object_relocations_.emplace(
1166 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
1167 offset += sizeof(ArtField);
1171 // Visit and assign offsets for methods.
1172 size_t num_methods = as_klass->NumMethods();
1173 if (num_methods != 0) {
1174 bool any_dirty = false;
1175 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1176 if (WillMethodBeDirty(&m)) {
1181 NativeObjectRelocationType type = any_dirty
1182 ? kNativeObjectRelocationTypeArtMethodDirty
1183 : kNativeObjectRelocationTypeArtMethodClean;
1184 Bin bin_type = BinTypeForNativeRelocationType(type);
1185 // Forward the entire array at once, but header first.
1186 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1187 const size_t method_size = ArtMethod::Size(target_ptr_size_);
1188 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1191 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
1192 auto it = native_object_relocations_.find(array);
1193 CHECK(it == native_object_relocations_.end())
1194 << "Method array " << array << " already forwarded";
1195 size_t& offset = image_info.bin_slot_sizes_[bin_type];
1196 DCHECK(!IsInBootImage(array));
1197 native_object_relocations_.emplace(array,
1198 NativeObjectRelocation {
1201 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1202 : kNativeObjectRelocationTypeArtMethodArrayClean });
1203 offset += header_size;
1204 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1205 AssignMethodOffset(&m, type, oat_index);
1207 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
1209 } else if (h_obj->IsObjectArray()) {
1210 // Walk elements of an object array.
1211 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
1212 for (int32_t i = 0; i < length; i++) {
1213 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
1214 mirror::Object* value = obj_array->Get(i);
1215 if (value != nullptr) {
1216 WalkFieldsInOrder(value);
1219 } else if (h_obj->IsClassLoader()) {
1220 // Register the class loader if it has a class table.
1221 // The fake boot class loader should not get registered and we should end up with only one
1223 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1224 if (class_loader->GetClassTable() != nullptr) {
1225 class_loaders_.insert(class_loader);
1231 void ImageWriter::AssignMethodOffset(ArtMethod* method,
1232 NativeObjectRelocationType type,
1234 DCHECK(!IsInBootImage(method));
1235 auto it = native_object_relocations_.find(method);
1236 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
1237 << PrettyMethod(method);
1238 ImageInfo& image_info = GetImageInfo(oat_index);
1239 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1240 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
1241 offset += ArtMethod::Size(target_ptr_size_);
1244 void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1245 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1246 DCHECK(writer != nullptr);
1247 writer->WalkFieldsInOrder(obj);
1250 void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1251 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1252 DCHECK(writer != nullptr);
1253 if (!writer->IsInBootImage(obj)) {
1254 writer->UnbinObjectsIntoOffset(obj);
1258 void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
1259 DCHECK(!IsInBootImage(obj));
1260 CHECK(obj != nullptr);
1262 // We know the bin slot, and the total bin sizes for all objects by now,
1263 // so calculate the object's final image offset.
1265 DCHECK(IsImageBinSlotAssigned(obj));
1266 BinSlot bin_slot = GetImageBinSlot(obj);
1267 // Change the lockword from a bin slot into an offset
1268 AssignImageOffset(obj, bin_slot);
1271 void ImageWriter::CalculateNewObjectOffsets() {
1272 Thread* const self = Thread::Current();
1273 StackHandleScopeCollection handles(self);
1274 std::vector<Handle<ObjectArray<Object>>> image_roots;
1275 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1276 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
1279 auto* runtime = Runtime::Current();
1280 auto* heap = runtime->GetHeap();
1282 // Leave space for the header, but do not write it yet, we need to
1283 // know where image_roots is going to end up
1284 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
1286 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1287 heap->VisitObjects(WalkFieldsCallback, this);
1288 // Write the image runtime methods.
1289 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1290 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1291 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1292 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1293 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1294 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1295 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1296 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1298 // Add room for fake length prefixed array for holding the image methods.
1299 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1300 auto it = native_object_relocations_.find(&image_method_array_);
1301 CHECK(it == native_object_relocations_.end());
1302 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
1304 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
1305 if (!compile_app_image_) {
1306 native_object_relocations_.emplace(&image_method_array_,
1307 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
1309 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1310 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
1311 0, ArtMethod::Size(target_ptr_size_), method_alignment);
1312 CHECK_ALIGNED_PARAM(array_size, method_alignment);
1313 offset += array_size;
1314 for (auto* m : image_methods_) {
1315 CHECK(m != nullptr);
1316 CHECK(m->IsRuntimeMethod());
1317 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1318 if (!IsInBootImage(m)) {
1319 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
1322 // Calculate size of the dex cache arrays slot and prepare offsets.
1323 PrepareDexCacheArraySlots();
1325 // Calculate the sizes of the intern tables and class tables.
1326 for (ImageInfo& image_info : image_infos_) {
1327 // Calculate how big the intern table will be after being serialized.
1328 InternTable* const intern_table = image_info.intern_table_.get();
1329 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1330 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1331 // Calculate the size of the class table.
1332 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1333 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1336 // Calculate bin slot offsets.
1337 for (ImageInfo& image_info : image_infos_) {
1338 size_t bin_offset = image_objects_offset_begin_;
1339 for (size_t i = 0; i != kBinSize; ++i) {
1340 image_info.bin_slot_offsets_[i] = bin_offset;
1341 bin_offset += image_info.bin_slot_sizes_[i];
1342 if (i == kBinArtField) {
1343 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1344 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1345 DCHECK_ALIGNED(bin_offset, 4u);
1346 DCHECK(method_alignment == 4u || method_alignment == 8u);
1347 bin_offset = RoundUp(bin_offset, method_alignment);
1350 // NOTE: There may be additional padding between the bin slots and the intern table.
1351 DCHECK_EQ(image_info.image_end_,
1352 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
1355 // Calculate image offsets.
1356 size_t image_offset = 0;
1357 for (ImageInfo& image_info : image_infos_) {
1358 image_info.image_begin_ = global_image_begin_ + image_offset;
1359 image_info.image_offset_ = image_offset;
1360 ImageSection unused_sections[ImageHeader::kSectionCount];
1361 image_info.image_size_ = RoundUp(
1362 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1364 // There should be no gaps until the next image.
1365 image_offset += image_info.image_size_;
1368 // Transform each object's bin slot into an offset which will be used to do the final copy.
1369 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
1371 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1374 for (ImageInfo& image_info : image_infos_) {
1375 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1379 // Update the native relocations by adding their bin sums.
1380 for (auto& pair : native_object_relocations_) {
1381 NativeObjectRelocation& relocation = pair.second;
1382 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
1383 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
1384 relocation.offset += image_info.bin_slot_offsets_[bin_type];
1387 // Note that image_info.image_end_ is left at end of used mirror object section.
1390 size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1391 ImageSection* out_sections) const {
1392 DCHECK(out_sections != nullptr);
1394 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1395 *objects_section = ImageSection(0u, image_end_);
1396 size_t cur_pos = objects_section->End();
1397 // Add field section.
1398 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1399 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1400 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1401 cur_pos = field_section->End();
1402 // Round up to the alignment the required by the method section.
1403 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1404 // Add method section.
1405 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1406 *methods_section = ImageSection(cur_pos,
1407 bin_slot_sizes_[kBinArtMethodClean] +
1408 bin_slot_sizes_[kBinArtMethodDirty]);
1409 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1410 cur_pos = methods_section->End();
1411 // Add dex cache arrays section.
1412 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1413 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1414 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1415 cur_pos = dex_cache_arrays_section->End();
1416 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1417 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1418 // Calculate the size of the interned strings.
1419 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1420 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1421 cur_pos = interned_strings_section->End();
1422 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1423 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1424 // Calculate the size of the class table section.
1425 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
1426 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
1427 cur_pos = class_table_section->End();
1428 // Image end goes right before the start of the image bitmap.
1432 void ImageWriter::CreateHeader(size_t oat_index) {
1433 ImageInfo& image_info = GetImageInfo(oat_index);
1434 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1435 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1436 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
1438 // Create the image sections.
1439 ImageSection sections[ImageHeader::kSectionCount];
1440 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1442 // Finally bitmap section.
1443 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
1444 auto* bitmap_section = §ions[ImageHeader::kSectionImageBitmap];
1445 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1446 if (VLOG_IS_ON(compiler)) {
1447 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
1449 for (const ImageSection& section : sections) {
1450 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1453 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1454 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1455 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1456 << " Image offset=" << image_info.image_offset_ << std::dec;
1457 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1458 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1459 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1460 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
1462 // Store boot image info for app image so that we can relocate.
1463 uint32_t boot_image_begin = 0;
1464 uint32_t boot_image_end = 0;
1465 uint32_t boot_oat_begin = 0;
1466 uint32_t boot_oat_end = 0;
1467 gc::Heap* const heap = Runtime::Current()->GetHeap();
1468 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1470 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1472 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1475 image_info.image_roots_address_,
1476 image_info.oat_checksum_,
1477 PointerToLowMemUInt32(oat_file_begin),
1478 PointerToLowMemUInt32(image_info.oat_data_begin_),
1479 PointerToLowMemUInt32(oat_data_end),
1480 PointerToLowMemUInt32(oat_file_end),
1482 boot_image_end - boot_image_begin,
1484 boot_oat_end - boot_oat_begin,
1487 /*is_pic*/compile_app_image_,
1488 image_storage_mode_,
1492 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
1493 auto it = native_object_relocations_.find(method);
1494 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
1495 size_t oat_index = GetOatIndex(method->GetDexCache());
1496 ImageInfo& image_info = GetImageInfo(oat_index);
1497 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1498 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
1501 class FixupRootVisitor : public RootVisitor {
1503 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1506 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
1507 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1508 for (size_t i = 0; i < count; ++i) {
1509 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
1513 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1514 const RootInfo& info ATTRIBUTE_UNUSED)
1515 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1516 for (size_t i = 0; i < count; ++i) {
1517 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
1522 ImageWriter* const image_writer_;
1525 void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1526 ImageInfo& image_info = GetImageInfo(oat_index);
1527 // Copy ArtFields and methods to their locations and update the array for convenience.
1528 for (auto& pair : native_object_relocations_) {
1529 NativeObjectRelocation& relocation = pair.second;
1530 // Only work with fields and methods that are in the current oat file.
1531 if (relocation.oat_index != oat_index) {
1534 auto* dest = image_info.image_->Begin() + relocation.offset;
1535 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
1536 DCHECK(!IsInBootImage(pair.first));
1537 switch (relocation.type) {
1538 case kNativeObjectRelocationTypeArtField: {
1539 memcpy(dest, pair.first, sizeof(ArtField));
1540 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1541 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1544 case kNativeObjectRelocationTypeArtMethodClean:
1545 case kNativeObjectRelocationTypeArtMethodDirty: {
1546 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1547 reinterpret_cast<ArtMethod*>(dest),
1551 // For arrays, copy just the header since the elements will get copied by their corresponding
1553 case kNativeObjectRelocationTypeArtFieldArray: {
1554 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1557 case kNativeObjectRelocationTypeArtMethodArrayClean:
1558 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
1559 size_t size = ArtMethod::Size(target_ptr_size_);
1560 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1561 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1562 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1563 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
1566 case kNativeObjectRelocationTypeDexCacheArray:
1567 // Nothing to copy here, everything is done in FixupDexCache().
1571 // Fixup the image method roots.
1572 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
1573 const ImageSection& methods_section = image_header->GetMethodsSection();
1574 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
1575 ArtMethod* method = image_methods_[i];
1576 CHECK(method != nullptr);
1577 // Only place runtime methods in the image of the default oat file.
1578 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
1581 if (!IsInBootImage(method)) {
1582 auto it = native_object_relocations_.find(method);
1583 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
1584 NativeObjectRelocation& relocation = it->second;
1585 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1587 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1588 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
1590 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
1592 FixupRootVisitor root_visitor(this);
1594 // Write the intern table into the image.
1595 if (image_info.intern_table_bytes_ > 0) {
1596 const ImageSection& intern_table_section = image_header->GetImageSection(
1597 ImageHeader::kSectionInternedStrings);
1598 InternTable* const intern_table = image_info.intern_table_.get();
1599 uint8_t* const intern_table_memory_ptr =
1600 image_info.image_->Begin() + intern_table_section.Offset();
1601 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1602 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1603 // Fixup the pointers in the newly written intern table to contain image addresses.
1604 InternTable temp_intern_table;
1605 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1606 // the VisitRoots() will update the memory directly rather than the copies.
1607 // This also relies on visit roots not doing any verification which could fail after we update
1608 // the roots to be the image addresses.
1609 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1610 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1611 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1613 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1614 // class loaders. Writing multiple class tables into the image is currently unsupported.
1615 if (image_info.class_table_bytes_ > 0u) {
1616 const ImageSection& class_table_section = image_header->GetImageSection(
1617 ImageHeader::kSectionClassTable);
1618 uint8_t* const class_table_memory_ptr =
1619 image_info.image_->Begin() + class_table_section.Offset();
1620 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1622 ClassTable* table = image_info.class_table_.get();
1623 CHECK(table != nullptr);
1624 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1625 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1626 // Fixup the pointers in the newly written class table to contain image addresses. See
1627 // above comment for intern tables.
1628 ClassTable temp_class_table;
1629 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1630 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1631 table->NumZygoteClasses());
1632 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1633 RootInfo(kRootUnknown));
1634 temp_class_table.VisitRoots(buffered_visitor);
1638 void ImageWriter::CopyAndFixupObjects() {
1639 gc::Heap* heap = Runtime::Current()->GetHeap();
1640 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1641 // Fix up the object previously had hash codes.
1642 for (const auto& hash_pair : saved_hashcode_map_) {
1643 Object* obj = hash_pair.first;
1644 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1645 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
1647 saved_hashcode_map_.clear();
1650 void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
1651 DCHECK(obj != nullptr);
1652 DCHECK(arg != nullptr);
1653 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1656 void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1657 mirror::Class* klass, Bin array_type) {
1658 CHECK(klass->IsArrayClass());
1659 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1660 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
1661 const size_t num_elements = arr->GetLength();
1662 dst->SetClass(GetImageAddress(arr->GetClass()));
1663 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
1664 for (size_t i = 0, count = num_elements; i < count; ++i) {
1665 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1666 if (elem != nullptr && !IsInBootImage(elem)) {
1667 auto it = native_object_relocations_.find(elem);
1668 if (UNLIKELY(it == native_object_relocations_.end())) {
1669 if (it->second.IsArtMethodRelocation()) {
1670 auto* method = reinterpret_cast<ArtMethod*>(elem);
1671 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1672 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1673 << PrettyClass(method->GetDeclaringClass());
1675 CHECK_EQ(array_type, kBinArtField);
1676 auto* field = reinterpret_cast<ArtField*>(elem);
1677 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1678 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1679 << PrettyClass(field->GetDeclaringClass());
1683 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
1684 elem = image_info.image_begin_ + it->second.offset;
1687 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
1691 void ImageWriter::CopyAndFixupObject(Object* obj) {
1692 if (IsInBootImage(obj)) {
1695 size_t offset = GetImageOffset(obj);
1696 size_t oat_index = GetOatIndex(obj);
1697 ImageInfo& image_info = GetImageInfo(oat_index);
1698 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1699 DCHECK_LT(offset, image_info.image_end_);
1700 const auto* src = reinterpret_cast<const uint8_t*>(obj);
1702 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
1704 const size_t n = obj->SizeOf();
1705 DCHECK_LE(offset + n, image_info.image_->Size());
1706 memcpy(dst, src, n);
1708 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1710 const auto it = saved_hashcode_map_.find(obj);
1711 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1712 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
1713 FixupObject(obj, dst);
1716 // Rewrite all the references in the copied object to point to their image address equivalent
1717 class FixupVisitor {
1719 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1722 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1723 // with other logic.
1724 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1726 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1729 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
1730 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1731 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
1732 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1734 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1736 image_writer_->GetImageAddress(ref));
1739 // java.lang.ref.Reference visitor.
1740 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
1741 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1742 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1743 mirror::Reference::ReferentOffset(),
1744 image_writer_->GetImageAddress(ref->GetReferent()));
1748 ImageWriter* const image_writer_;
1749 mirror::Object* const copy_;
1752 class FixupClassVisitor FINAL : public FixupVisitor {
1754 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1757 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
1758 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1759 DCHECK(obj->IsClass());
1760 FixupVisitor::operator()(obj, offset, /*is_static*/false);
1763 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1764 mirror::Reference* ref ATTRIBUTE_UNUSED) const
1765 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1766 LOG(FATAL) << "Reference not expected here.";
1770 uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1771 DCHECK(obj != nullptr);
1772 DCHECK(!IsInBootImage(obj));
1773 auto it = native_object_relocations_.find(obj);
1774 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1775 << Runtime::Current()->GetHeap()->DumpSpaces();
1776 const NativeObjectRelocation& relocation = it->second;
1777 return relocation.offset;
1780 template <typename T>
1781 T* ImageWriter::NativeLocationInImage(T* obj) {
1782 if (obj == nullptr || IsInBootImage(obj)) {
1785 auto it = native_object_relocations_.find(obj);
1786 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1787 << Runtime::Current()->GetHeap()->DumpSpaces();
1788 const NativeObjectRelocation& relocation = it->second;
1789 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
1790 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
1794 template <typename T>
1795 T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1796 if (obj == nullptr || IsInBootImage(obj)) {
1799 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1800 ImageInfo& image_info = GetImageInfo(oat_index);
1801 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1805 class NativeLocationVisitor {
1807 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1809 template <typename T>
1810 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1811 return image_writer_->NativeLocationInImage(ptr);
1815 ImageWriter* const image_writer_;
1818 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1819 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
1820 FixupClassVisitor visitor(this, copy);
1821 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
1823 // Remove the clinitThreadId. This is required for image determinism.
1824 copy->SetClinitThreadId(static_cast<pid_t>(0));
1827 void ImageWriter::FixupObject(Object* orig, Object* copy) {
1828 DCHECK(orig != nullptr);
1829 DCHECK(copy != nullptr);
1830 if (kUseBakerOrBrooksReadBarrier) {
1831 orig->AssertReadBarrierPointer();
1832 if (kUseBrooksReadBarrier) {
1833 // Note the address 'copy' isn't the same as the image address of 'orig'.
1834 copy->SetReadBarrierPointer(GetImageAddress(orig));
1835 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1838 auto* klass = orig->GetClass();
1839 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
1840 // Is this a native pointer array?
1841 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1842 if (it != pointer_arrays_.end()) {
1843 // Should only need to fixup every pointer array exactly once.
1844 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1845 pointer_arrays_.erase(it);
1849 if (orig->IsClass()) {
1850 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
1852 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1853 // Need to go update the ArtMethod.
1854 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1855 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1856 ArtMethod* src_method = src->GetArtMethod();
1857 auto it = native_object_relocations_.find(src_method);
1858 CHECK(it != native_object_relocations_.end())
1859 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
1861 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
1862 } else if (!klass->IsArrayClass()) {
1863 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1864 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1865 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1866 } else if (klass->IsClassLoaderClass()) {
1867 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
1868 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1870 copy_loader->SetClassTable(nullptr);
1871 // Also set allocator to null to be safe. The allocator is created when we create the class
1872 // table. We also never expect to unload things in the image since they are held live as
1874 copy_loader->SetAllocator(nullptr);
1877 FixupVisitor visitor(this, copy);
1878 orig->VisitReferences(visitor, visitor);
1883 class ImageAddressVisitor {
1885 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1887 template <typename T>
1888 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1889 return image_writer_->GetImageAddress(ptr);
1893 ImageWriter* const image_writer_;
1897 void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1898 mirror::DexCache* copy_dex_cache) {
1899 // Though the DexCache array fields are usually treated as native pointers, we set the full
1900 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1901 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1902 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1903 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1904 if (orig_strings != nullptr) {
1905 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1906 NativeLocationInImage(orig_strings),
1907 /*pointer size*/8u);
1908 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1909 ImageAddressVisitor(this));
1911 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1912 if (orig_types != nullptr) {
1913 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1914 NativeLocationInImage(orig_types),
1915 /*pointer size*/8u);
1916 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1917 ImageAddressVisitor(this));
1919 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1920 if (orig_methods != nullptr) {
1921 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1922 NativeLocationInImage(orig_methods),
1923 /*pointer size*/8u);
1924 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
1925 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1926 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
1927 // NativeLocationInImage also handles runtime methods since these have relocation info.
1928 ArtMethod* copy = NativeLocationInImage(orig);
1929 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1932 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1933 if (orig_fields != nullptr) {
1934 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
1935 NativeLocationInImage(orig_fields),
1936 /*pointer size*/8u);
1937 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
1938 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1939 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
1940 ArtField* copy = NativeLocationInImage(orig);
1941 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1945 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1946 // compiler pointers in here will make the output non-deterministic.
1947 copy_dex_cache->SetDexFile(nullptr);
1950 const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1951 DCHECK_LT(type, kOatAddressCount);
1952 // If we are compiling an app image, we need to use the stubs of the boot image.
1953 if (compile_app_image_) {
1954 // Use the current image pointers.
1955 const std::vector<gc::space::ImageSpace*>& image_spaces =
1956 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1957 DCHECK(!image_spaces.empty());
1958 const OatFile* oat_file = image_spaces[0]->GetOatFile();
1959 CHECK(oat_file != nullptr);
1960 const OatHeader& header = oat_file->GetOatHeader();
1962 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1963 case kOatAddressQuickGenericJNITrampoline:
1964 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1965 case kOatAddressInterpreterToInterpreterBridge:
1966 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1967 case kOatAddressInterpreterToCompiledCodeBridge:
1968 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1969 case kOatAddressJNIDlsymLookup:
1970 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1971 case kOatAddressQuickIMTConflictTrampoline:
1972 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1973 case kOatAddressQuickResolutionTrampoline:
1974 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1975 case kOatAddressQuickToInterpreterBridge:
1976 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1981 const ImageInfo& primary_image_info = GetImageInfo(0);
1982 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
1985 const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1986 const ImageInfo& image_info,
1987 bool* quick_is_interpreted) {
1988 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1989 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
1990 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
1991 DCHECK(method->IsInvokable()) << PrettyMethod(method);
1992 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
1994 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1997 // Quick entrypoint:
1998 const void* quick_oat_entry_point =
1999 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2000 const uint8_t* quick_code;
2002 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2003 DCHECK(method->IsCopied());
2004 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2005 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2007 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2008 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2011 *quick_is_interpreted = false;
2012 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2013 method->GetDeclaringClass()->IsInitialized())) {
2014 // We have code for a non-static or initialized method, just use the code.
2015 } else if (quick_code == nullptr && method->IsNative() &&
2016 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2017 // Non-static or initialized native method missing compiled code, use generic JNI version.
2018 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
2019 } else if (quick_code == nullptr && !method->IsNative()) {
2020 // We don't have code at all for a non-native method, use the interpreter.
2021 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
2022 *quick_is_interpreted = true;
2024 CHECK(!method->GetDeclaringClass()->IsInitialized());
2025 // We have code for a static method, but need to go through the resolution stub for class
2027 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2029 if (!IsInBootOatFile(quick_code)) {
2030 // DCHECK_GE(quick_code, oat_data_begin_);
2035 void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2037 const ImageInfo& image_info) {
2038 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
2040 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
2041 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
2042 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
2043 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
2044 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
2046 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2049 // The resolution method has a special trampoline to call.
2050 Runtime* runtime = Runtime::Current();
2051 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2052 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2053 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2054 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2055 orig == runtime->GetImtUnimplementedMethod())) {
2056 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2057 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2058 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2059 bool found_one = false;
2060 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2061 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2062 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2067 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2068 CHECK(copy->IsRuntimeMethod());
2070 // We assume all methods have code. If they don't currently then we set them to the use the
2071 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2072 // use results in an AbstractMethodError. We use the interpreter to achieve this.
2073 if (UNLIKELY(!orig->IsInvokable())) {
2074 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2075 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
2077 bool quick_is_interpreted;
2078 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
2079 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
2082 if (orig->IsNative()) {
2083 // The native method's pointer is set to a stub to lookup via dlsym.
2084 // Note this is not the code_ pointer, that is handled above.
2085 copy->SetEntryPointFromJniPtrSize(
2086 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
2092 size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
2093 DCHECK_LE(up_to, kBinSize);
2094 return std::accumulate(&image_info.bin_slot_sizes_[0],
2095 &image_info.bin_slot_sizes_[up_to],
2099 ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2100 // These values may need to get updated if more bins are added to the enum Bin
2101 static_assert(kBinBits == 3, "wrong number of bin bits");
2102 static_assert(kBinShift == 27, "wrong number of shift");
2103 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2105 DCHECK_LT(GetBin(), kBinSize);
2106 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2109 ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2110 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2111 DCHECK_EQ(index, GetIndex());
2114 ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2115 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2118 uint32_t ImageWriter::BinSlot::GetIndex() const {
2119 return lockword_ & ~kBinMask;
2122 ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2124 case kNativeObjectRelocationTypeArtField:
2125 case kNativeObjectRelocationTypeArtFieldArray:
2126 return kBinArtField;
2127 case kNativeObjectRelocationTypeArtMethodClean:
2128 case kNativeObjectRelocationTypeArtMethodArrayClean:
2129 return kBinArtMethodClean;
2130 case kNativeObjectRelocationTypeArtMethodDirty:
2131 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2132 return kBinArtMethodDirty;
2133 case kNativeObjectRelocationTypeDexCacheArray:
2134 return kBinDexCacheArray;
2139 size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
2140 if (compile_app_image_) {
2141 return GetDefaultOatIndex();
2143 mirror::DexCache* dex_cache =
2144 obj->IsDexCache() ? obj->AsDexCache()
2145 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2146 : obj->GetClass()->GetDexCache();
2147 return GetOatIndexForDexCache(dex_cache);
2151 size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2152 if (compile_app_image_) {
2153 return GetDefaultOatIndex();
2155 auto it = dex_file_oat_index_map_.find(dex_file);
2156 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2161 size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2162 if (dex_cache == nullptr) {
2163 return GetDefaultOatIndex();
2165 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2169 void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2170 size_t oat_loaded_size,
2171 size_t oat_data_offset,
2172 size_t oat_data_size) {
2173 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2174 for (const ImageInfo& info : image_infos_) {
2175 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2177 DCHECK(images_end != nullptr); // Image space must be ready.
2179 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2180 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2181 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2182 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2183 cur_image_info.oat_size_ = oat_data_size;
2185 if (compile_app_image_) {
2186 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2190 // Update the oat_offset of the next image info.
2191 if (oat_index + 1u != oat_filenames_.size()) {
2192 // There is a following one.
2193 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
2194 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2198 void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2199 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2200 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2202 if (oat_index == GetDefaultOatIndex()) {
2203 // Primary oat file, read the trampolines.
2204 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2205 oat_header.GetInterpreterToInterpreterBridgeOffset();
2206 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2207 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2208 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2209 oat_header.GetJniDlsymLookupOffset();
2210 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2211 oat_header.GetQuickGenericJniTrampolineOffset();
2212 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2213 oat_header.GetQuickImtConflictTrampolineOffset();
2214 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2215 oat_header.GetQuickResolutionTrampolineOffset();
2216 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2217 oat_header.GetQuickToInterpreterBridgeOffset();
2221 ImageWriter::ImageWriter(
2222 const CompilerDriver& compiler_driver,
2223 uintptr_t image_begin,
2225 bool compile_app_image,
2226 ImageHeader::StorageMode image_storage_mode,
2227 const std::vector<const char*>& oat_filenames,
2228 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
2229 : compiler_driver_(compiler_driver),
2230 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2231 image_objects_offset_begin_(0),
2232 compile_pic_(compile_pic),
2233 compile_app_image_(compile_app_image),
2234 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2235 image_infos_(oat_filenames.size()),
2236 image_method_array_(ImageHeader::kImageMethodsCount),
2239 image_storage_mode_(image_storage_mode),
2240 oat_filenames_(oat_filenames),
2241 dex_file_oat_index_map_(dex_file_oat_index_map) {
2242 CHECK_NE(image_begin, 0U);
2243 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2244 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2245 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
2248 ImageWriter::ImageInfo::ImageInfo()
2249 : intern_table_(new InternTable),
2250 class_table_(new ClassTable) {}