blob: 51edca47b45464839198bbe779394bddb86212a2 [file] [log] [blame]
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "image_writer.h"
#include <lz4.h>
#include <lz4hc.h>
#include <sys/stat.h>
#include <zlib.h>
#include <memory>
#include <numeric>
#include <unordered_set>
#include <vector>
#include "art_field-inl.h"
#include "art_method-inl.h"
#include "base/callee_save_type.h"
#include "base/enums.h"
#include "base/globals.h"
#include "base/logging.h" // For VLOG.
#include "base/stl_util.h"
#include "base/unix_file/fd_file.h"
#include "class_linker-inl.h"
#include "class_root.h"
#include "compiled_method.h"
#include "dex/dex_file-inl.h"
#include "dex/dex_file_types.h"
#include "driver/compiler_options.h"
#include "elf/elf_utils.h"
#include "elf_file.h"
#include "entrypoints/entrypoint_utils-inl.h"
#include "gc/accounting/card_table-inl.h"
#include "gc/accounting/heap_bitmap.h"
#include "gc/accounting/space_bitmap-inl.h"
#include "gc/collector/concurrent_copying.h"
#include "gc/heap-visit-objects-inl.h"
#include "gc/heap.h"
#include "gc/space/large_object_space.h"
#include "gc/space/region_space.h"
#include "gc/space/space-inl.h"
#include "gc/verification.h"
#include "handle_scope-inl.h"
#include "image-inl.h"
#include "imt_conflict_table.h"
#include "intern_table-inl.h"
#include "jni/jni_internal.h"
#include "linear_alloc.h"
#include "lock_word.h"
#include "mirror/array-inl.h"
#include "mirror/class-inl.h"
#include "mirror/class_ext-inl.h"
#include "mirror/class_loader.h"
#include "mirror/dex_cache-inl.h"
#include "mirror/dex_cache.h"
#include "mirror/executable.h"
#include "mirror/method.h"
#include "mirror/object-inl.h"
#include "mirror/object-refvisitor-inl.h"
#include "mirror/object_array-alloc-inl.h"
#include "mirror/object_array-inl.h"
#include "mirror/string-inl.h"
#include "oat.h"
#include "oat_file.h"
#include "oat_file_manager.h"
#include "optimizing/intrinsic_objects.h"
#include "runtime.h"
#include "scoped_thread_state_change-inl.h"
#include "subtype_check.h"
#include "utils/dex_cache_arrays_layout-inl.h"
#include "well_known_classes.h"
using ::art::mirror::Class;
using ::art::mirror::DexCache;
using ::art::mirror::Object;
using ::art::mirror::ObjectArray;
using ::art::mirror::String;
namespace art {
namespace linker {
static ArrayRef<const uint8_t> MaybeCompressData(ArrayRef<const uint8_t> source,
ImageHeader::StorageMode image_storage_mode,
/*out*/ std::vector<uint8_t>* storage) {
const uint64_t compress_start_time = NanoTime();
switch (image_storage_mode) {
case ImageHeader::kStorageModeLZ4: {
storage->resize(LZ4_compressBound(source.size()));
size_t data_size = LZ4_compress_default(
reinterpret_cast<char*>(const_cast<uint8_t*>(source.data())),
reinterpret_cast<char*>(storage->data()),
source.size(),
storage->size());
storage->resize(data_size);
break;
}
case ImageHeader::kStorageModeLZ4HC: {
// Bound is same as non HC.
storage->resize(LZ4_compressBound(source.size()));
size_t data_size = LZ4_compress_HC(
reinterpret_cast<const char*>(const_cast<uint8_t*>(source.data())),
reinterpret_cast<char*>(storage->data()),
source.size(),
storage->size(),
LZ4HC_CLEVEL_MAX);
storage->resize(data_size);
break;
}
case ImageHeader::kStorageModeUncompressed: {
return source;
}
default: {
LOG(FATAL) << "Unsupported";
UNREACHABLE();
}
}
DCHECK(image_storage_mode == ImageHeader::kStorageModeLZ4 ||
image_storage_mode == ImageHeader::kStorageModeLZ4HC);
VLOG(compiler) << "Compressed from " << source.size() << " to " << storage->size() << " in "
<< PrettyDuration(NanoTime() - compress_start_time);
if (kIsDebugBuild) {
std::vector<uint8_t> decompressed(source.size());
const size_t decompressed_size = LZ4_decompress_safe(
reinterpret_cast<char*>(storage->data()),
reinterpret_cast<char*>(decompressed.data()),
storage->size(),
decompressed.size());
CHECK_EQ(decompressed_size, decompressed.size());
CHECK_EQ(memcmp(source.data(), decompressed.data(), source.size()), 0) << image_storage_mode;
}
return ArrayRef<const uint8_t>(*storage);
}
// Separate objects into multiple bins to optimize dirty memory use.
static constexpr bool kBinObjects = true;
ObjPtr<mirror::ObjectArray<mirror::Object>> AllocateBootImageLiveObjects(
Thread* self, Runtime* runtime) REQUIRES_SHARED(Locks::mutator_lock_) {
ClassLinker* class_linker = runtime->GetClassLinker();
// The objects used for the Integer.valueOf() intrinsic must remain live even if references
// to them are removed using reflection. Image roots are not accessible through reflection,
// so the array we construct here shall keep them alive.
StackHandleScope<1> hs(self);
Handle<mirror::ObjectArray<mirror::Object>> integer_cache =
hs.NewHandle(IntrinsicObjects::LookupIntegerCache(self, class_linker));
size_t live_objects_size =
enum_cast<size_t>(ImageHeader::kIntrinsicObjectsStart) +
((integer_cache != nullptr) ? (/* cache */ 1u + integer_cache->GetLength()) : 0u);
ObjPtr<mirror::ObjectArray<mirror::Object>> live_objects =
mirror::ObjectArray<mirror::Object>::Alloc(
self, GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker), live_objects_size);
int32_t index = 0u;
auto set_entry = [&](ImageHeader::BootImageLiveObjects entry,
ObjPtr<mirror::Object> value) REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK_EQ(index, enum_cast<int32_t>(entry));
live_objects->Set</*kTransacrionActive=*/ false>(index, value);
++index;
};
set_entry(ImageHeader::kOomeWhenThrowingException,
runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
set_entry(ImageHeader::kOomeWhenThrowingOome,
runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
set_entry(ImageHeader::kOomeWhenHandlingStackOverflow,
runtime->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
set_entry(ImageHeader::kNoClassDefFoundError, runtime->GetPreAllocatedNoClassDefFoundError());
set_entry(ImageHeader::kClearedJniWeakSentinel, runtime->GetSentinel().Read());
DCHECK_EQ(index, enum_cast<int32_t>(ImageHeader::kIntrinsicObjectsStart));
if (integer_cache != nullptr) {
live_objects->Set(index++, integer_cache.Get());
for (int32_t i = 0, length = integer_cache->GetLength(); i != length; ++i) {
live_objects->Set(index++, integer_cache->Get(i));
}
}
CHECK_EQ(index, live_objects->GetLength());
if (kIsDebugBuild && integer_cache != nullptr) {
CHECK_EQ(integer_cache.Get(), IntrinsicObjects::GetIntegerValueOfCache(live_objects));
for (int32_t i = 0, len = integer_cache->GetLength(); i != len; ++i) {
CHECK_EQ(integer_cache->GetWithoutChecks(i),
IntrinsicObjects::GetIntegerValueOfObject(live_objects, i));
}
}
return live_objects;
}
ObjPtr<mirror::ClassLoader> ImageWriter::GetAppClassLoader() const
REQUIRES_SHARED(Locks::mutator_lock_) {
return compiler_options_.IsAppImage()
? ObjPtr<mirror::ClassLoader>::DownCast(Thread::Current()->DecodeJObject(app_class_loader_))
: nullptr;
}
bool ImageWriter::IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
// For boot image, we keep all dex caches.
if (compiler_options_.IsBootImage()) {
return true;
}
// Dex caches already in the boot image do not belong to the image being written.
if (IsInBootImage(dex_cache.Ptr())) {
return false;
}
// Dex caches for the boot class path components that are not part of the boot image
// cannot be garbage collected in PrepareImageAddressSpace() but we do not want to
// include them in the app image.
if (!ContainsElement(compiler_options_.GetDexFilesForOatFile(), dex_cache->GetDexFile())) {
return false;
}
return true;
}
static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK(obj != nullptr);
Class* klass = obj->GetClass();
if (klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile)) {
ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
// Null out the cookie to enable determinism. b/34090128
field->SetObject</*kTransactionActive*/false>(obj, nullptr);
}
};
Runtime::Current()->GetHeap()->VisitObjects(visitor);
}
bool ImageWriter::PrepareImageAddressSpace(bool preload_dex_caches, TimingLogger* timings) {
target_ptr_size_ = InstructionSetPointerSize(compiler_options_.GetInstructionSet());
Thread* const self = Thread::Current();
gc::Heap* const heap = Runtime::Current()->GetHeap();
{
ScopedObjectAccess soa(self);
{
TimingLogger::ScopedTiming t("PruneNonImageClasses", timings);
PruneNonImageClasses(); // Remove junk
}
if (compiler_options_.IsAppImage()) {
TimingLogger::ScopedTiming t("ClearDexFileCookies", timings);
// Clear dex file cookies for app images to enable app image determinism. This is required
// since the cookie field contains long pointers to DexFiles which are not deterministic.
// b/34090128
ClearDexFileCookies();
}
}
{
TimingLogger::ScopedTiming t("CollectGarbage", timings);
heap->CollectGarbage(/* clear_soft_references */ false); // Remove garbage.
}
if (kIsDebugBuild) {
ScopedObjectAccess soa(self);
CheckNonImageClassesRemoved();
}
{
// All remaining weak interns are referenced. Promote them to strong interns. Whether a
// string was strongly or weakly interned, we shall make it strongly interned in the image.
TimingLogger::ScopedTiming t("PromoteInterns", timings);
ScopedObjectAccess soa(self);
Runtime::Current()->GetInternTable()->PromoteWeakToStrong();
}
if (preload_dex_caches) {
TimingLogger::ScopedTiming t("PreloadDexCaches", timings);
// Preload deterministic contents to the dex cache arrays we're going to write.
ScopedObjectAccess soa(self);
ObjPtr<mirror::ClassLoader> class_loader = GetAppClassLoader();
std::vector<ObjPtr<mirror::DexCache>> dex_caches = FindDexCaches(self);
for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
if (!IsImageDexCache(dex_cache)) {
continue; // Boot image DexCache is not written to the app image.
}
PreloadDexCache(dex_cache, class_loader);
}
}
{
TimingLogger::ScopedTiming t("CalculateNewObjectOffsets", timings);
ScopedObjectAccess soa(self);
CalculateNewObjectOffsets();
}
// Obtain class count for debugging purposes
if (VLOG_IS_ON(compiler) && compiler_options_.IsAppImage()) {
ScopedObjectAccess soa(self);
size_t app_image_class_count = 0;
for (ImageInfo& info : image_infos_) {
info.class_table_->Visit([&](ObjPtr<mirror::Class> klass)
REQUIRES_SHARED(Locks::mutator_lock_) {
if (!IsInBootImage(klass.Ptr())) {
++app_image_class_count;
}
// Indicate that we would like to continue visiting classes.
return true;
});
}
VLOG(compiler) << "Dex2Oat:AppImage:classCount = " << app_image_class_count;
}
// This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
// bin size sums being calculated.
TimingLogger::ScopedTiming t("AllocMemory", timings);
return AllocMemory();
}
void ImageWriter::CopyMetadata() {
DCHECK(compiler_options_.IsAppImage());
CHECK_EQ(image_infos_.size(), 1u);
const ImageInfo& image_info = image_infos_.back();
std::vector<ImageSection> image_sections = image_info.CreateImageSections().second;
auto* sfo_section_base = reinterpret_cast<AppImageReferenceOffsetInfo*>(
image_info.image_.Begin() +
image_sections[ImageHeader::kSectionStringReferenceOffsets].Offset());
std::copy(image_info.string_reference_offsets_.begin(),
image_info.string_reference_offsets_.end(),
sfo_section_base);
}
bool ImageWriter::IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const {
return referred_obj != nullptr &&
!IsInBootImage(referred_obj.Ptr()) &&
referred_obj->IsString() &&
referred_obj == Runtime::Current()->GetInternTable()->LookupStrong(
Thread::Current(), referred_obj->AsString());
}
// Helper class that erases the image file if it isn't properly flushed and closed.
class ImageWriter::ImageFileGuard {
public:
ImageFileGuard() noexcept = default;
ImageFileGuard(ImageFileGuard&& other) noexcept = default;
ImageFileGuard& operator=(ImageFileGuard&& other) noexcept = default;
~ImageFileGuard() {
if (image_file_ != nullptr) {
// Failure, erase the image file.
image_file_->Erase();
}
}
void reset(File* image_file) {
image_file_.reset(image_file);
}
bool operator==(std::nullptr_t) {
return image_file_ == nullptr;
}
bool operator!=(std::nullptr_t) {
return image_file_ != nullptr;
}
File* operator->() const {
return image_file_.get();
}
bool WriteHeaderAndClose(const std::string& image_filename, const ImageHeader* image_header) {
// The header is uncompressed since it contains whether the image is compressed or not.
if (!image_file_->PwriteFully(image_header, sizeof(ImageHeader), 0)) {
PLOG(ERROR) << "Failed to write image file header " << image_filename;
return false;
}
// FlushCloseOrErase() takes care of erasing, so the destructor does not need
// to do that whether the FlushCloseOrErase() succeeds or fails.
std::unique_ptr<File> image_file = std::move(image_file_);
if (image_file->FlushCloseOrErase() != 0) {
PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
return false;
}
return true;
}
private:
std::unique_ptr<File> image_file_;
};
bool ImageWriter::Write(int image_fd,
const std::vector<std::string>& image_filenames,
size_t component_count) {
// If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
// oat_filenames.
CHECK(!image_filenames.empty());
if (image_fd != kInvalidFd) {
CHECK_EQ(image_filenames.size(), 1u);
}
DCHECK(!oat_filenames_.empty());
CHECK_EQ(image_filenames.size(), oat_filenames_.size());
Thread* const self = Thread::Current();
{
ScopedObjectAccess soa(self);
for (size_t i = 0; i < oat_filenames_.size(); ++i) {
CreateHeader(i, component_count);
CopyAndFixupNativeData(i);
}
}
{
// TODO: heap validation can't handle these fix up passes.
ScopedObjectAccess soa(self);
Runtime::Current()->GetHeap()->DisableObjectValidation();
CopyAndFixupObjects();
}
if (compiler_options_.IsAppImage()) {
CopyMetadata();
}
// Primary image header shall be written last for two reasons. First, this ensures
// that we shall not end up with a valid primary image and invalid secondary image.
// Second, its checksum shall include the checksums of the secondary images (XORed).
// This way only the primary image checksum needs to be checked to determine whether
// any of the images or oat files are out of date. (Oat file checksums are included
// in the image checksum calculation.)
ImageHeader* primary_header = reinterpret_cast<ImageHeader*>(image_infos_[0].image_.Begin());
ImageFileGuard primary_image_file;
for (size_t i = 0; i < image_filenames.size(); ++i) {
const std::string& image_filename = image_filenames[i];
ImageInfo& image_info = GetImageInfo(i);
ImageFileGuard image_file;
if (image_fd != kInvalidFd) {
// Ignore image_filename, it is supplied only for better diagnostic.
image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
// Empty the file in case it already exists.
if (image_file != nullptr) {
TEMP_FAILURE_RETRY(image_file->SetLength(0));
TEMP_FAILURE_RETRY(image_file->Flush());
}
} else {
image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
}
if (image_file == nullptr) {
LOG(ERROR) << "Failed to open image file " << image_filename;
return false;
}
// Make file world readable if we have created it, i.e. when not passed as file descriptor.
if (image_fd == -1 && !compiler_options_.IsAppImage() && fchmod(image_file->Fd(), 0644) != 0) {
PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
return false;
}
// Image data size excludes the bitmap and the header.
ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
// Block sources (from the image).
const bool is_compressed = image_storage_mode_ != ImageHeader::kStorageModeUncompressed;
std::vector<std::pair<uint32_t, uint32_t>> block_sources;
std::vector<ImageHeader::Block> blocks;
// Add a set of solid blocks such that no block is larger than the maximum size. A solid block
// is a block that must be decompressed all at once.
auto add_blocks = [&](uint32_t offset, uint32_t size) {
while (size != 0u) {
const uint32_t cur_size = std::min(size, compiler_options_.MaxImageBlockSize());
block_sources.emplace_back(offset, cur_size);
offset += cur_size;
size -= cur_size;
}
};
add_blocks(sizeof(ImageHeader), image_header->GetImageSize() - sizeof(ImageHeader));
// Checksum of compressed image data and header.
uint32_t image_checksum = adler32(0L, Z_NULL, 0);
image_checksum = adler32(image_checksum,
reinterpret_cast<const uint8_t*>(image_header),
sizeof(ImageHeader));
// Copy and compress blocks.
size_t out_offset = sizeof(ImageHeader);
for (const std::pair<uint32_t, uint32_t> block : block_sources) {
ArrayRef<const uint8_t> raw_image_data(image_info.image_.Begin() + block.first,
block.second);
std::vector<uint8_t> compressed_data;
ArrayRef<const uint8_t> image_data =
MaybeCompressData(raw_image_data, image_storage_mode_, &compressed_data);
if (!is_compressed) {
// For uncompressed, preserve alignment since the image will be directly mapped.
out_offset = block.first;
}
// Fill in the compressed location of the block.
blocks.emplace_back(ImageHeader::Block(
image_storage_mode_,
/*data_offset=*/ out_offset,
/*data_size=*/ image_data.size(),
/*image_offset=*/ block.first,
/*image_size=*/ block.second));
// Write out the image + fields + methods.
if (!image_file->PwriteFully(image_data.data(), image_data.size(), out_offset)) {
PLOG(ERROR) << "Failed to write image file data " << image_filename;
image_file->Erase();
return false;
}
out_offset += image_data.size();
image_checksum = adler32(image_checksum, image_data.data(), image_data.size());
}
// Write the block metadata directly after the image sections.
// Note: This is not part of the mapped image and is not preserved after decompressing, it's
// only used for image loading. For this reason, only write it out for compressed images.
if (is_compressed) {
// Align up since the compressed data is not necessarily aligned.
out_offset = RoundUp(out_offset, alignof(ImageHeader::Block));
CHECK(!blocks.empty());
const size_t blocks_bytes = blocks.size() * sizeof(blocks[0]);
if (!image_file->PwriteFully(&blocks[0], blocks_bytes, out_offset)) {
PLOG(ERROR) << "Failed to write image blocks " << image_filename;
image_file->Erase();
return false;
}
image_header->blocks_offset_ = out_offset;
image_header->blocks_count_ = blocks.size();
out_offset += blocks_bytes;
}
// Data size includes everything except the bitmap.
image_header->data_size_ = out_offset - sizeof(ImageHeader);
// Update and write the bitmap section. Note that the bitmap section is relative to the
// possibly compressed image.
ImageSection& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
// Align up since data size may be unaligned if the image is compressed.
out_offset = RoundUp(out_offset, kPageSize);
bitmap_section = ImageSection(out_offset, bitmap_section.Size());
if (!image_file->PwriteFully(image_info.image_bitmap_.Begin(),
bitmap_section.Size(),
bitmap_section.Offset())) {
PLOG(ERROR) << "Failed to write image file bitmap " << image_filename;
return false;
}
int err = image_file->Flush();
if (err < 0) {
PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
return false;
}
// Calculate the image checksum of the remaining data.
image_checksum = adler32(image_checksum,
reinterpret_cast<const uint8_t*>(image_info.image_bitmap_.Begin()),
bitmap_section.Size());
image_header->SetImageChecksum(image_checksum);
if (VLOG_IS_ON(compiler)) {
const size_t separately_written_section_size = bitmap_section.Size();
const size_t total_uncompressed_size = image_info.image_size_ +
separately_written_section_size;
const size_t total_compressed_size = out_offset + separately_written_section_size;
VLOG(compiler) << "Dex2Oat:uncompressedImageSize = " << total_uncompressed_size;
if (total_uncompressed_size != total_compressed_size) {
VLOG(compiler) << "Dex2Oat:compressedImageSize = " << total_compressed_size;
}
}
CHECK_EQ(bitmap_section.End(), static_cast<size_t>(image_file->GetLength()))
<< "Bitmap should be at the end of the file";
// Write header last in case the compiler gets killed in the middle of image writing.
// We do not want to have a corrupted image with a valid header.
// Delay the writing of the primary image header until after writing secondary images.
if (i == 0u) {
primary_image_file = std::move(image_file);
} else {
if (!image_file.WriteHeaderAndClose(image_filename, image_header)) {
return false;
}
// Update the primary image checksum with the secondary image checksum.
primary_header->SetImageChecksum(primary_header->GetImageChecksum() ^ image_checksum);
}
}
DCHECK(primary_image_file != nullptr);
if (!primary_image_file.WriteHeaderAndClose(image_filenames[0], primary_header)) {
return false;
}
return true;
}
size_t ImageWriter::GetImageOffset(mirror::Object* object, size_t oat_index) const {
BinSlot bin_slot = GetImageBinSlot(object, oat_index);
const ImageInfo& image_info = GetImageInfo(oat_index);
size_t offset = image_info.GetBinSlotOffset(bin_slot.GetBin()) + bin_slot.GetOffset();
DCHECK_LT(offset, image_info.image_end_);
return offset;
}
void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
DCHECK(object != nullptr);
DCHECK(!IsImageBinSlotAssigned(object));
// Before we stomp over the lock word, save the hash code for later.
LockWord lw(object->GetLockWord(false));
switch (lw.GetState()) {
case LockWord::kFatLocked:
FALLTHROUGH_INTENDED;
case LockWord::kThinLocked: {
std::ostringstream oss;
bool thin = (lw.GetState() == LockWord::kThinLocked);
oss << (thin ? "Thin" : "Fat")
<< " locked object " << object << "(" << object->PrettyTypeOf()
<< ") found during object copy";
if (thin) {
oss << ". Lock owner:" << lw.ThinLockOwner();
}
LOG(FATAL) << oss.str();
UNREACHABLE();
}
case LockWord::kUnlocked:
// No hash, don't need to save it.
break;
case LockWord::kHashCode:
DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
saved_hashcode_map_.emplace(object, lw.GetHashCode());
break;
default:
LOG(FATAL) << "Unreachable.";
UNREACHABLE();
}
object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()),
/*as_volatile=*/ false);
DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
DCHECK(IsImageBinSlotAssigned(object));
}
void ImageWriter::PrepareDexCacheArraySlots() {
// Prepare dex cache array starts based on the ordering specified in the CompilerOptions.
// Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
// when AssignImageBinSlot() assigns their indexes out or order.
for (const DexFile* dex_file : compiler_options_.GetDexFilesForOatFile()) {
auto it = dex_file_oat_index_map_.find(dex_file);
DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
ImageInfo& image_info = GetImageInfo(it->second);
image_info.dex_cache_array_starts_.Put(
dex_file, image_info.GetBinSlotSize(Bin::kDexCacheArray));
DexCacheArraysLayout layout(target_ptr_size_, dex_file);
image_info.IncrementBinSlotSize(Bin::kDexCacheArray, layout.Size());
}
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Thread* const self = Thread::Current();
ReaderMutexLock mu(self, *Locks::dex_lock_);
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
ObjPtr<mirror::DexCache> dex_cache =
ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
if (dex_cache == nullptr || !IsImageDexCache(dex_cache)) {
continue;
}
const DexFile* dex_file = dex_cache->GetDexFile();
CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
<< "Dex cache should have been pruned " << dex_file->GetLocation()
<< "; possibly in class path";
DexCacheArraysLayout layout(target_ptr_size_, dex_file);
// Empty dex files will not have a "valid" DexCacheArraysLayout.
if (dex_file->NumTypeIds() + dex_file->NumStringIds() + dex_file->NumMethodIds() +
dex_file->NumFieldIds() + dex_file->NumProtoIds() + dex_file->NumCallSiteIds() != 0) {
DCHECK(layout.Valid());
}
size_t oat_index = GetOatIndexForDexFile(dex_file);
ImageInfo& image_info = GetImageInfo(oat_index);
uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
start + layout.TypesOffset(),
oat_index);
DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
start + layout.MethodsOffset(),
oat_index);
DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
start + layout.FieldsOffset(),
oat_index);
DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), oat_index);
AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
start + layout.MethodTypesOffset(),
oat_index);
AddDexCacheArrayRelocation(dex_cache->GetResolvedCallSites(),
start + layout.CallSitesOffset(),
oat_index);
// Preresolved strings aren't part of the special layout.
GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
if (preresolved_strings != nullptr) {
DCHECK(!IsInBootImage(preresolved_strings));
// Add the array to the metadata section.
const size_t count = dex_cache->NumPreResolvedStrings();
auto bin = BinTypeForNativeRelocationType(NativeObjectRelocationType::kGcRootPointer);
for (size_t i = 0; i < count; ++i) {
native_object_relocations_.emplace(&preresolved_strings[i],
NativeObjectRelocation { oat_index,
image_info.GetBinSlotSize(bin),
NativeObjectRelocationType::kGcRootPointer });
image_info.IncrementBinSlotSize(bin, sizeof(GcRoot<mirror::Object>));
}
}
}
}
void ImageWriter::AddDexCacheArrayRelocation(void* array,
size_t offset,
size_t oat_index) {
if (array != nullptr) {
DCHECK(!IsInBootImage(array));
native_object_relocations_.emplace(array,
NativeObjectRelocation { oat_index, offset, NativeObjectRelocationType::kDexCacheArray });
}
}
void ImageWriter::AddMethodPointerArray(ObjPtr<mirror::PointerArray> arr) {
DCHECK(arr != nullptr);
if (kIsDebugBuild) {
for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
if (method != nullptr && !method->IsRuntimeMethod()) {
ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
CHECK(klass == nullptr || KeepClass(klass))
<< Class::PrettyClass(klass) << " should be a kept class";
}
}
}
// kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
// ArtMethods.
pointer_arrays_.emplace(arr.Ptr(), Bin::kArtMethodClean);
}
ImageWriter::Bin ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
DCHECK(object != nullptr);
size_t object_size = object->SizeOf();
// The magic happens here. We segregate objects into different bins based
// on how likely they are to get dirty at runtime.
//
// Likely-to-dirty objects get packed together into the same bin so that
// at runtime their page dirtiness ratio (how many dirty objects a page has) is
// maximized.
//
// This means more pages will stay either clean or shared dirty (with zygote) and
// the app will use less of its own (private) memory.
Bin bin = Bin::kRegular;
if (kBinObjects) {
//
// Changing the bin of an object is purely a memory-use tuning.
// It has no change on runtime correctness.
//
// Memory analysis has determined that the following types of objects get dirtied
// the most:
//
// * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
// a fixed layout which helps improve generated code (using PC-relative addressing),
// so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
// Since these arrays are huge, most pages do not overlap other objects and it's not
// really important where they are for the clean/dirty separation. Due to their
// special PC-relative addressing, we arbitrarily keep them at the end.
// * Class'es which are verified [their clinit runs only at runtime]
// - classes in general [because their static fields get overwritten]
// - initialized classes with all-final statics are unlikely to be ever dirty,
// so bin them separately
// * Art Methods that are:
// - native [their native entry point is not looked up until runtime]
// - have declaring classes that aren't initialized
// [their interpreter/quick entry points are trampolines until the class
// becomes initialized]
//
// We also assume the following objects get dirtied either never or extremely rarely:
// * Strings (they are immutable)
// * Art methods that aren't native and have initialized declared classes
//
// We assume that "regular" bin objects are highly unlikely to become dirtied,
// so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
//
if (object->IsClass()) {
bin = Bin::kClassVerified;
ObjPtr<mirror::Class> klass = object->AsClass();
// Add non-embedded vtable to the pointer array table if there is one.
ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
if (vtable != nullptr) {
AddMethodPointerArray(vtable);
}
ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
if (iftable != nullptr) {
for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
if (iftable->GetMethodArrayCount(i) > 0) {
AddMethodPointerArray(iftable->GetMethodArray(i));
}
}
}
// Move known dirty objects into their own sections. This includes:
// - classes with dirty static fields.
if (dirty_image_objects_ != nullptr &&
dirty_image_objects_->find(klass->PrettyDescriptor()) != dirty_image_objects_->end()) {
bin = Bin::kKnownDirty;
} else if (klass->GetStatus() == ClassStatus::kVisiblyInitialized) {
bin = Bin::kClassInitialized;
// If the class's static fields are all final, put it into a separate bin
// since it's very likely it will stay clean.
uint32_t num_static_fields = klass->NumStaticFields();
if (num_static_fields == 0) {
bin = Bin::kClassInitializedFinalStatics;
} else {
// Maybe all the statics are final?
bool all_final = true;
for (uint32_t i = 0; i < num_static_fields; ++i) {
ArtField* field = klass->GetStaticField(i);
if (!field->IsFinal()) {
all_final = false;
break;
}
}
if (all_final) {
bin = Bin::kClassInitializedFinalStatics;
}
}
}
} else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
bin = Bin::kString; // Strings are almost always immutable (except for object header).
} else if (object->GetClass<kVerifyNone>() == GetClassRoot<mirror::Object>()) {
// Instance of java lang object, probably a lock object. This means it will be dirty when we
// synchronize on it.
bin = Bin::kMiscDirty;
} else if (object->IsDexCache()) {
// Dex file field becomes dirty when the image is loaded.
bin = Bin::kMiscDirty;
}
// else bin = kBinRegular
}
// Assign the oat index too.
DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
oat_index_map_.emplace(object, oat_index);
ImageInfo& image_info = GetImageInfo(oat_index);
size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
// How many bytes the current bin is at (aligned).
size_t current_offset = image_info.GetBinSlotSize(bin);
// Move the current bin size up to accommodate the object we just assigned a bin slot.
image_info.IncrementBinSlotSize(bin, offset_delta);
BinSlot new_bin_slot(bin, current_offset);
SetImageBinSlot(object, new_bin_slot);
image_info.IncrementBinSlotCount(bin, 1u);
// Grow the image closer to the end by the object we just assigned.
image_info.image_end_ += offset_delta;
return bin;
}
bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
if (m->IsNative()) {
return true;
}
ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
// Initialized is highly unlikely to dirty since there's no entry points to mutate.
return declaring_class == nullptr ||
declaring_class->GetStatus() != ClassStatus::kVisiblyInitialized;
}
bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
DCHECK(object != nullptr);
// We always stash the bin slot into a lockword, in the 'forwarding address' state.
// If it's in some other state, then we haven't yet assigned an image bin slot.
if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
return false;
} else if (kIsDebugBuild) {
LockWord lock_word = object->GetLockWord(false);
size_t offset = lock_word.ForwardingAddress();
BinSlot bin_slot(offset);
size_t oat_index = GetOatIndex(object);
const ImageInfo& image_info = GetImageInfo(oat_index);
DCHECK_LT(bin_slot.GetOffset(), image_info.GetBinSlotSize(bin_slot.GetBin()))
<< "bin slot offset should not exceed the size of that bin";
}
return true;
}
ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object, size_t oat_index) const {
DCHECK(object != nullptr);
DCHECK(IsImageBinSlotAssigned(object));
LockWord lock_word = object->GetLockWord(false);
size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
BinSlot bin_slot(static_cast<uint32_t>(offset));
DCHECK_LT(bin_slot.GetOffset(), GetImageInfo(oat_index).GetBinSlotSize(bin_slot.GetBin()));
return bin_slot;
}
void ImageWriter::UpdateImageBinSlotOffset(mirror::Object* object,
size_t oat_index,
size_t new_offset) {
BinSlot old_bin_slot = GetImageBinSlot(object, oat_index);
DCHECK_LT(new_offset, GetImageInfo(oat_index).GetBinSlotSize(old_bin_slot.GetBin()));
BinSlot new_bin_slot(old_bin_slot.GetBin(), new_offset);
object->SetLockWord(LockWord::FromForwardingAddress(new_bin_slot.Uint32Value()),
/*as_volatile=*/ false);
DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
DCHECK(IsImageBinSlotAssigned(object));
}
bool ImageWriter::AllocMemory() {
for (ImageInfo& image_info : image_infos_) {
const size_t length = RoundUp(image_info.CreateImageSections().first, kPageSize);
std::string error_msg;
image_info.image_ = MemMap::MapAnonymous("image writer image",
length,
PROT_READ | PROT_WRITE,
/*low_4gb=*/ false,
&error_msg);
if (UNLIKELY(!image_info.image_.IsValid())) {
LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
return false;
}
// Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
CHECK_LE(image_info.image_end_, length);
image_info.image_bitmap_ = gc::accounting::ContinuousSpaceBitmap::Create(
"image bitmap", image_info.image_.Begin(), RoundUp(image_info.image_end_, kPageSize));
if (!image_info.image_bitmap_.IsValid()) {
LOG(ERROR) << "Failed to allocate memory for image bitmap";
return false;
}
}
return true;
}
static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
REQUIRES_SHARED(Locks::mutator_lock_) {
return klass->GetClassLoader() == nullptr;
}
bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
}
// This visitor follows the references of an instance, recursively then prune this class
// if a type of any field is pruned.
class ImageWriter::PruneObjectReferenceVisitor {
public:
PruneObjectReferenceVisitor(ImageWriter* image_writer,
bool* early_exit,
std::unordered_set<mirror::Object*>* visited,
bool* result)
: image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
ALWAYS_INLINE void VisitRootIfNonNull(
mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
REQUIRES_SHARED(Locks::mutator_lock_) { }
ALWAYS_INLINE void VisitRoot(
mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
REQUIRES_SHARED(Locks::mutator_lock_) { }
ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
MemberOffset offset,
bool is_static ATTRIBUTE_UNUSED) const
REQUIRES_SHARED(Locks::mutator_lock_) {
mirror::Object* ref =
obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
if (ref == nullptr || visited_->find(ref) != visited_->end()) {
return;
}
ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
Runtime::Current()->GetClassLinker()->GetClassRoots();
ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
if (klass == GetClassRoot<mirror::Method>(class_roots) ||
klass == GetClassRoot<mirror::Constructor>(class_roots)) {
// Prune all classes using reflection because the content they held will not be fixup.
*result_ = true;
}
if (ref->IsClass()) {
*result_ = *result_ ||
image_writer_->PruneImageClassInternal(ref->AsClass(), early_exit_, visited_);
} else {
// Record the object visited in case of circular reference.
visited_->emplace(ref);
*result_ = *result_ ||
image_writer_->PruneImageClassInternal(klass, early_exit_, visited_);
ref->VisitReferences(*this, *this);
// Clean up before exit for next call of this function.
visited_->erase(ref);
}
}
ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
ObjPtr<mirror::Reference> ref) const
REQUIRES_SHARED(Locks::mutator_lock_) {
operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
}
private:
ImageWriter* image_writer_;
bool* early_exit_;
std::unordered_set<mirror::Object*>* visited_;
bool* const result_;
};
bool ImageWriter::PruneImageClass(ObjPtr<mirror::Class> klass) {
bool early_exit = false;
std::unordered_set<mirror::Object*> visited;
return PruneImageClassInternal(klass, &early_exit, &visited);
}
bool ImageWriter::PruneImageClassInternal(
ObjPtr<mirror::Class> klass,
bool* early_exit,
std::unordered_set<mirror::Object*>* visited) {
DCHECK(early_exit != nullptr);
DCHECK(visited != nullptr);
DCHECK(compiler_options_.IsAppImage() || compiler_options_.IsBootImageExtension());
if (klass == nullptr || IsInBootImage(klass.Ptr())) {
return false;
}
auto found = prune_class_memo_.find(klass.Ptr());
if (found != prune_class_memo_.end()) {
// Already computed, return the found value.
return found->second;
}
// Circular dependencies, return false but do not store the result in the memoization table.
if (visited->find(klass.Ptr()) != visited->end()) {
*early_exit = true;
return false;
}
visited->emplace(klass.Ptr());
bool result = IsBootClassLoaderClass(klass);
std::string temp;
// Prune if not an image class, this handles any broken sets of image classes such as having a
// class in the set but not it's superclass.
result = result || !compiler_options_.IsImageClass(klass->GetDescriptor(&temp));
bool my_early_exit = false; // Only for ourselves, ignore caller.
// Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
// app image.
if (klass->IsErroneous()) {
result = true;
} else {
ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
}
if (!result) {
// Check interfaces since these wont be visited through VisitReferences.)
ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
result = result || PruneImageClassInternal(if_table->GetInterface(i),
&my_early_exit,
visited);
}
}
if (klass->IsObjectArrayClass()) {
result = result || PruneImageClassInternal(klass->GetComponentType(),
&my_early_exit,
visited);
}
// Check static fields and their classes.
if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
size_t num_static_fields = klass->NumReferenceStaticFields();
// Presumably GC can happen when we are cross compiling, it should not cause performance
// problems to do pointer size logic.
MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
Runtime::Current()->GetClassLinker()->GetImagePointerSize());
for (size_t i = 0u; i < num_static_fields; ++i) {
mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
if (ref != nullptr) {
if (ref->IsClass()) {
result = result || PruneImageClassInternal(ref->AsClass(), &my_early_exit, visited);
} else {
mirror::Class* type = ref->GetClass();
result = result || PruneImageClassInternal(type, &my_early_exit, visited);
if (!result) {
// For non-class case, also go through all the types mentioned by it's fields'
// references recursively to decide whether to keep this class.
bool tmp = false;
PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
ref->VisitReferences(visitor, visitor);
result = result || tmp;
}
}
}
field_offset = MemberOffset(field_offset.Uint32Value() +
sizeof(mirror::HeapReference<mirror::Object>));
}
}
result = result || PruneImageClassInternal(klass->GetSuperClass(), &my_early_exit, visited);
// Remove the class if the dex file is not in the set of dex files. This happens for classes that
// are from uses-library if there is no profile. b/30688277
ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
if (dex_cache != nullptr) {
result = result ||
dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
}
// Erase the element we stored earlier since we are exiting the function.
auto it = visited->find(klass.Ptr());
DCHECK(it != visited->end());
visited->erase(it);
// Only store result if it is true or none of the calls early exited due to circular
// dependencies. If visited is empty then we are the root caller, in this case the cycle was in
// a child call and we can remember the result.
if (result == true || !my_early_exit || visited->empty()) {
prune_class_memo_[klass.Ptr()] = result;
}
*early_exit |= my_early_exit;
return result;
}
bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
if (klass == nullptr) {
return false;
}
if (IsInBootImage(klass.Ptr())) {
// Already in boot image, return true.
DCHECK(!compiler_options_.IsBootImage());
return true;
}
std::string temp;
if (!compiler_options_.IsImageClass(klass->GetDescriptor(&temp))) {
return false;
}
if (compiler_options_.IsAppImage()) {
// For app images, we need to prune classes that
// are defined by the boot class path we're compiling against but not in
// the boot image spaces since these may have already been loaded at
// run time when this image is loaded. Keep classes in the boot image
// spaces we're compiling against since we don't want to re-resolve these.
return !PruneImageClass(klass);
}
return true;
}
class ImageWriter::PruneClassesVisitor : public ClassVisitor {
public:
PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
: image_writer_(image_writer),
class_loader_(class_loader),
classes_to_prune_(),
defined_class_count_(0u) { }
bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
if (!image_writer_->KeepClass(klass.Ptr())) {
classes_to_prune_.insert(klass.Ptr());
if (klass->GetClassLoader() == class_loader_) {
++defined_class_count_;
}
}
return true;
}
size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
ClassTable* class_table =
Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
for (mirror::Class* klass : classes_to_prune_) {
std::string storage;
const char* descriptor = klass->GetDescriptor(&storage);
bool result = class_table->Remove(descriptor);
DCHECK(result);
DCHECK(!class_table->Remove(descriptor)) << descriptor;
}
return defined_class_count_;
}
private:
ImageWriter* const image_writer_;
const ObjPtr<mirror::ClassLoader> class_loader_;
std::unordered_set<mirror::Class*> classes_to_prune_;
size_t defined_class_count_;
};
class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
public:
explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
: image_writer_(image_writer), removed_class_count_(0) {}
void Visit(ObjPtr<mirror::ClassLoader> class_loader) override
REQUIRES_SHARED(Locks::mutator_lock_) {
PruneClassesVisitor classes_visitor(image_writer_, class_loader);
ClassTable* class_table =
Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
class_table->Visit(classes_visitor);
removed_class_count_ += classes_visitor.Prune();
}
size_t GetRemovedClassCount() const {
return removed_class_count_;
}
private:
ImageWriter* const image_writer_;
size_t removed_class_count_;
};
void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
visitor->Visit(nullptr); // Visit boot class loader.
Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
}
void ImageWriter::ClearDexCache(ObjPtr<mirror::DexCache> dex_cache) {
// Clear methods.
mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
for (size_t slot_idx = 0, num = dex_cache->NumResolvedMethods(); slot_idx != num; ++slot_idx) {
auto pair =
mirror::DexCache::GetNativePairPtrSize(resolved_methods, slot_idx, target_ptr_size_);
if (pair.object != nullptr) {
dex_cache->ClearResolvedMethod(pair.index, target_ptr_size_);
}
}
// Clear fields.
mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
for (size_t slot_idx = 0, num = dex_cache->NumResolvedFields(); slot_idx != num; ++slot_idx) {
auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
if (pair.object != nullptr) {
dex_cache->ClearResolvedField(pair.index, target_ptr_size_);
}
}
// Clear types.
for (size_t slot_idx = 0, num = dex_cache->NumResolvedTypes(); slot_idx != num; ++slot_idx) {
mirror::TypeDexCachePair pair =
dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
if (!pair.object.IsNull()) {
dex_cache->ClearResolvedType(dex::TypeIndex(pair.index));
}
}
// Clear strings.
for (size_t slot_idx = 0, num = dex_cache->NumStrings(); slot_idx != num; ++slot_idx) {
mirror::StringDexCachePair pair =
dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
if (!pair.object.IsNull()) {
dex_cache->ClearString(dex::StringIndex(pair.index));
}
}
}
void ImageWriter::PreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
ObjPtr<mirror::ClassLoader> class_loader) {
// To ensure deterministic contents of the hash-based arrays, each slot shall contain
// the candidate with the lowest index. As we're processing entries in increasing index
// order, this means trying to look up the entry for the current index if the slot is
// empty or if it contains a higher index.
Runtime* runtime = Runtime::Current();
ClassLinker* class_linker = runtime->GetClassLinker();
const DexFile& dex_file = *dex_cache->GetDexFile();
// Preload the methods array and make the contents deterministic.
mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
dex::TypeIndex last_class_idx; // Initialized to invalid index.
ObjPtr<mirror::Class> last_class = nullptr;
for (size_t i = 0, num = dex_cache->GetDexFile()->NumMethodIds(); i != num; ++i) {
uint32_t slot_idx = dex_cache->MethodSlotIndex(i);
auto pair =
mirror::DexCache::GetNativePairPtrSize(resolved_methods, slot_idx, target_ptr_size_);
uint32_t stored_index = pair.index;
ArtMethod* method = pair.object;
if (method != nullptr && i > stored_index) {
continue; // Already checked.
}
// Check if the referenced class is in the image. Note that we want to check the referenced
// class rather than the declaring class to preserve the semantics, i.e. using a MethodId
// results in resolving the referenced class and that can for example throw OOME.
const dex::MethodId& method_id = dex_file.GetMethodId(i);
if (method_id.class_idx_ != last_class_idx) {
last_class_idx = method_id.class_idx_;
last_class = class_linker->LookupResolvedType(last_class_idx, dex_cache, class_loader);
}
if (method == nullptr || i < stored_index) {
if (last_class != nullptr) {
// Try to resolve the method with the class linker, which will insert
// it into the dex cache if successful.
method = class_linker->FindResolvedMethod(last_class, dex_cache, class_loader, i);
DCHECK(method == nullptr || dex_cache->GetResolvedMethod(i, target_ptr_size_) == method);
}
} else {
DCHECK_EQ(i, stored_index);
DCHECK(last_class != nullptr);
}
}
// Preload the fields array and make the contents deterministic.
mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
last_class_idx = dex::TypeIndex(); // Initialized to invalid index.
last_class = nullptr;
for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
uint32_t stored_index = pair.index;
ArtField* field = pair.object;
if (field != nullptr && i > stored_index) {
continue; // Already checked.
}
// Check if the referenced class is in the image. Note that we want to check the referenced
// class rather than the declaring class to preserve the semantics, i.e. using a FieldId
// results in resolving the referenced class and that can for example throw OOME.
const dex::FieldId& field_id = dex_file.GetFieldId(i);
if (field_id.class_idx_ != last_class_idx) {
last_class_idx = field_id.class_idx_;
last_class = class_linker->LookupResolvedType(last_class_idx, dex_cache, class_loader);
if (last_class != nullptr && !KeepClass(last_class)) {
last_class = nullptr;
}
}
if (field == nullptr || i < stored_index) {
if (last_class != nullptr) {
// Try to resolve the field with the class linker, which will insert
// it into the dex cache if successful.
field = class_linker->FindResolvedFieldJLS(last_class, dex_cache, class_loader, i);
DCHECK(field == nullptr || dex_cache->GetResolvedField(i, target_ptr_size_) == field);
}
} else {
DCHECK_EQ(i, stored_index);
DCHECK(last_class != nullptr);
}
}
// Preload the types array and make the contents deterministic.
// This is done after fields and methods as their lookup can touch the types array.
for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
dex::TypeIndex type_idx(i);
uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
mirror::TypeDexCachePair pair =
dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
uint32_t stored_index = pair.index;
ObjPtr<mirror::Class> klass = pair.object.Read();
if (klass == nullptr || i < stored_index) {
klass = class_linker->LookupResolvedType(type_idx, dex_cache, class_loader);
DCHECK(klass == nullptr || dex_cache->GetResolvedType(type_idx) == klass);
}
}
// Preload the strings array and make the contents deterministic.
for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
dex::StringIndex string_idx(i);
uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
mirror::StringDexCachePair pair =
dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
uint32_t stored_index = pair.index;
ObjPtr<mirror::String> string = pair.object.Read();
if (string == nullptr || i < stored_index) {
string = class_linker->LookupString(string_idx, dex_cache);
DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
}
}
}
void ImageWriter::PruneNonImageClasses() {
Runtime* runtime = Runtime::Current();
ClassLinker* class_linker = runtime->GetClassLinker();
Thread* self = Thread::Current();
ScopedAssertNoThreadSuspension sa(__FUNCTION__);
// Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
// sure the other ones don't get unloaded before the OatWriter runs.
class_linker->VisitClassTables(
[&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
table->RemoveStrongRoots(
[&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
ObjPtr<mirror::Object> obj = root.Read();
if (obj->IsDexCache()) {
// Return true if the dex file is not one of the ones in the map.
return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
dex_file_oat_index_map_.end();
}
// Return false to avoid removing.
return false;
});
});
// Remove the undesired classes from the class roots.
{
PruneClassLoaderClassesVisitor class_loader_visitor(this);
VisitClassLoaders(&class_loader_visitor);
VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
}
// Completely clear DexCaches. They shall be re-filled in PreloadDexCaches if requested.
std::vector<ObjPtr<mirror::DexCache>> dex_caches = FindDexCaches(self);
for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
ClearDexCache(dex_cache);
}
// Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
class_linker->DropFindArrayClassCache();
// Clear to save RAM.
prune_class_memo_.clear();
}
std::vector<ObjPtr<mirror::DexCache>> ImageWriter::FindDexCaches(Thread* self) {
std::vector<ObjPtr<mirror::DexCache>> dex_caches;
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
ReaderMutexLock mu2(self, *Locks::dex_lock_);
dex_caches.reserve(class_linker->GetDexCachesData().size());
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
if (self->IsJWeakCleared(data.weak_root)) {
continue;
}
dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
}
return dex_caches;
}
void ImageWriter::CheckNonImageClassesRemoved() {
auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
if (obj->IsClass() && !IsInBootImage(obj)) {
ObjPtr<Class> klass = obj->AsClass();
if (!KeepClass(klass)) {
DumpImageClasses();
CHECK(KeepClass(klass))
<< Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
}
}
};
gc::Heap* heap = Runtime::Current()->GetHeap();
heap->VisitObjects(visitor);
}
void ImageWriter::DumpImageClasses() {
for (const std::string& image_class : compiler_options_.GetImageClasses()) {
LOG(INFO) << " " << image_class;
}
}
ObjPtr<mirror::ObjectArray<mirror::Object>> ImageWriter::CollectDexCaches(Thread* self,
size_t oat_index) const {
std::unordered_set<const DexFile*> image_dex_files;
for (auto& pair : dex_file_oat_index_map_) {
const DexFile* image_dex_file = pair.first;
size_t image_oat_index = pair.second;
if (oat_index == image_oat_index) {
image_dex_files.insert(image_dex_file);
}
}
// build an Object[] of all the DexCaches used in the source_space_.
// Since we can't hold the dex lock when allocating the dex_caches
// ObjectArray, we lock the dex lock twice, first to get the number
// of dex caches first and then lock it again to copy the dex
// caches. We check that the number of dex caches does not change.
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
size_t dex_cache_count = 0;
{
ReaderMutexLock mu(self, *Locks::dex_lock_);
// Count number of dex caches not in the boot image.
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
ObjPtr<mirror::DexCache> dex_cache =
ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
if (dex_cache == nullptr) {
continue;
}
const DexFile* dex_file = dex_cache->GetDexFile();
if (IsImageDexCache(dex_cache)) {
dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
}
}
}
ObjPtr<ObjectArray<Object>> dex_caches = ObjectArray<Object>::Alloc(
self, GetClassRoot<ObjectArray<Object>>(class_linker), dex_cache_count);
CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
{
ReaderMutexLock mu(self, *Locks::dex_lock_);
size_t non_image_dex_caches = 0;
// Re-count number of non image dex caches.
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
ObjPtr<mirror::DexCache> dex_cache =
ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
if (dex_cache == nullptr) {
continue;
}
const DexFile* dex_file = dex_cache->GetDexFile();
if (IsImageDexCache(dex_cache)) {
non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
}
}
CHECK_EQ(dex_cache_count, non_image_dex_caches)
<< "The number of non-image dex caches changed.";
size_t i = 0;
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
ObjPtr<mirror::DexCache> dex_cache =
ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
if (dex_cache == nullptr) {
continue;
}
const DexFile* dex_file = dex_cache->GetDexFile();
if (IsImageDexCache(dex_cache) &&
image_dex_files.find(dex_file) != image_dex_files.end()) {
dex_caches->Set<false>(i, dex_cache.Ptr());
++i;
}
}
}
return dex_caches;
}
ObjPtr<ObjectArray<Object>> ImageWriter::CreateImageRoots(
size_t oat_index,
Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects) const {
Runtime* runtime = Runtime::Current();
ClassLinker* class_linker = runtime->GetClassLinker();
Thread* self = Thread::Current();
StackHandleScope<2> hs(self);
Handle<ObjectArray<Object>> dex_caches(hs.NewHandle(CollectDexCaches(self, oat_index)));
// build an Object[] of the roots needed to restore the runtime
int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compiler_options_.IsAppImage());
Handle<ObjectArray<Object>> image_roots(hs.NewHandle(ObjectArray<Object>::Alloc(
self, GetClassRoot<ObjectArray<Object>>(class_linker), image_roots_size)));
image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
if (!compiler_options_.IsAppImage()) {
DCHECK(boot_image_live_objects != nullptr);
image_roots->Set<false>(ImageHeader::kBootImageLiveObjects, boot_image_live_objects.Get());
} else {
DCHECK(boot_image_live_objects == nullptr);
image_roots->Set<false>(ImageHeader::kAppImageClassLoader, GetAppClassLoader());
}
for (int32_t i = 0; i != image_roots_size; ++i) {
CHECK(image_roots->Get(i) != nullptr);
}
return image_roots.Get();
}
void ImageWriter::RecordNativeRelocations(ObjPtr<mirror::Object> obj, size_t oat_index) {
if (obj->IsString()) {
ObjPtr<mirror::String> str = obj->AsString();
InternTable* intern_table = Runtime::Current()->GetInternTable();
Thread* const self = Thread::Current();
if (intern_table->LookupStrong(self, str) == str) {
DCHECK(std::none_of(image_infos_.begin(),
image_infos_.end(),
[=](ImageInfo& info) REQUIRES_SHARED(Locks::mutator_lock_) {
return info.intern_table_->LookupStrong(self, str) != nullptr;
}));
ObjPtr<mirror::String> interned =
GetImageInfo(oat_index).intern_table_->InternStrongImageString(str);
DCHECK_EQ(interned, obj);
}
} else if (obj->IsDexCache()) {
DCHECK_EQ(oat_index, GetOatIndexForDexFile(obj->AsDexCache()->GetDexFile()));
} else if (obj->IsClass()) {
// Visit and assign offsets for fields and field arrays.
ObjPtr<mirror::Class> as_klass = obj->AsClass();
DCHECK_EQ(oat_index, GetOatIndexForClass(as_klass));
DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
if (compiler_options_.IsAppImage()) {
// Extra sanity, no boot loader classes should be left!
CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
}
LengthPrefixedArray<ArtField>* fields[] = {
as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
};
ImageInfo& image_info = GetImageInfo(oat_index);
if (!compiler_options_.IsAppImage()) {
// Note: Avoid locking to prevent lock order violations from root visiting;
// image_info.class_table_ is only accessed from the image writer.
image_info.class_table_->InsertWithoutLocks(as_klass);
}
for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
// Total array length including header.
if (cur_fields != nullptr) {
const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
// Forward the entire array at once.
auto it = native_object_relocations_.find(cur_fields);
CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
<< " already forwarded";
size_t offset = image_info.GetBinSlotSize(Bin::kArtField);
DCHECK(!IsInBootImage(cur_fields));
native_object_relocations_.emplace(
cur_fields,
NativeObjectRelocation {
oat_index, offset, NativeObjectRelocationType::kArtFieldArray
});
offset += header_size;
// Forward individual fields so that we can quickly find where they belong.
for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
// Need to forward arrays separate of fields.
ArtField* field = &cur_fields->At(i);
auto it2 = native_object_relocations_.find(field);
CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
<< " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
DCHECK(!IsInBootImage(field));
native_object_relocations_.emplace(
field,
NativeObjectRelocation { oat_index,
offset,
NativeObjectRelocationType::kArtField });
offset += sizeof(ArtField);
}
image_info.IncrementBinSlotSize(
Bin::kArtField, header_size + cur_fields->size() * sizeof(ArtField));
DCHECK_EQ(offset, image_info.GetBinSlotSize(Bin::kArtField));
}
}
// Visit and assign offsets for methods.
size_t num_methods = as_klass->NumMethods();
if (num_methods != 0) {
bool any_dirty = false;
for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
if (WillMethodBeDirty(&m)) {
any_dirty = true;
break;
}
}
NativeObjectRelocationType type = any_dirty
? NativeObjectRelocationType::kArtMethodDirty
: NativeObjectRelocationType::kArtMethodClean;
Bin bin_type = BinTypeForNativeRelocationType(type);
// Forward the entire array at once, but header first.
const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
const size_t method_size = ArtMethod::Size(target_ptr_size_);
const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
method_size,
method_alignment);
LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
auto it = native_object_relocations_.find(array);
CHECK(it == native_object_relocations_.end())
<< "Method array " << array << " already forwarded";
size_t offset = image_info.GetBinSlotSize(bin_type);
DCHECK(!IsInBootImage(array));
native_object_relocations_.emplace(array,
NativeObjectRelocation {
oat_index,
offset,
any_dirty ? NativeObjectRelocationType::kArtMethodArrayDirty
: NativeObjectRelocationType::kArtMethodArrayClean });
image_info.IncrementBinSlotSize(bin_type, header_size);
for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
AssignMethodOffset(&m, type, oat_index);
}
(any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
}
// Assign offsets for all runtime methods in the IMT since these may hold conflict tables
// live.
if (as_klass->ShouldHaveImt()) {
ImTable* imt = as_klass->GetImt(target_ptr_size_);
if (TryAssignImTableOffset(imt, oat_index)) {
// Since imt's can be shared only do this the first time to not double count imt method
// fixups.
for (size_t i = 0; i < ImTable::kSize; ++i) {
ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
DCHECK(imt_method != nullptr);
if (imt_method->IsRuntimeMethod() &&
!IsInBootImage(imt_method) &&
!NativeRelocationAssigned(imt_method)) {
AssignMethodOffset(imt_method, NativeObjectRelocationType::kRuntimeMethod, oat_index);
}
}
}
}
} else if (obj->IsClassLoader()) {
// Register the class loader if it has a class table.
// The fake boot class loader should not get registered.
ObjPtr<mirror::ClassLoader> class_loader = obj->AsClassLoader();
if (class_loader->GetClassTable() != nullptr) {
DCHECK(compiler_options_.IsAppImage());
if (class_loader == GetAppClassLoader()) {
ImageInfo& image_info = GetImageInfo(oat_index);
// Note: Avoid locking to prevent lock order violations from root visiting;
// image_info.class_table_ table is only accessed from the image writer
// and class_loader->GetClassTable() is iterated but not modified.
image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
}
}
}
}
bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
return native_object_relocations_.find(ptr) != native_object_relocations_.end();
}
bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
// No offset, or already assigned.
if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
return false;
}
// If the method is a conflict method we also want to assign the conflict table offset.
ImageInfo& image_info = GetImageInfo(oat_index);
const size_t size = ImTable::SizeInBytes(target_ptr_size_);
native_object_relocations_.emplace(
imt,
NativeObjectRelocation {
oat_index,
image_info.GetBinSlotSize(Bin::kImTable),
NativeObjectRelocationType::kIMTable});
image_info.IncrementBinSlotSize(Bin::kImTable, size);
return true;
}
void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
// No offset, or already assigned.
if (table == nullptr || NativeRelocationAssigned(table)) {
return;
}
CHECK(!IsInBootImage(table));
// If the method is a conflict method we also want to assign the conflict table offset.
ImageInfo& image_info = GetImageInfo(oat_index);
const size_t size = table->ComputeSize(target_ptr_size_);
native_object_relocations_.emplace(
table,
NativeObjectRelocation {
oat_index,
image_info.GetBinSlotSize(Bin::kIMTConflictTable),
NativeObjectRelocationType::kIMTConflictTable});
image_info.IncrementBinSlotSize(Bin::kIMTConflictTable, size);
}
void ImageWriter::AssignMethodOffset(ArtMethod* method,
NativeObjectRelocationType type,
size_t oat_index) {
DCHECK(!IsInBootImage(method));
CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
<< ArtMethod::PrettyMethod(method);
if (method->IsRuntimeMethod()) {
TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
}
ImageInfo& image_info = GetImageInfo(oat_index);
Bin bin_type = BinTypeForNativeRelocationType(type);
size_t offset = image_info.GetBinSlotSize(bin_type);
native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
image_info.IncrementBinSlotSize(bin_type, ArtMethod::Size(target_ptr_size_));
}
class ImageWriter::LayoutHelper {
public:
explicit LayoutHelper(ImageWriter* image_writer)
: image_writer_(image_writer) {
bin_objects_.resize(image_writer_->image_infos_.size());
for (auto& inner : bin_objects_) {
inner.resize(enum_cast<size_t>(Bin::kMirrorCount));
}
}
void ProcessDexFileObjects(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
void ProcessRoots(VariableSizedHandleScope* handles) REQUIRES_SHARED(Locks::mutator_lock_);
void ProcessWorkQueue() REQUIRES_SHARED(Locks::mutator_lock_);
void VerifyImageBinSlotsAssigned() REQUIRES_SHARED(Locks::mutator_lock_);
void FinalizeBinSlotOffsets() REQUIRES_SHARED(Locks::mutator_lock_);
/*
* Collects the string reference info necessary for loading app images.
*
* Because AppImages may contain interned strings that must be deduplicated
* with previously interned strings when loading the app image, we need to
* visit references to these strings and update them to point to the correct
* string. To speed up the visiting of references at load time we include
* a list of offsets to string references in the AppImage.
*/
void CollectStringReferenceInfo(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
private:
class CollectClassesVisitor;
class CollectRootsVisitor;
class CollectStringReferenceVisitor;
class VisitReferencesVisitor;
using WorkQueue = std::deque<std::pair<ObjPtr<mirror::Object>, size_t>>;
void VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index)
REQUIRES_SHARED(Locks::mutator_lock_);
bool TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index)
REQUIRES_SHARED(Locks::mutator_lock_);
ImageWriter* const image_writer_;
// Work list of <object, oat_index> for objects. Everything in the queue must already be
// assigned a bin slot.
WorkQueue work_queue_;
// Objects for individual bins. Indexed by `oat_index` and `bin`.
// Cannot use ObjPtr<> because of invalidation in Heap::VisitObjects().
dchecked_vector<dchecked_vector<dchecked_vector<mirror::Object*>>> bin_objects_;
};
class ImageWriter::LayoutHelper::CollectClassesVisitor : public ClassVisitor {
public:
explicit CollectClassesVisitor(ImageWriter* image_writer)
: image_writer_(image_writer),
dex_files_(image_writer_->compiler_options_.GetDexFilesForOatFile()) {}
bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
if (!image_writer_->IsInBootImage(klass.Ptr())) {
ObjPtr<mirror::Class> component_type = klass;
size_t dimension = 0u;
while (component_type->IsArrayClass()) {
++dimension;
component_type = component_type->GetComponentType();
}
DCHECK(!component_type->IsProxyClass());
size_t dex_file_index;
uint32_t class_def_index = 0u;
if (UNLIKELY(component_type->IsPrimitive())) {
DCHECK(image_writer_->compiler_options_.IsBootImage());
dex_file_index = 0u;
class_def_index = enum_cast<uint32_t>(component_type->GetPrimitiveType());
} else {
auto it = std::find(dex_files_.begin(), dex_files_.end(), &component_type->GetDexFile());
DCHECK(it != dex_files_.end()) << klass->PrettyDescriptor();
dex_file_index = std::distance(dex_files_.begin(), it) + 1u; // 0 is for primitive types.
class_def_index = component_type->GetDexClassDefIndex();
}
klasses_.push_back({klass, dex_file_index, class_def_index, dimension});
}
return true;
}
WorkQueue SortAndReleaseClasses()
REQUIRES_SHARED(Locks::mutator_lock_) {
std::sort(klasses_.begin(), klasses_.end());
WorkQueue result;
size_t last_dex_file_index = static_cast<size_t>(-1);
size_t last_oat_index = static_cast<size_t>(-1);
for (const ClassEntry& entry : klasses_) {
if (last_dex_file_index != entry.dex_file_index) {
if (UNLIKELY(entry.dex_file_index == 0u)) {
last_oat_index = GetDefaultOatIndex(); // Primitive type.
} else {
uint32_t dex_file_index = entry.dex_file_index - 1u; // 0 is for primitive types.
last_oat_index = image_writer_->GetOatIndexForDexFile(dex_files_[dex_file_index]);
}
last_dex_file_index = entry.dex_file_index;
}
result.emplace_back(entry.klass, last_oat_index);
}
klasses_.clear();
return result;
}
private:
struct ClassEntry {
ObjPtr<mirror::Class> klass;
// We shall sort classes by dex file, class def index and array dimension.
size_t dex_file_index;
uint32_t class_def_index;
size_t dimension;
bool operator<(const ClassEntry& other) const {
return std::tie(dex_file_index, class_def_index, dimension) <
std::tie(other.dex_file_index, other.class_def_index, other.dimension);
}
};
ImageWriter* const image_writer_;
ArrayRef<const DexFile* const> dex_files_;
std::deque<ClassEntry> klasses_;
};
class ImageWriter::LayoutHelper::CollectRootsVisitor {
public:
CollectRootsVisitor() = default;
std::vector<ObjPtr<mirror::Object>> ReleaseRoots() {
std::vector<ObjPtr<mirror::Object>> roots;
roots.swap(roots_);
return roots;
}
void VisitRootIfNonNull(StackReference<mirror::Object>* ref) {
if (!ref->IsNull()) {
roots_.push_back(ref->AsMirrorPtr());
}
}
private:
std::vector<ObjPtr<mirror::Object>> roots_;
};
class ImageWriter::LayoutHelper::CollectStringReferenceVisitor {
public:
explicit CollectStringReferenceVisitor(
const ImageWriter* image_writer,
size_t oat_index,
std::vector<AppImageReferenceOffsetInfo>* const string_reference_offsets,
ObjPtr<mirror::Object> current_obj)
: image_writer_(image_writer),
oat_index_(oat_index),
string_reference_offsets_(string_reference_offsets),
current_obj_(current_obj) {}
void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
REQUIRES_SHARED(Locks::mutator_lock_) {
if (!root->IsNull()) {
VisitRoot(root);
}
}
void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
REQUIRES_SHARED(Locks::mutator_lock_) {
// Only dex caches have native String roots. These are collected separately.
DCHECK(current_obj_->IsDexCache() ||
!image_writer_->IsInternedAppImageStringReference(root->AsMirrorPtr()))
<< mirror::Object::PrettyTypeOf(current_obj_);
}
// Collects info for managed fields that reference managed Strings.
void operator() (ObjPtr<mirror::Object> obj,
MemberOffset member_offset,
bool is_static ATTRIBUTE_UNUSED) const
REQUIRES_SHARED(Locks::mutator_lock_) {
ObjPtr<mirror::Object> referred_obj =
obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(member_offset);
if (image_writer_->IsInternedAppImageStringReference(referred_obj)) {
size_t base_offset = image_writer_->GetImageOffset(current_obj_.Ptr(), oat_index_);
string_reference_offsets_->emplace_back(base_offset, member_offset.Uint32Value());
}
}
ALWAYS_INLINE
void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
ObjPtr<mirror::Reference> ref) const
REQUIRES_SHARED(Locks::mutator_lock_) {
operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
}
private:
const ImageWriter* const image_writer_;
const size_t oat_index_;
std::vector<AppImageReferenceOffsetInfo>* const string_reference_offsets_;
const ObjPtr<mirror::Object> current_obj_;
};
class ImageWriter::LayoutHelper::VisitReferencesVisitor {
public:
VisitReferencesVisitor(LayoutHelper* helper, size_t oat_index)
: helper_(helper), oat_index_(oat_index) {}
// Fix up separately since we also need to fix up method entrypoints.
ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
REQUIRES_SHARED(Locks::mutator_lock_) {
if (!root->IsNull()) {
VisitRoot(root);
}
}
ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
REQUIRES_SHARED(Locks::mutator_lock_) {
root->Assign(VisitReference(root->AsMirrorPtr()));
}
ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
MemberOffset offset,
bool is_static ATTRIBUTE_UNUSED) const
REQUIRES_SHARED(Locks::mutator_lock_) {
mirror::Object* ref =
obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
}
ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
ObjPtr<mirror::Reference> ref) const
REQUIRES_SHARED(Locks::mutator_lock_) {
operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
}
private:
mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
if (helper_->TryAssignBinSlot(ref, oat_index_)) {
// Remember how many objects we're adding at the front of the queue as we want
// to reverse that range to process these references in the order of addition.
helper_->work_queue_.emplace_front(ref, oat_index_);
}
if (ClassLinker::kAppImageMayContainStrings &&
helper_->image_writer_->compiler_options_.IsAppImage() &&
helper_->image_writer_->IsInternedAppImageStringReference(ref)) {
helper_->image_writer_->image_infos_[oat_index_].num_string_references_ += 1u;
}
return ref;
}
LayoutHelper* const helper_;
const size_t oat_index_;
};
void ImageWriter::LayoutHelper::ProcessDexFileObjects(Thread* self) {
Runtime* runtime = Runtime::Current();
ClassLinker* class_linker = runtime->GetClassLinker();
// To ensure deterministic output, populate the work queue with objects in a pre-defined order.
// Note: If we decide to implement a profile-guided layout, this is the place to do so.
// Get initial work queue with the image classes and assign their bin slots.
CollectClassesVisitor visitor(image_writer_);
class_linker->VisitClasses(&visitor);
DCHECK(work_queue_.empty());
work_queue_ = visitor.SortAndReleaseClasses();
for (const std::pair<ObjPtr<mirror::Object>, size_t>& entry : work_queue_) {
DCHECK(entry.first->IsClass());
bool assigned = TryAssignBinSlot(entry.first, entry.second);
DCHECK(assigned);
}
// Assign bin slots to strings and dex caches.
for (const DexFile* dex_file : image_writer_->compiler_options_.GetDexFilesForOatFile()) {
auto it = image_writer_->dex_file_oat_index_map_.find(dex_file);
DCHECK(it != image_writer_->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
const size_t oat_index = it->second;
// Assign bin slots for strings defined in this dex file in StringId (lexicographical) order.
InternTable* const intern_table = runtime->GetInternTable();
for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
uint32_t utf16_length;
const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
&utf16_length);
ObjPtr<mirror::String> string = intern_table->LookupStrong(self, utf16_length, utf8_data);
if (string != nullptr && !image_writer_->IsInBootImage(string.Ptr())) {
// Try to assign bin slot to this string but do not add it to the work list.
// The only reference in a String is its class, processed above for the boot image.
bool assigned = TryAssignBinSlot(string, oat_index);
DCHECK(assigned ||
// We could have seen the same string in an earlier dex file.
dex_file != image_writer_->compiler_options_.GetDexFilesForOatFile().front());
}
}
// Assign bin slot to this file's dex cache and add it to the end of the work queue.
ObjPtr<mirror::DexCache> dex_cache = class_linker->FindDexCache(self, *dex_file);
DCHECK(dex_cache != nullptr);
bool assigned = TryAssignBinSlot(dex_cache, oat_index);
DCHECK(assigned);
work_queue_.emplace_back(dex_cache, oat_index);
}
// Since classes and dex caches have been assigned to their bins, when we process a class
// we do not follow through the class references or dex caches, so we correctly process
// only objects actually belonging to that class before taking a new class from the queue.
// If multiple class statics reference the same object (directly or indirectly), the object
// is treated as belonging to the first encountered referencing class.
ProcessWorkQueue();
}
void ImageWriter::LayoutHelper::ProcessRoots(VariableSizedHandleScope* handles) {
// Assing bin slots to the image objects referenced by `handles`, add them to the work queue
// and process the work queue. These objects are the image roots and boot image live objects
// and they reference other objects needed for the image, for example the array of dex cache
// references, or the pre-allocated exceptions for the boot image.
DCHECK(work_queue_.empty());
CollectRootsVisitor visitor;
handles->VisitRoots(visitor);
for (ObjPtr<mirror::Object> root : visitor.ReleaseRoots()) {
if (TryAssignBinSlot(root, GetDefaultOatIndex())) {
work_queue_.emplace_back(root, GetDefaultOatIndex());
}
}
ProcessWorkQueue();
}
void ImageWriter::LayoutHelper::ProcessWorkQueue() {
while (!work_queue_.empty()) {
std::pair<ObjPtr<mirror::Object>, size_t> pair = work_queue_.front();
work_queue_.pop_front();
VisitReferences(/*obj=*/ pair.first, /*oat_index=*/ pair.second);
}
}
void ImageWriter::LayoutHelper::VerifyImageBinSlotsAssigned() {
std::vector<mirror::Object*> carveout;
if (image_writer_->compiler_options_.IsAppImage()) {
// Exclude boot class path dex caches that are not part of the boot image.
// Also exclude their locations if they have not been visited through another path.
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Thread* self = Thread::Current();
ReaderMutexLock mu(self, *Locks::dex_lock_);
for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
ObjPtr<mirror::DexCache> dex_cache =
ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
if (dex_cache == nullptr ||
image_writer_->IsInBootImage(dex_cache.Ptr()) ||
ContainsElement(image_writer_->compiler_options_.GetDexFilesForOatFile(),
dex_cache->GetDexFile())) {
continue;
}
CHECK(!image_writer_->IsImageBinSlotAssigned(dex_cache.Ptr()));
carveout.push_back(dex_cache.Ptr());
ObjPtr<mirror::String> location = dex_cache->GetLocation();
if (!image_writer_->IsImageBinSlotAssigned(location.Ptr())) {
carveout.push_back(location.Ptr());
}
}
}
std::vector<mirror::Object*> missed_objects;
auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
REQUIRES_SHARED(Locks::mutator_lock_) {
if (!image_writer_->IsInBootImage(obj)) {
if (!UNLIKELY(image_writer_->IsImageBinSlotAssigned(obj))) {
// Ignore the `carveout` objects.
if (ContainsElement(carveout, obj)) {
return;
}
// Ignore finalizer references for the dalvik.system.DexFile objects referenced by
// the app class loader.
if (obj->IsFinalizerReferenceInstance()) {
ArtField* ref_field =
obj->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;");
CHECK(ref_field != nullptr);
ObjPtr<mirror::Object> ref = ref_field->GetObject(obj);
CHECK(ref != nullptr);
CHECK(image_writer_->IsImageBinSlotAssigned(ref.Ptr()));
ObjPtr<mirror::Class> klass = ref->GetClass();
CHECK(klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile));
// Note: The app class loader is used only for checking against the runtime
// class loader, the dex file cookie is cleared and therefore we do not need
// to run the finalizer even if we implement app image objects collection.
ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
CHECK(field->GetObject(ref) == nullptr);
return;
}
if (obj->IsString()) {
// Ignore interned strings. These may come from reflection interning method names.
// TODO: Make dex file strings weak interns and GC them before writing the image.
Runtime* runtime = Runtime::Current();
ObjPtr<mirror::String> interned =
runtime->GetInternTable()->LookupStrong(Thread::Current(), obj->AsString());
if (interned == obj) {
return;
}
}
missed_objects.push_back(obj);
}
}
};
Runtime::Current()->GetHeap()->VisitObjects(ensure_bin_slots_assigned);
if (!missed_objects.empty()) {
const gc::Verification* v = Runtime::Current()->GetHeap()->GetVerification();
size_t num_missed_objects = missed_objects.size();
size_t num_paths = std::min<size_t>(num_missed_objects, 5u); // Do not flood the output.
ArrayRef<mirror::Object*> missed_objects_head =
ArrayRef<mirror::Object*>(missed_objects).SubArray(/*pos=*/ 0u, /*length=*/ num_paths);
for (mirror::Object* obj : missed_objects_head) {
LOG(ERROR) << "Image object without assigned bin slot: "
<< mirror::Object::PrettyTypeOf(obj) << " " << obj
<< " " << v->FirstPathFromRootSet(obj);
}
LOG(FATAL) << "Found " << num_missed_objects << " objects without assigned bin slots.";
}
}
void ImageWriter::LayoutHelper::FinalizeBinSlotOffsets() {
// Calculate bin slot offsets and adjust for region padding if needed.
const size_t region_size = image_writer_->region_size_;
const size_t num_image_infos = image_writer_->image_infos_.size();
for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
ImageInfo& image_info = image_writer_->image_infos_[oat_index];
size_t bin_offset = image_writer_->image_objects_offset_begin_;
for (size_t i = 0; i != kNumberOfBins; ++i) {
Bin bin = enum_cast<Bin>(i);
switch (bin) {
case Bin::kArtMethodClean:
case Bin::kArtMethodDirty: {
bin_offset = RoundUp(bin_offset, ArtMethod::Alignment(image_writer_->target_ptr_size_));
break;
}
case Bin::kDexCacheArray:
bin_offset =
RoundUp(bin_offset, DexCacheArraysLayout::Alignment(image_writer_->target_ptr_size_));
break;
case Bin::kImTable:
case Bin::kIMTConflictTable: {
bin_offset = RoundUp(bin_offset, static_cast<size_t>(image_writer_->target_ptr_size_));
break;
}
default: {
// Normal alignment.
}
}
image_info.bin_slot_offsets_[i] = bin_offset;
// If the bin is for mirror objects, we may need to add region padding and update offsets.
if (i < enum_cast<size_t>(Bin::kMirrorCount) && region_size != 0u) {
const size_t offset_after_header = bin_offset - sizeof(ImageHeader);
size_t remaining_space =
RoundUp(offset_after_header + 1u, region_size) - offset_after_header;
// Exercise the loop below in debug builds to get coverage.
if (kIsDebugBuild || remaining_space < image_info.bin_slot_sizes_[i]) {
// The bin crosses a region boundary. Add padding if needed.
size_t object_offset = 0u;
size_t padding = 0u;
for (mirror::Object* object : bin_objects_[oat_index][i]) {
BinSlot bin_slot = image_writer_->GetImageBinSlot(object, oat_index);
DCHECK_EQ(enum_cast<size_t>(bin_slot.GetBin()), i);
DCHECK_EQ(bin_slot.GetOffset() + padding, object_offset);
size_t object_size = RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
auto add_padding = [&](bool tail_region) {
DCHECK_NE(remaining_space, 0u);
DCHECK_LT(remaining_space, region_size);
DCHECK_ALIGNED(remaining_space, kObjectAlignment);
// TODO When copying to heap regions, leave the tail region padding zero-filled.
if (!tail_region || true) {
image_info.padding_offsets_.push_back(bin_offset + object_offset);
}
image_info.bin_slot_sizes_[i] += remaining_space;
padding += remaining_space;
object_offset += remaining_space;
remaining_space = region_size;
};
if (object_size > remaining_space) {
// Padding needed if we're not at region boundary (with a multi-region object).
if (remaining_space != region_size) {
// TODO: Instead of adding padding, we should consider reordering the bins
// or objects to reduce wasted space.
add_padding(/*tail_region=*/ false);
}
DCHECK_EQ(remaining_space, region_size);
// For huge objects, adjust the remaining space to hold the object and some more.
if (object_size > region_size) {
remaining_space = RoundUp(object_size + 1u, region_size);
}
} else if (remaining_space == object_size) {
// Move to the next region, no padding needed.
remaining_space += region_size;
}
DCHECK_GT(remaining_space, object_size);
remaining_space -= object_size;
image_writer_->UpdateImageBinSlotOffset(object, oat_index, object_offset);
object_offset += object_size;
// Add padding to the tail region of huge objects if not region-aligned.
if (object_size > region_size && remaining_space != region_size) {
DCHECK(!IsAlignedParam(object_size, region_size));
add_padding(/*tail_region=*/ true);
}
}
image_writer_->region_alignment_wasted_ += padding;
image_info.image_end_ += padding;
}
}
bin_offset += image_info.bin_slot_sizes_[i];
}
// NOTE: There may be additional padding between the bin slots and the intern table.
DCHECK_EQ(
image_info.image_end_,
image_info.GetBinSizeSum(Bin::kMirrorCount) + image_writer_->image_objects_offset_begin_);
}
VLOG(image) << "Space wasted for region alignment " << image_writer_->region_alignment_wasted_;
}
void ImageWriter::LayoutHelper::CollectStringReferenceInfo(Thread* self) {
size_t managed_string_refs = 0u;
size_t total_string_refs = 0u;
const size_t num_image_infos = image_writer_->image_infos_.size();
for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
ImageInfo& image_info = image_writer_->image_infos_[oat_index];
DCHECK(image_info.string_reference_offsets_.empty());
image_info.string_reference_offsets_.reserve(image_info.num_string_references_);
for (size_t i = 0; i < enum_cast<size_t>(Bin::kMirrorCount); ++i) {
for (mirror::Object* obj : bin_objects_[oat_index][i]) {
CollectStringReferenceVisitor visitor(image_writer_,
oat_index,
&image_info.string_reference_offsets_,
obj);
/*
* References to managed strings can occur either in the managed heap or in
* native memory regions. Information about managed references is collected
* by the CollectStringReferenceVisitor and directly added to the image info.
*
* Native references to managed strings can only occur through DexCache
* objects. This is verified by the visitor in debug mode and the references
* are collected separately below.
*/
obj->VisitReferences</*kVisitNativeRoots=*/ kIsDebugBuild,
kVerifyNone,
kWithoutReadBarrier>(visitor, visitor);
}
}
managed_string_refs += image_info.string_reference_offsets_.size();
// Collect dex cache string arrays.
for (const DexFile* dex_file : image_writer_->compiler_options_.GetDexFilesForOatFile()) {
if (image_writer_->GetOatIndexForDexFile(dex_file) == oat_index) {
ObjPtr<mirror::DexCache> dex_cache =
Runtime::Current()->GetClassLinker()->FindDexCache(self, *dex_file);
DCHECK(dex_cache != nullptr);
size_t base_offset = image_writer_->GetImageOffset(dex_cache.Ptr(), oat_index);
// Visit all string cache entries.
mirror::StringDexCacheType* strings = dex_cache->GetStrings();
const size_t num_strings = dex_cache->NumStrings();
for (uint32_t index = 0; index != num_strings; ++index) {
ObjPtr<mirror::String> referred_string = strings[index].load().object.Read();
if (image_writer_->IsInternedAppImageStringReference(referred_string)) {
image_info.string_reference_offsets_.emplace_back(
SetDexCacheStringNativeRefTag(base_offset), index);
}
}
// Visit all pre-resolved string entries.
GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
const size_t num_pre_resolved_strings = dex_cache->NumPreResolvedStrings();
for (uint32_t index = 0; index != num_pre_resolved_strings; ++index) {
ObjPtr<mirror::String> referred_string = preresolved_strings[index].Read();
if (image_writer_->IsInternedAppImageStringReference(referred_string)) {
image_info.string_reference_offsets_.emplace_back(
SetDexCachePreResolvedStringNativeRefTag(base_offset), index);
}
}
}
}
total_string_refs += image_info.string_reference_offsets_.size();
// Check that we collected the same number of string references as we saw in the previous pass.
CHECK_EQ(image_info.string_reference_offsets_.size(), image_info.num_string_references_);
}
VLOG(compiler) << "Dex2Oat:AppImage:stringReferences = " << total_string_refs
<< " (managed: " << managed_string_refs
<< ", native: " << (total_string_refs - managed_string_refs) << ")";
}
void ImageWriter::LayoutHelper::VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index) {
size_t old_work_queue_size = work_queue_.size();
VisitReferencesVisitor visitor(this, oat_index);
// Walk references and assign bin slots for them.
obj->VisitReferences</*kVisitNativeRoots=*/ true, kVerifyNone, kWithoutReadBarrier>(
visitor,
visitor);
// Put the added references in the queue in the order in which they were added.
// The visitor just pushes them to the front as it visits them.
DCHECK_LE(old_work_queue_size, work_queue_.size());
size_t num_added = work_queue_.size() - old_work_queue_size;
std::reverse(work_queue_.begin(), work_queue_.begin() + num_added);
}
bool ImageWriter::LayoutHelper::TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index) {
if (obj == nullptr || image_writer_->IsInBootImage(obj.Ptr())) {
// Object is null or already in the image, there is no work to do.
return false;
}
bool assigned = false;
if (!image_writer_->IsImageBinSlotAssigned(obj.Ptr())) {
image_writer_->RecordNativeRelocations(obj, oat_index);
Bin bin = image_writer_->AssignImageBinSlot(obj.Ptr(), oat_index);
bin_objects_[oat_index][enum_cast<size_t>(bin)].push_back(obj.Ptr());
assigned = true;
}
return assigned;
}
static ObjPtr<ObjectArray<Object>> GetBootImageLiveObjects() REQUIRES_SHARED(Locks::mutator_lock_)