1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "image_writer.h" 18 19 #include <sys/stat.h> 20 #include <lz4.h> 21 #include <lz4hc.h> 22 23 #include <memory> 24 #include <numeric> 25 #include <unordered_set> 26 #include <vector> 27 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" 36 #include "elf_file.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" 42 #include "gc/heap.h" 43 #include "gc/space/large_object_space.h" 44 #include "gc/space/space-inl.h" 45 #include "globals.h" 46 #include "image.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" 59 #include "oat.h" 60 #include "oat_file.h" 61 #include "oat_file_manager.h" 62 #include "runtime.h" 63 #include "scoped_thread_state_change.h" 64 #include "handle_scope-inl.h" 65 #include "utils/dex_cache_arrays_layout-inl.h" 66 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; 72 73 namespace art { 74 75 // Separate objects into multiple bins to optimize dirty memory use. 76 static constexpr bool kBinObjects = true; 77 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()); 83 return false; 84 } 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) { 90 return true; 91 } 92 } 93 return false; 94 } 95 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()); 100 return false; 101 } 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()) { 105 return true; 106 } 107 } 108 return false; 109 } 110 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"); 115 } 116 117 static void CheckNoDexObjects() { 118 ScopedObjectAccess soa(Thread::Current()); 119 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr); 120 } 121 122 bool ImageWriter::PrepareImageAddressSpace() { 123 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet()); 124 gc::Heap* const heap = Runtime::Current()->GetHeap(); 125 { 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 131 } 132 } 133 heap->CollectGarbage(false); // Remove garbage. 134 135 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped 136 // dex files. 137 // 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 140 // true. 141 if (kIsDebugBuild) { 142 CheckNoDexObjects(); 143 } 144 145 if (kIsDebugBuild) { 146 ScopedObjectAccess soa(Thread::Current()); 147 CheckNonImageClassesRemoved(); 148 } 149 150 { 151 ScopedObjectAccess soa(Thread::Current()); 152 CalculateNewObjectOffsets(); 153 } 154 155 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and 156 // bin size sums being calculated. 157 if (!AllocMemory()) { 158 return false; 159 } 160 161 return true; 162 } 163 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 168 // oat_filenames. 169 CHECK(!image_filenames.empty()); 170 if (image_fd != kInvalidFd) { 171 CHECK_EQ(image_filenames.size(), 1u); 172 } 173 CHECK(!oat_filenames.empty()); 174 CHECK_EQ(image_filenames.size(), oat_filenames.size()); 175 176 { 177 ScopedObjectAccess soa(Thread::Current()); 178 for (size_t i = 0; i < oat_filenames.size(); ++i) { 179 CreateHeader(i); 180 CopyAndFixupNativeData(i); 181 } 182 } 183 184 { 185 // TODO: heap validation can't handle these fix up passes. 186 ScopedObjectAccess soa(Thread::Current()); 187 Runtime::Current()->GetHeap()->DisableObjectValidation(); 188 CopyAndFixupObjects(); 189 } 190 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()); 202 } 203 } else { 204 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename; 205 } 206 } else { 207 image_file.reset(OS::CreateEmptyFile(image_filename)); 208 } 209 210 if (image_file == nullptr) { 211 LOG(ERROR) << "Failed to open image file " << image_filename; 212 return false; 213 } 214 215 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) { 216 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename; 217 image_file->Erase(); 218 return EXIT_FAILURE; 219 } 220 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); 226 size_t data_size; 227 const char* image_data_to_write; 228 const uint64_t compress_start_time = NanoTime(); 229 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), 238 &compressed_data[0], 239 image_data_size); 240 241 break; 242 } 243 /* 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), 251 &compressed_data[0], 252 image_data_size); 253 break; 254 } 255 */ 256 case ImageHeader::kStorageModeUncompressed: { 257 data_size = image_data_size; 258 image_data_to_write = image_data; 259 break; 260 } 261 default: { 262 LOG(FATAL) << "Unsupported"; 263 UNREACHABLE(); 264 } 265 } 266 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); 271 if (kIsDebugBuild) { 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]), 276 data_size, 277 image_data_size); 278 CHECK_EQ(decompressed_size, image_data_size); 279 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_; 280 } 281 } 282 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; 287 image_file->Erase(); 288 return false; 289 } 290 291 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for 292 // convenience. 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()); 299 } 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; 304 image_file->Erase(); 305 return false; 306 } 307 308 int err = image_file->Flush(); 309 if (err < 0) { 310 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err; 311 image_file->Erase(); 312 return false; 313 } 314 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()), 320 sizeof(ImageHeader), 321 0)) { 322 PLOG(ERROR) << "Failed to write image file header " << image_filename; 323 image_file->Erase(); 324 return false; 325 } 326 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; 331 return false; 332 } 333 } 334 return true; 335 } 336 337 void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) { 338 DCHECK(object != nullptr); 339 DCHECK_NE(offset, 0U); 340 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)); 345 } 346 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); 351 } 352 353 void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) { 354 DCHECK(object != nullptr); 355 DCHECK_NE(image_objects_offset_begin_, 0u); 356 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); 362 363 SetImageOffset(object, new_offset); 364 DCHECK_LT(new_offset, image_info.image_end_); 365 } 366 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; 371 } 372 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_); 381 return offset; 382 } 383 384 void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) { 385 DCHECK(object != nullptr); 386 DCHECK(!IsImageOffsetAssigned(object)); 387 DCHECK(!IsImageBinSlotAssigned(object)); 388 389 // Before we stomp over the lock word, save the hash code for later. 390 LockWord lw(object->GetLockWord(false)); 391 switch (lw.GetState()) { 392 case LockWord::kFatLocked: { 393 LOG(FATAL) << "Fat locked object " << object << " found during object copy"; 394 break; 395 } 396 case LockWord::kThinLocked: { 397 LOG(FATAL) << "Thin locked object " << object << " found during object copy"; 398 break; 399 } 400 case LockWord::kUnlocked: 401 // No hash, don't need to save it. 402 break; 403 case LockWord::kHashCode: 404 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end()); 405 saved_hashcode_map_.emplace(object, lw.GetHashCode()); 406 break; 407 default: 408 LOG(FATAL) << "Unreachable."; 409 UNREACHABLE(); 410 } 411 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false); 412 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u); 413 DCHECK(IsImageBinSlotAssigned(object)); 414 } 415 416 void ImageWriter::PrepareDexCacheArraySlots() { 417 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver. 418 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned() 419 // when AssignImageBinSlot() assigns their indexes out or order. 420 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) { 421 auto it = dex_file_oat_index_map_.find(dex_file); 422 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation(); 423 ImageInfo& image_info = GetImageInfo(it->second); 424 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]); 425 DexCacheArraysLayout layout(target_ptr_size_, dex_file); 426 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size(); 427 } 428 429 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 430 Thread* const self = Thread::Current(); 431 ReaderMutexLock mu(self, *class_linker->DexLock()); 432 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) { 433 mirror::DexCache* dex_cache = 434 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 435 if (dex_cache == nullptr || IsInBootImage(dex_cache)) { 436 continue; 437 } 438 const DexFile* dex_file = dex_cache->GetDexFile(); 439 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end()) 440 << "Dex cache should have been pruned " << dex_file->GetLocation() 441 << "; possibly in class path"; 442 DexCacheArraysLayout layout(target_ptr_size_, dex_file); 443 DCHECK(layout.Valid()); 444 size_t oat_index = GetOatIndexForDexCache(dex_cache); 445 ImageInfo& image_info = GetImageInfo(oat_index); 446 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file); 447 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr); 448 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(), 449 start + layout.TypesOffset(), 450 dex_cache); 451 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr); 452 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(), 453 start + layout.MethodsOffset(), 454 dex_cache); 455 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr); 456 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(), 457 start + layout.FieldsOffset(), 458 dex_cache); 459 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr); 460 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache); 461 } 462 } 463 464 void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) { 465 if (array != nullptr) { 466 DCHECK(!IsInBootImage(array)); 467 size_t oat_index = GetOatIndexForDexCache(dex_cache); 468 native_object_relocations_.emplace(array, 469 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray }); 470 } 471 } 472 473 void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) { 474 DCHECK(arr != nullptr); 475 if (kIsDebugBuild) { 476 for (size_t i = 0, len = arr->GetLength(); i < len; i++) { 477 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_); 478 if (method != nullptr && !method->IsRuntimeMethod()) { 479 mirror::Class* klass = method->GetDeclaringClass(); 480 CHECK(klass == nullptr || KeepClass(klass)) 481 << PrettyClass(klass) << " should be a kept class"; 482 } 483 } 484 } 485 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and 486 // ArtMethods. 487 pointer_arrays_.emplace(arr, kBinArtMethodClean); 488 } 489 490 void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) { 491 DCHECK(object != nullptr); 492 size_t object_size = object->SizeOf(); 493 494 // The magic happens here. We segregate objects into different bins based 495 // on how likely they are to get dirty at runtime. 496 // 497 // Likely-to-dirty objects get packed together into the same bin so that 498 // at runtime their page dirtiness ratio (how many dirty objects a page has) is 499 // maximized. 500 // 501 // This means more pages will stay either clean or shared dirty (with zygote) and 502 // the app will use less of its own (private) memory. 503 Bin bin = kBinRegular; 504 size_t current_offset = 0u; 505 506 if (kBinObjects) { 507 // 508 // Changing the bin of an object is purely a memory-use tuning. 509 // It has no change on runtime correctness. 510 // 511 // Memory analysis has determined that the following types of objects get dirtied 512 // the most: 513 // 514 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have 515 // a fixed layout which helps improve generated code (using PC-relative addressing), 516 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots(). 517 // Since these arrays are huge, most pages do not overlap other objects and it's not 518 // really important where they are for the clean/dirty separation. Due to their 519 // special PC-relative addressing, we arbitrarily keep them at the end. 520 // * Class'es which are verified [their clinit runs only at runtime] 521 // - classes in general [because their static fields get overwritten] 522 // - initialized classes with all-final statics are unlikely to be ever dirty, 523 // so bin them separately 524 // * Art Methods that are: 525 // - native [their native entry point is not looked up until runtime] 526 // - have declaring classes that aren't initialized 527 // [their interpreter/quick entry points are trampolines until the class 528 // becomes initialized] 529 // 530 // We also assume the following objects get dirtied either never or extremely rarely: 531 // * Strings (they are immutable) 532 // * Art methods that aren't native and have initialized declared classes 533 // 534 // We assume that "regular" bin objects are highly unlikely to become dirtied, 535 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio. 536 // 537 if (object->IsClass()) { 538 bin = kBinClassVerified; 539 mirror::Class* klass = object->AsClass(); 540 541 // Add non-embedded vtable to the pointer array table if there is one. 542 auto* vtable = klass->GetVTable(); 543 if (vtable != nullptr) { 544 AddMethodPointerArray(vtable); 545 } 546 auto* iftable = klass->GetIfTable(); 547 if (iftable != nullptr) { 548 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 549 if (iftable->GetMethodArrayCount(i) > 0) { 550 AddMethodPointerArray(iftable->GetMethodArray(i)); 551 } 552 } 553 } 554 555 if (klass->GetStatus() == Class::kStatusInitialized) { 556 bin = kBinClassInitialized; 557 558 // If the class's static fields are all final, put it into a separate bin 559 // since it's very likely it will stay clean. 560 uint32_t num_static_fields = klass->NumStaticFields(); 561 if (num_static_fields == 0) { 562 bin = kBinClassInitializedFinalStatics; 563 } else { 564 // Maybe all the statics are final? 565 bool all_final = true; 566 for (uint32_t i = 0; i < num_static_fields; ++i) { 567 ArtField* field = klass->GetStaticField(i); 568 if (!field->IsFinal()) { 569 all_final = false; 570 break; 571 } 572 } 573 574 if (all_final) { 575 bin = kBinClassInitializedFinalStatics; 576 } 577 } 578 } 579 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) { 580 bin = kBinString; // Strings are almost always immutable (except for object header). 581 } else if (object->GetClass<kVerifyNone>() == 582 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) { 583 // Instance of java lang object, probably a lock object. This means it will be dirty when we 584 // synchronize on it. 585 bin = kBinMiscDirty; 586 } else if (object->IsDexCache()) { 587 // Dex file field becomes dirty when the image is loaded. 588 bin = kBinMiscDirty; 589 } 590 // else bin = kBinRegular 591 } 592 593 // Assign the oat index too. 594 DCHECK(oat_index_map_.find(object) == oat_index_map_.end()); 595 oat_index_map_.emplace(object, oat_index); 596 597 ImageInfo& image_info = GetImageInfo(oat_index); 598 599 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment 600 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned). 601 // Move the current bin size up to accommodate the object we just assigned a bin slot. 602 image_info.bin_slot_sizes_[bin] += offset_delta; 603 604 BinSlot new_bin_slot(bin, current_offset); 605 SetImageBinSlot(object, new_bin_slot); 606 607 ++image_info.bin_slot_count_[bin]; 608 609 // Grow the image closer to the end by the object we just assigned. 610 image_info.image_end_ += offset_delta; 611 } 612 613 bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const { 614 if (m->IsNative()) { 615 return true; 616 } 617 mirror::Class* declaring_class = m->GetDeclaringClass(); 618 // Initialized is highly unlikely to dirty since there's no entry points to mutate. 619 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized; 620 } 621 622 bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const { 623 DCHECK(object != nullptr); 624 625 // We always stash the bin slot into a lockword, in the 'forwarding address' state. 626 // If it's in some other state, then we haven't yet assigned an image bin slot. 627 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) { 628 return false; 629 } else if (kIsDebugBuild) { 630 LockWord lock_word = object->GetLockWord(false); 631 size_t offset = lock_word.ForwardingAddress(); 632 BinSlot bin_slot(offset); 633 size_t oat_index = GetOatIndex(object); 634 const ImageInfo& image_info = GetImageInfo(oat_index); 635 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]) 636 << "bin slot offset should not exceed the size of that bin"; 637 } 638 return true; 639 } 640 641 ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const { 642 DCHECK(object != nullptr); 643 DCHECK(IsImageBinSlotAssigned(object)); 644 645 LockWord lock_word = object->GetLockWord(false); 646 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t 647 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max()); 648 649 BinSlot bin_slot(static_cast<uint32_t>(offset)); 650 size_t oat_index = GetOatIndex(object); 651 const ImageInfo& image_info = GetImageInfo(oat_index); 652 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]); 653 654 return bin_slot; 655 } 656 657 bool ImageWriter::AllocMemory() { 658 for (ImageInfo& image_info : image_infos_) { 659 ImageSection unused_sections[ImageHeader::kSectionCount]; 660 const size_t length = RoundUp( 661 image_info.CreateImageSections(unused_sections), kPageSize); 662 663 std::string error_msg; 664 image_info.image_.reset(MemMap::MapAnonymous("image writer image", 665 nullptr, 666 length, 667 PROT_READ | PROT_WRITE, 668 false, 669 false, 670 &error_msg)); 671 if (UNLIKELY(image_info.image_.get() == nullptr)) { 672 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg; 673 return false; 674 } 675 676 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_. 677 CHECK_LE(image_info.image_end_, length); 678 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create( 679 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize))); 680 if (image_info.image_bitmap_.get() == nullptr) { 681 LOG(ERROR) << "Failed to allocate memory for image bitmap"; 682 return false; 683 } 684 } 685 return true; 686 } 687 688 class ComputeLazyFieldsForClassesVisitor : public ClassVisitor { 689 public: 690 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 691 StackHandleScope<1> hs(Thread::Current()); 692 mirror::Class::ComputeName(hs.NewHandle(c)); 693 return true; 694 } 695 }; 696 697 void ImageWriter::ComputeLazyFieldsForImageClasses() { 698 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 699 ComputeLazyFieldsForClassesVisitor visitor; 700 class_linker->VisitClassesWithoutClassesLock(&visitor); 701 } 702 703 static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) { 704 return klass->GetClassLoader() == nullptr; 705 } 706 707 bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) { 708 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass); 709 } 710 711 bool ImageWriter::PruneAppImageClass(mirror::Class* klass) { 712 bool early_exit = false; 713 std::unordered_set<mirror::Class*> visited; 714 return PruneAppImageClassInternal(klass, &early_exit, &visited); 715 } 716 717 bool ImageWriter::PruneAppImageClassInternal( 718 mirror::Class* klass, 719 bool* early_exit, 720 std::unordered_set<mirror::Class*>* visited) { 721 DCHECK(early_exit != nullptr); 722 DCHECK(visited != nullptr); 723 DCHECK(compile_app_image_); 724 if (klass == nullptr || IsInBootImage(klass)) { 725 return false; 726 } 727 auto found = prune_class_memo_.find(klass); 728 if (found != prune_class_memo_.end()) { 729 // Already computed, return the found value. 730 return found->second; 731 } 732 // Circular dependencies, return false but do not store the result in the memoization table. 733 if (visited->find(klass) != visited->end()) { 734 *early_exit = true; 735 return false; 736 } 737 visited->emplace(klass); 738 bool result = IsBootClassLoaderClass(klass); 739 std::string temp; 740 // Prune if not an image class, this handles any broken sets of image classes such as having a 741 // class in the set but not it's superclass. 742 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp)); 743 bool my_early_exit = false; // Only for ourselves, ignore caller. 744 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the 745 // app image. 746 if (klass->GetStatus() == mirror::Class::kStatusError) { 747 result = true; 748 } else { 749 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass); 750 } 751 if (!result) { 752 // Check interfaces since these wont be visited through VisitReferences.) 753 mirror::IfTable* if_table = klass->GetIfTable(); 754 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) { 755 result = result || PruneAppImageClassInternal(if_table->GetInterface(i), 756 &my_early_exit, 757 visited); 758 } 759 } 760 if (klass->IsObjectArrayClass()) { 761 result = result || PruneAppImageClassInternal(klass->GetComponentType(), 762 &my_early_exit, 763 visited); 764 } 765 // Check static fields and their classes. 766 size_t num_static_fields = klass->NumReferenceStaticFields(); 767 if (num_static_fields != 0 && klass->IsResolved()) { 768 // Presumably GC can happen when we are cross compiling, it should not cause performance 769 // problems to do pointer size logic. 770 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset( 771 Runtime::Current()->GetClassLinker()->GetImagePointerSize()); 772 for (size_t i = 0u; i < num_static_fields; ++i) { 773 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset); 774 if (ref != nullptr) { 775 if (ref->IsClass()) { 776 result = result || PruneAppImageClassInternal(ref->AsClass(), 777 &my_early_exit, 778 visited); 779 } else { 780 result = result || PruneAppImageClassInternal(ref->GetClass(), 781 &my_early_exit, 782 visited); 783 } 784 } 785 field_offset = MemberOffset(field_offset.Uint32Value() + 786 sizeof(mirror::HeapReference<mirror::Object>)); 787 } 788 } 789 result = result || PruneAppImageClassInternal(klass->GetSuperClass(), 790 &my_early_exit, 791 visited); 792 // Erase the element we stored earlier since we are exiting the function. 793 auto it = visited->find(klass); 794 DCHECK(it != visited->end()); 795 visited->erase(it); 796 // Only store result if it is true or none of the calls early exited due to circular 797 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in 798 // a child call and we can remember the result. 799 if (result == true || !my_early_exit || visited->empty()) { 800 prune_class_memo_[klass] = result; 801 } 802 *early_exit |= my_early_exit; 803 return result; 804 } 805 806 bool ImageWriter::KeepClass(Class* klass) { 807 if (klass == nullptr) { 808 return false; 809 } 810 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) { 811 // Already in boot image, return true. 812 return true; 813 } 814 std::string temp; 815 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) { 816 return false; 817 } 818 if (compile_app_image_) { 819 // For app images, we need to prune boot loader classes that are not in the boot image since 820 // these may have already been loaded when the app image is loaded. 821 // Keep classes in the boot image space since we don't want to re-resolve these. 822 return !PruneAppImageClass(klass); 823 } 824 return true; 825 } 826 827 class NonImageClassesVisitor : public ClassVisitor { 828 public: 829 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {} 830 831 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 832 if (!image_writer_->KeepClass(klass)) { 833 classes_to_prune_.insert(klass); 834 } 835 return true; 836 } 837 838 std::unordered_set<mirror::Class*> classes_to_prune_; 839 ImageWriter* const image_writer_; 840 }; 841 842 void ImageWriter::PruneNonImageClasses() { 843 Runtime* runtime = Runtime::Current(); 844 ClassLinker* class_linker = runtime->GetClassLinker(); 845 Thread* self = Thread::Current(); 846 847 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class 848 // path dex caches. 849 class_linker->ClearClassTableStrongRoots(); 850 851 // Make a list of classes we would like to prune. 852 NonImageClassesVisitor visitor(this); 853 class_linker->VisitClasses(&visitor); 854 855 // Remove the undesired classes from the class roots. 856 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes"; 857 for (mirror::Class* klass : visitor.classes_to_prune_) { 858 std::string temp; 859 const char* name = klass->GetDescriptor(&temp); 860 VLOG(compiler) << "Pruning class " << name; 861 if (!compile_app_image_) { 862 DCHECK(IsBootClassLoaderClass(klass)); 863 } 864 bool result = class_linker->RemoveClass(name, klass->GetClassLoader()); 865 DCHECK(result); 866 } 867 868 // Clear references to removed classes from the DexCaches. 869 ArtMethod* resolution_method = runtime->GetResolutionMethod(); 870 871 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__); 872 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable 873 ReaderMutexLock mu2(self, *class_linker->DexLock()); 874 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) { 875 if (self->IsJWeakCleared(data.weak_root)) { 876 continue; 877 } 878 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache(); 879 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) { 880 Class* klass = dex_cache->GetResolvedType(i); 881 if (klass != nullptr && !KeepClass(klass)) { 882 dex_cache->SetResolvedType(i, nullptr); 883 } 884 } 885 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods(); 886 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) { 887 ArtMethod* method = 888 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_); 889 DCHECK(method != nullptr) << "Expected resolution method instead of null method"; 890 mirror::Class* declaring_class = method->GetDeclaringClass(); 891 // Copied methods may be held live by a class which was not an image class but have a 892 // declaring class which is an image class. Set it to the resolution method to be safe and 893 // prevent dangling pointers. 894 if (method->IsCopied() || !KeepClass(declaring_class)) { 895 mirror::DexCache::SetElementPtrSize(resolved_methods, 896 i, 897 resolution_method, 898 target_ptr_size_); 899 } else { 900 // Check that the class is still in the classes table. 901 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class " 902 << PrettyClass(declaring_class) << " not in class linker table"; 903 } 904 } 905 ArtField** resolved_fields = dex_cache->GetResolvedFields(); 906 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) { 907 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_); 908 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) { 909 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_); 910 } 911 } 912 // Clean the dex field. It might have been populated during the initialization phase, but 913 // contains data only valid during a real run. 914 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr); 915 } 916 917 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live. 918 class_linker->DropFindArrayClassCache(); 919 920 // Clear to save RAM. 921 prune_class_memo_.clear(); 922 } 923 924 void ImageWriter::CheckNonImageClassesRemoved() { 925 if (compiler_driver_.GetImageClasses() != nullptr) { 926 gc::Heap* heap = Runtime::Current()->GetHeap(); 927 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this); 928 } 929 } 930 931 void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) { 932 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg); 933 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) { 934 Class* klass = obj->AsClass(); 935 if (!image_writer->KeepClass(klass)) { 936 image_writer->DumpImageClasses(); 937 std::string temp; 938 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp) 939 << " " << PrettyDescriptor(klass); 940 } 941 } 942 } 943 944 void ImageWriter::DumpImageClasses() { 945 auto image_classes = compiler_driver_.GetImageClasses(); 946 CHECK(image_classes != nullptr); 947 for (const std::string& image_class : *image_classes) { 948 LOG(INFO) << " " << image_class; 949 } 950 } 951 952 mirror::String* ImageWriter::FindInternedString(mirror::String* string) { 953 Thread* const self = Thread::Current(); 954 for (const ImageInfo& image_info : image_infos_) { 955 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string); 956 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr) 957 << string->ToModifiedUtf8(); 958 if (found != nullptr) { 959 return found; 960 } 961 } 962 if (compile_app_image_) { 963 Runtime* const runtime = Runtime::Current(); 964 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string); 965 // If we found it in the runtime intern table it could either be in the boot image or interned 966 // during app image compilation. If it was in the boot image return that, otherwise return null 967 // since it belongs to another image space. 968 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) { 969 return found; 970 } 971 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr) 972 << string->ToModifiedUtf8(); 973 } 974 return nullptr; 975 } 976 977 978 ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const { 979 Runtime* runtime = Runtime::Current(); 980 ClassLinker* class_linker = runtime->GetClassLinker(); 981 Thread* self = Thread::Current(); 982 StackHandleScope<3> hs(self); 983 Handle<Class> object_array_class(hs.NewHandle( 984 class_linker->FindSystemClass(self, "[Ljava/lang/Object;"))); 985 986 std::unordered_set<const DexFile*> image_dex_files; 987 for (auto& pair : dex_file_oat_index_map_) { 988 const DexFile* image_dex_file = pair.first; 989 size_t image_oat_index = pair.second; 990 if (oat_index == image_oat_index) { 991 image_dex_files.insert(image_dex_file); 992 } 993 } 994 995 // build an Object[] of all the DexCaches used in the source_space_. 996 // Since we can't hold the dex lock when allocating the dex_caches 997 // ObjectArray, we lock the dex lock twice, first to get the number 998 // of dex caches first and then lock it again to copy the dex 999 // caches. We check that the number of dex caches does not change. 1000 size_t dex_cache_count = 0; 1001 { 1002 ReaderMutexLock mu(self, *class_linker->DexLock()); 1003 // Count number of dex caches not in the boot image. 1004 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) { 1005 mirror::DexCache* dex_cache = 1006 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 1007 if (dex_cache == nullptr) { 1008 continue; 1009 } 1010 const DexFile* dex_file = dex_cache->GetDexFile(); 1011 if (!IsInBootImage(dex_cache)) { 1012 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u; 1013 } 1014 } 1015 } 1016 Handle<ObjectArray<Object>> dex_caches( 1017 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count))); 1018 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array."; 1019 { 1020 ReaderMutexLock mu(self, *class_linker->DexLock()); 1021 size_t non_image_dex_caches = 0; 1022 // Re-count number of non image dex caches. 1023 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) { 1024 mirror::DexCache* dex_cache = 1025 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 1026 if (dex_cache == nullptr) { 1027 continue; 1028 } 1029 const DexFile* dex_file = dex_cache->GetDexFile(); 1030 if (!IsInBootImage(dex_cache)) { 1031 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u; 1032 } 1033 } 1034 CHECK_EQ(dex_cache_count, non_image_dex_caches) 1035 << "The number of non-image dex caches changed."; 1036 size_t i = 0; 1037 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) { 1038 mirror::DexCache* dex_cache = 1039 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 1040 if (dex_cache == nullptr) { 1041 continue; 1042 } 1043 const DexFile* dex_file = dex_cache->GetDexFile(); 1044 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) { 1045 dex_caches->Set<false>(i, dex_cache); 1046 ++i; 1047 } 1048 } 1049 } 1050 1051 // build an Object[] of the roots needed to restore the runtime 1052 auto image_roots(hs.NewHandle( 1053 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax))); 1054 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get()); 1055 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots()); 1056 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) { 1057 CHECK(image_roots->Get(i) != nullptr); 1058 } 1059 return image_roots.Get(); 1060 } 1061 1062 mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack, 1063 mirror::Object* obj, 1064 size_t oat_index) { 1065 if (obj == nullptr || IsInBootImage(obj)) { 1066 // Object is null or already in the image, there is no work to do. 1067 return obj; 1068 } 1069 if (!IsImageBinSlotAssigned(obj)) { 1070 // We want to intern all strings but also assign offsets for the source string. Since the 1071 // pruning phase has already happened, if we intern a string to one in the image we still 1072 // end up copying an unreachable string. 1073 if (obj->IsString()) { 1074 // Need to check if the string is already interned in another image info so that we don't have 1075 // the intern tables of two different images contain the same string. 1076 mirror::String* interned = FindInternedString(obj->AsString()); 1077 if (interned == nullptr) { 1078 // Not in another image space, insert to our table. 1079 interned = GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()); 1080 DCHECK_EQ(interned, obj); 1081 } 1082 } else if (obj->IsDexCache()) { 1083 oat_index = GetOatIndexForDexCache(obj->AsDexCache()); 1084 } else if (obj->IsClass()) { 1085 // Visit and assign offsets for fields and field arrays. 1086 mirror::Class* as_klass = obj->AsClass(); 1087 mirror::DexCache* dex_cache = as_klass->GetDexCache(); 1088 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError); 1089 if (compile_app_image_) { 1090 // Extra sanity, no boot loader classes should be left! 1091 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass); 1092 } 1093 LengthPrefixedArray<ArtField>* fields[] = { 1094 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(), 1095 }; 1096 // Overwrite the oat index value since the class' dex cache is more accurate of where it 1097 // belongs. 1098 oat_index = GetOatIndexForDexCache(dex_cache); 1099 ImageInfo& image_info = GetImageInfo(oat_index); 1100 { 1101 // Note: This table is only accessed from the image writer, avoid locking to prevent lock 1102 // order violations from root visiting. 1103 image_info.class_table_->InsertWithoutLocks(as_klass); 1104 } 1105 for (LengthPrefixedArray<ArtField>* cur_fields : fields) { 1106 // Total array length including header. 1107 if (cur_fields != nullptr) { 1108 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0); 1109 // Forward the entire array at once. 1110 auto it = native_object_relocations_.find(cur_fields); 1111 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields 1112 << " already forwarded"; 1113 size_t& offset = image_info.bin_slot_sizes_[kBinArtField]; 1114 DCHECK(!IsInBootImage(cur_fields)); 1115 native_object_relocations_.emplace( 1116 cur_fields, 1117 NativeObjectRelocation { 1118 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray 1119 }); 1120 offset += header_size; 1121 // Forward individual fields so that we can quickly find where they belong. 1122 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) { 1123 // Need to forward arrays separate of fields. 1124 ArtField* field = &cur_fields->At(i); 1125 auto it2 = native_object_relocations_.find(field); 1126 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i 1127 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic(); 1128 DCHECK(!IsInBootImage(field)); 1129 native_object_relocations_.emplace( 1130 field, 1131 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField }); 1132 offset += sizeof(ArtField); 1133 } 1134 } 1135 } 1136 // Visit and assign offsets for methods. 1137 size_t num_methods = as_klass->NumMethods(); 1138 if (num_methods != 0) { 1139 bool any_dirty = false; 1140 for (auto& m : as_klass->GetMethods(target_ptr_size_)) { 1141 if (WillMethodBeDirty(&m)) { 1142 any_dirty = true; 1143 break; 1144 } 1145 } 1146 NativeObjectRelocationType type = any_dirty 1147 ? kNativeObjectRelocationTypeArtMethodDirty 1148 : kNativeObjectRelocationTypeArtMethodClean; 1149 Bin bin_type = BinTypeForNativeRelocationType(type); 1150 // Forward the entire array at once, but header first. 1151 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_); 1152 const size_t method_size = ArtMethod::Size(target_ptr_size_); 1153 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0, 1154 method_size, 1155 method_alignment); 1156 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr(); 1157 auto it = native_object_relocations_.find(array); 1158 CHECK(it == native_object_relocations_.end()) 1159 << "Method array " << array << " already forwarded"; 1160 size_t& offset = image_info.bin_slot_sizes_[bin_type]; 1161 DCHECK(!IsInBootImage(array)); 1162 native_object_relocations_.emplace(array, 1163 NativeObjectRelocation { 1164 oat_index, 1165 offset, 1166 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty 1167 : kNativeObjectRelocationTypeArtMethodArrayClean }); 1168 offset += header_size; 1169 for (auto& m : as_klass->GetMethods(target_ptr_size_)) { 1170 AssignMethodOffset(&m, type, oat_index); 1171 } 1172 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods; 1173 } 1174 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables 1175 // live. 1176 if (as_klass->ShouldHaveImt()) { 1177 ImTable* imt = as_klass->GetImt(target_ptr_size_); 1178 for (size_t i = 0; i < ImTable::kSize; ++i) { 1179 ArtMethod* imt_method = imt->Get(i, target_ptr_size_); 1180 DCHECK(imt_method != nullptr); 1181 if (imt_method->IsRuntimeMethod() && 1182 !IsInBootImage(imt_method) && 1183 !NativeRelocationAssigned(imt_method)) { 1184 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index); 1185 } 1186 } 1187 } 1188 1189 if (as_klass->ShouldHaveImt()) { 1190 ImTable* imt = as_klass->GetImt(target_ptr_size_); 1191 TryAssignImTableOffset(imt, oat_index); 1192 } 1193 } else if (obj->IsClassLoader()) { 1194 // Register the class loader if it has a class table. 1195 // The fake boot class loader should not get registered and we should end up with only one 1196 // class loader. 1197 mirror::ClassLoader* class_loader = obj->AsClassLoader(); 1198 if (class_loader->GetClassTable() != nullptr) { 1199 class_loaders_.insert(class_loader); 1200 } 1201 } 1202 AssignImageBinSlot(obj, oat_index); 1203 work_stack.emplace(obj, oat_index); 1204 } 1205 if (obj->IsString()) { 1206 // Always return the interned string if there exists one. 1207 mirror::String* interned = FindInternedString(obj->AsString()); 1208 if (interned != nullptr) { 1209 return interned; 1210 } 1211 } 1212 return obj; 1213 } 1214 1215 bool ImageWriter::NativeRelocationAssigned(void* ptr) const { 1216 return native_object_relocations_.find(ptr) != native_object_relocations_.end(); 1217 } 1218 1219 void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) { 1220 // No offset, or already assigned. 1221 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) { 1222 return; 1223 } 1224 // If the method is a conflict method we also want to assign the conflict table offset. 1225 ImageInfo& image_info = GetImageInfo(oat_index); 1226 const size_t size = ImTable::SizeInBytes(target_ptr_size_); 1227 native_object_relocations_.emplace( 1228 imt, 1229 NativeObjectRelocation { 1230 oat_index, 1231 image_info.bin_slot_sizes_[kBinImTable], 1232 kNativeObjectRelocationTypeIMTable}); 1233 image_info.bin_slot_sizes_[kBinImTable] += size; 1234 } 1235 1236 void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) { 1237 // No offset, or already assigned. 1238 if (table == nullptr || NativeRelocationAssigned(table)) { 1239 return; 1240 } 1241 CHECK(!IsInBootImage(table)); 1242 // If the method is a conflict method we also want to assign the conflict table offset. 1243 ImageInfo& image_info = GetImageInfo(oat_index); 1244 const size_t size = table->ComputeSize(target_ptr_size_); 1245 native_object_relocations_.emplace( 1246 table, 1247 NativeObjectRelocation { 1248 oat_index, 1249 image_info.bin_slot_sizes_[kBinIMTConflictTable], 1250 kNativeObjectRelocationTypeIMTConflictTable}); 1251 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size; 1252 } 1253 1254 void ImageWriter::AssignMethodOffset(ArtMethod* method, 1255 NativeObjectRelocationType type, 1256 size_t oat_index) { 1257 DCHECK(!IsInBootImage(method)); 1258 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned " 1259 << PrettyMethod(method); 1260 if (method->IsRuntimeMethod()) { 1261 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index); 1262 } 1263 ImageInfo& image_info = GetImageInfo(oat_index); 1264 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)]; 1265 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type }); 1266 offset += ArtMethod::Size(target_ptr_size_); 1267 } 1268 1269 void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) { 1270 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg); 1271 DCHECK(writer != nullptr); 1272 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) { 1273 CHECK(writer->IsImageBinSlotAssigned(obj)) << PrettyTypeOf(obj) << " " << obj; 1274 } 1275 } 1276 1277 void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) { 1278 Monitor::Deflate(Thread::Current(), obj); 1279 } 1280 1281 void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) { 1282 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg); 1283 DCHECK(writer != nullptr); 1284 if (!writer->IsInBootImage(obj)) { 1285 writer->UnbinObjectsIntoOffset(obj); 1286 } 1287 } 1288 1289 void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) { 1290 DCHECK(!IsInBootImage(obj)); 1291 CHECK(obj != nullptr); 1292 1293 // We know the bin slot, and the total bin sizes for all objects by now, 1294 // so calculate the object's final image offset. 1295 1296 DCHECK(IsImageBinSlotAssigned(obj)); 1297 BinSlot bin_slot = GetImageBinSlot(obj); 1298 // Change the lockword from a bin slot into an offset 1299 AssignImageOffset(obj, bin_slot); 1300 } 1301 1302 class ImageWriter::VisitReferencesVisitor { 1303 public: 1304 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index) 1305 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {} 1306 1307 // Fix up separately since we also need to fix up method entrypoints. 1308 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const 1309 SHARED_REQUIRES(Locks::mutator_lock_) { 1310 if (!root->IsNull()) { 1311 VisitRoot(root); 1312 } 1313 } 1314 1315 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const 1316 SHARED_REQUIRES(Locks::mutator_lock_) { 1317 root->Assign(VisitReference(root->AsMirrorPtr())); 1318 } 1319 1320 ALWAYS_INLINE void operator() (mirror::Object* obj, 1321 MemberOffset offset, 1322 bool is_static ATTRIBUTE_UNUSED) const 1323 SHARED_REQUIRES(Locks::mutator_lock_) { 1324 mirror::Object* ref = 1325 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset); 1326 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref)); 1327 } 1328 1329 ALWAYS_INLINE void operator() (mirror::Class* klass ATTRIBUTE_UNUSED, 1330 mirror::Reference* ref) const 1331 SHARED_REQUIRES(Locks::mutator_lock_) { 1332 ref->SetReferent</*kTransactionActive*/false>( 1333 VisitReference(ref->GetReferent<kWithoutReadBarrier>())); 1334 } 1335 1336 private: 1337 mirror::Object* VisitReference(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_) { 1338 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_); 1339 } 1340 1341 ImageWriter* const image_writer_; 1342 WorkStack* const work_stack_; 1343 const size_t oat_index_; 1344 }; 1345 1346 class ImageWriter::GetRootsVisitor : public RootVisitor { 1347 public: 1348 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {} 1349 1350 void VisitRoots(mirror::Object*** roots, 1351 size_t count, 1352 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE 1353 SHARED_REQUIRES(Locks::mutator_lock_) { 1354 for (size_t i = 0; i < count; ++i) { 1355 roots_->push_back(*roots[i]); 1356 } 1357 } 1358 1359 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, 1360 size_t count, 1361 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE 1362 SHARED_REQUIRES(Locks::mutator_lock_) { 1363 for (size_t i = 0; i < count; ++i) { 1364 roots_->push_back(roots[i]->AsMirrorPtr()); 1365 } 1366 } 1367 1368 private: 1369 std::vector<mirror::Object*>* const roots_; 1370 }; 1371 1372 void ImageWriter::ProcessWorkStack(WorkStack* work_stack) { 1373 while (!work_stack->empty()) { 1374 std::pair<mirror::Object*, size_t> pair(work_stack->top()); 1375 work_stack->pop(); 1376 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second); 1377 // Walk references and assign bin slots for them. 1378 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>( 1379 visitor, 1380 visitor); 1381 } 1382 } 1383 1384 void ImageWriter::CalculateNewObjectOffsets() { 1385 Thread* const self = Thread::Current(); 1386 StackHandleScopeCollection handles(self); 1387 std::vector<Handle<ObjectArray<Object>>> image_roots; 1388 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) { 1389 image_roots.push_back(handles.NewHandle(CreateImageRoots(i))); 1390 } 1391 1392 Runtime* const runtime = Runtime::Current(); 1393 gc::Heap* const heap = runtime->GetHeap(); 1394 1395 // Leave space for the header, but do not write it yet, we need to 1396 // know where image_roots is going to end up 1397 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment 1398 1399 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_); 1400 // Write the image runtime methods. 1401 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod(); 1402 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod(); 1403 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod(); 1404 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll); 1405 image_methods_[ImageHeader::kRefsOnlySaveMethod] = 1406 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly); 1407 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] = 1408 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs); 1409 // Visit image methods first to have the main runtime methods in the first image. 1410 for (auto* m : image_methods_) { 1411 CHECK(m != nullptr); 1412 CHECK(m->IsRuntimeMethod()); 1413 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image"; 1414 if (!IsInBootImage(m)) { 1415 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex()); 1416 } 1417 } 1418 1419 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring 1420 // this lock while holding other locks may cause lock order violations. 1421 heap->VisitObjects(DeflateMonitorCallback, this); 1422 1423 // Work list of <object, oat_index> for objects. Everything on the stack must already be 1424 // assigned a bin slot. 1425 WorkStack work_stack; 1426 1427 // Special case interned strings to put them in the image they are likely to be resolved from. 1428 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) { 1429 auto it = dex_file_oat_index_map_.find(dex_file); 1430 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation(); 1431 const size_t oat_index = it->second; 1432 InternTable* const intern_table = runtime->GetInternTable(); 1433 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) { 1434 uint32_t utf16_length; 1435 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length); 1436 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data); 1437 TryAssignBinSlot(work_stack, string, oat_index); 1438 } 1439 } 1440 1441 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor 1442 // visits roots while holding various locks. 1443 { 1444 std::vector<mirror::Object*> roots; 1445 GetRootsVisitor root_visitor(&roots); 1446 runtime->VisitRoots(&root_visitor); 1447 for (mirror::Object* obj : roots) { 1448 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex()); 1449 } 1450 } 1451 ProcessWorkStack(&work_stack); 1452 1453 // For app images, there may be objects that are only held live by the by the boot image. One 1454 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback 1455 // does not fail any checks. TODO: We should probably avoid copying these objects. 1456 if (compile_app_image_) { 1457 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) { 1458 DCHECK(space->IsImageSpace()); 1459 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap(); 1460 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()), 1461 reinterpret_cast<uintptr_t>(space->Limit()), 1462 [this, &work_stack](mirror::Object* obj) 1463 SHARED_REQUIRES(Locks::mutator_lock_) { 1464 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex()); 1465 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot). 1466 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>( 1467 visitor, 1468 visitor); 1469 }); 1470 } 1471 // Process the work stack in case anything was added by TryAssignBinSlot. 1472 ProcessWorkStack(&work_stack); 1473 } 1474 1475 // Verify that all objects have assigned image bin slots. 1476 heap->VisitObjects(EnsureBinSlotAssignedCallback, this); 1477 1478 // Calculate size of the dex cache arrays slot and prepare offsets. 1479 PrepareDexCacheArraySlots(); 1480 1481 // Calculate the sizes of the intern tables and class tables. 1482 for (ImageInfo& image_info : image_infos_) { 1483 // Calculate how big the intern table will be after being serialized. 1484 InternTable* const intern_table = image_info.intern_table_.get(); 1485 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings"; 1486 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr); 1487 // Calculate the size of the class table. 1488 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1489 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr); 1490 } 1491 1492 // Calculate bin slot offsets. 1493 for (ImageInfo& image_info : image_infos_) { 1494 size_t bin_offset = image_objects_offset_begin_; 1495 for (size_t i = 0; i != kBinSize; ++i) { 1496 switch (i) { 1497 case kBinArtMethodClean: 1498 case kBinArtMethodDirty: { 1499 bin_offset = RoundUp(bin_offset, method_alignment); 1500 break; 1501 } 1502 case kBinImTable: 1503 case kBinIMTConflictTable: { 1504 bin_offset = RoundUp(bin_offset, target_ptr_size_); 1505 break; 1506 } 1507 default: { 1508 // Normal alignment. 1509 } 1510 } 1511 image_info.bin_slot_offsets_[i] = bin_offset; 1512 bin_offset += image_info.bin_slot_sizes_[i]; 1513 } 1514 // NOTE: There may be additional padding between the bin slots and the intern table. 1515 DCHECK_EQ(image_info.image_end_, 1516 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_); 1517 } 1518 1519 // Calculate image offsets. 1520 size_t image_offset = 0; 1521 for (ImageInfo& image_info : image_infos_) { 1522 image_info.image_begin_ = global_image_begin_ + image_offset; 1523 image_info.image_offset_ = image_offset; 1524 ImageSection unused_sections[ImageHeader::kSectionCount]; 1525 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize); 1526 // There should be no gaps until the next image. 1527 image_offset += image_info.image_size_; 1528 } 1529 1530 // Transform each object's bin slot into an offset which will be used to do the final copy. 1531 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this); 1532 1533 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_); 1534 1535 size_t i = 0; 1536 for (ImageInfo& image_info : image_infos_) { 1537 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get())); 1538 i++; 1539 } 1540 1541 // Update the native relocations by adding their bin sums. 1542 for (auto& pair : native_object_relocations_) { 1543 NativeObjectRelocation& relocation = pair.second; 1544 Bin bin_type = BinTypeForNativeRelocationType(relocation.type); 1545 ImageInfo& image_info = GetImageInfo(relocation.oat_index); 1546 relocation.offset += image_info.bin_slot_offsets_[bin_type]; 1547 } 1548 1549 // Note that image_info.image_end_ is left at end of used mirror object section. 1550 } 1551 1552 size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const { 1553 DCHECK(out_sections != nullptr); 1554 1555 // Do not round up any sections here that are represented by the bins since it will break 1556 // offsets. 1557 1558 // Objects section 1559 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects]; 1560 *objects_section = ImageSection(0u, image_end_); 1561 1562 // Add field section. 1563 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields]; 1564 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]); 1565 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset()); 1566 1567 // Add method section. 1568 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods]; 1569 *methods_section = ImageSection( 1570 bin_slot_offsets_[kBinArtMethodClean], 1571 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]); 1572 1573 // IMT section. 1574 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables]; 1575 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]); 1576 1577 // Conflict tables section. 1578 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables]; 1579 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable], 1580 bin_slot_sizes_[kBinIMTConflictTable]); 1581 1582 // Runtime methods section. 1583 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods]; 1584 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod], 1585 bin_slot_sizes_[kBinRuntimeMethod]); 1586 1587 // Add dex cache arrays section. 1588 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays]; 1589 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray], 1590 bin_slot_sizes_[kBinDexCacheArray]); 1591 1592 // Round up to the alignment the string table expects. See HashSet::WriteToMemory. 1593 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t)); 1594 // Calculate the size of the interned strings. 1595 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings]; 1596 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_); 1597 cur_pos = interned_strings_section->End(); 1598 // Round up to the alignment the class table expects. See HashSet::WriteToMemory. 1599 cur_pos = RoundUp(cur_pos, sizeof(uint64_t)); 1600 // Calculate the size of the class table section. 1601 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable]; 1602 *class_table_section = ImageSection(cur_pos, class_table_bytes_); 1603 cur_pos = class_table_section->End(); 1604 // Image end goes right before the start of the image bitmap. 1605 return cur_pos; 1606 } 1607 1608 void ImageWriter::CreateHeader(size_t oat_index) { 1609 ImageInfo& image_info = GetImageInfo(oat_index); 1610 const uint8_t* oat_file_begin = image_info.oat_file_begin_; 1611 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_; 1612 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_; 1613 1614 // Create the image sections. 1615 ImageSection sections[ImageHeader::kSectionCount]; 1616 const size_t image_end = image_info.CreateImageSections(sections); 1617 1618 // Finally bitmap section. 1619 const size_t bitmap_bytes = image_info.image_bitmap_->Size(); 1620 auto* bitmap_section = §ions[ImageHeader::kSectionImageBitmap]; 1621 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize)); 1622 if (VLOG_IS_ON(compiler)) { 1623 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index]; 1624 size_t idx = 0; 1625 for (const ImageSection& section : sections) { 1626 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section; 1627 ++idx; 1628 } 1629 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_; 1630 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec; 1631 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_) 1632 << " Image offset=" << image_info.image_offset_ << std::dec; 1633 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin) 1634 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_) 1635 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end) 1636 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end); 1637 } 1638 // Store boot image info for app image so that we can relocate. 1639 uint32_t boot_image_begin = 0; 1640 uint32_t boot_image_end = 0; 1641 uint32_t boot_oat_begin = 0; 1642 uint32_t boot_oat_end = 0; 1643 gc::Heap* const heap = Runtime::Current()->GetHeap(); 1644 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end); 1645 1646 // Create the header, leave 0 for data size since we will fill this in as we are writing the 1647 // image. 1648 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_), 1649 image_end, 1650 sections, 1651 image_info.image_roots_address_, 1652 image_info.oat_checksum_, 1653 PointerToLowMemUInt32(oat_file_begin), 1654 PointerToLowMemUInt32(image_info.oat_data_begin_), 1655 PointerToLowMemUInt32(oat_data_end), 1656 PointerToLowMemUInt32(oat_file_end), 1657 boot_image_begin, 1658 boot_image_end - boot_image_begin, 1659 boot_oat_begin, 1660 boot_oat_end - boot_oat_begin, 1661 target_ptr_size_, 1662 compile_pic_, 1663 /*is_pic*/compile_app_image_, 1664 image_storage_mode_, 1665 /*data_size*/0u); 1666 } 1667 1668 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) { 1669 auto it = native_object_relocations_.find(method); 1670 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method; 1671 size_t oat_index = GetOatIndex(method->GetDexCache()); 1672 ImageInfo& image_info = GetImageInfo(oat_index); 1673 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects"; 1674 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset); 1675 } 1676 1677 class FixupRootVisitor : public RootVisitor { 1678 public: 1679 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) { 1680 } 1681 1682 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) 1683 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 1684 for (size_t i = 0; i < count; ++i) { 1685 *roots[i] = image_writer_->GetImageAddress(*roots[i]); 1686 } 1687 } 1688 1689 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count, 1690 const RootInfo& info ATTRIBUTE_UNUSED) 1691 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 1692 for (size_t i = 0; i < count; ++i) { 1693 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr())); 1694 } 1695 } 1696 1697 private: 1698 ImageWriter* const image_writer_; 1699 }; 1700 1701 void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) { 1702 for (size_t i = 0; i < ImTable::kSize; ++i) { 1703 ArtMethod* method = orig->Get(i, target_ptr_size_); 1704 copy->Set(i, NativeLocationInImage(method), target_ptr_size_); 1705 } 1706 } 1707 1708 void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) { 1709 const size_t count = orig->NumEntries(target_ptr_size_); 1710 for (size_t i = 0; i < count; ++i) { 1711 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_); 1712 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_); 1713 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method)); 1714 copy->SetImplementationMethod(i, 1715 target_ptr_size_, 1716 NativeLocationInImage(implementation_method)); 1717 } 1718 } 1719 1720 void ImageWriter::CopyAndFixupNativeData(size_t oat_index) { 1721 const ImageInfo& image_info = GetImageInfo(oat_index); 1722 // Copy ArtFields and methods to their locations and update the array for convenience. 1723 for (auto& pair : native_object_relocations_) { 1724 NativeObjectRelocation& relocation = pair.second; 1725 // Only work with fields and methods that are in the current oat file. 1726 if (relocation.oat_index != oat_index) { 1727 continue; 1728 } 1729 auto* dest = image_info.image_->Begin() + relocation.offset; 1730 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_); 1731 DCHECK(!IsInBootImage(pair.first)); 1732 switch (relocation.type) { 1733 case kNativeObjectRelocationTypeArtField: { 1734 memcpy(dest, pair.first, sizeof(ArtField)); 1735 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass( 1736 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass())); 1737 break; 1738 } 1739 case kNativeObjectRelocationTypeRuntimeMethod: 1740 case kNativeObjectRelocationTypeArtMethodClean: 1741 case kNativeObjectRelocationTypeArtMethodDirty: { 1742 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first), 1743 reinterpret_cast<ArtMethod*>(dest), 1744 image_info); 1745 break; 1746 } 1747 // For arrays, copy just the header since the elements will get copied by their corresponding 1748 // relocations. 1749 case kNativeObjectRelocationTypeArtFieldArray: { 1750 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0)); 1751 break; 1752 } 1753 case kNativeObjectRelocationTypeArtMethodArrayClean: 1754 case kNativeObjectRelocationTypeArtMethodArrayDirty: { 1755 size_t size = ArtMethod::Size(target_ptr_size_); 1756 size_t alignment = ArtMethod::Alignment(target_ptr_size_); 1757 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment)); 1758 // Clear padding to avoid non-deterministic data in the image (and placate valgrind). 1759 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment); 1760 break; 1761 } 1762 case kNativeObjectRelocationTypeDexCacheArray: 1763 // Nothing to copy here, everything is done in FixupDexCache(). 1764 break; 1765 case kNativeObjectRelocationTypeIMTable: { 1766 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first); 1767 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest); 1768 CopyAndFixupImTable(orig_imt, dest_imt); 1769 break; 1770 } 1771 case kNativeObjectRelocationTypeIMTConflictTable: { 1772 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first); 1773 CopyAndFixupImtConflictTable( 1774 orig_table, 1775 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_)); 1776 break; 1777 } 1778 } 1779 } 1780 // Fixup the image method roots. 1781 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin()); 1782 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) { 1783 ArtMethod* method = image_methods_[i]; 1784 CHECK(method != nullptr); 1785 if (!IsInBootImage(method)) { 1786 method = NativeLocationInImage(method); 1787 } 1788 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method); 1789 } 1790 FixupRootVisitor root_visitor(this); 1791 1792 // Write the intern table into the image. 1793 if (image_info.intern_table_bytes_ > 0) { 1794 const ImageSection& intern_table_section = image_header->GetImageSection( 1795 ImageHeader::kSectionInternedStrings); 1796 InternTable* const intern_table = image_info.intern_table_.get(); 1797 uint8_t* const intern_table_memory_ptr = 1798 image_info.image_->Begin() + intern_table_section.Offset(); 1799 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr); 1800 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_); 1801 // Fixup the pointers in the newly written intern table to contain image addresses. 1802 InternTable temp_intern_table; 1803 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that 1804 // the VisitRoots() will update the memory directly rather than the copies. 1805 // This also relies on visit roots not doing any verification which could fail after we update 1806 // the roots to be the image addresses. 1807 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr); 1808 CHECK_EQ(temp_intern_table.Size(), intern_table->Size()); 1809 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots); 1810 } 1811 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple 1812 // class loaders. Writing multiple class tables into the image is currently unsupported. 1813 if (image_info.class_table_bytes_ > 0u) { 1814 const ImageSection& class_table_section = image_header->GetImageSection( 1815 ImageHeader::kSectionClassTable); 1816 uint8_t* const class_table_memory_ptr = 1817 image_info.image_->Begin() + class_table_section.Offset(); 1818 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1819 1820 ClassTable* table = image_info.class_table_.get(); 1821 CHECK(table != nullptr); 1822 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr); 1823 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_); 1824 // Fixup the pointers in the newly written class table to contain image addresses. See 1825 // above comment for intern tables. 1826 ClassTable temp_class_table; 1827 temp_class_table.ReadFromMemory(class_table_memory_ptr); 1828 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() + 1829 table->NumZygoteClasses()); 1830 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor, 1831 RootInfo(kRootUnknown)); 1832 temp_class_table.VisitRoots(buffered_visitor); 1833 } 1834 } 1835 1836 void ImageWriter::CopyAndFixupObjects() { 1837 gc::Heap* heap = Runtime::Current()->GetHeap(); 1838 heap->VisitObjects(CopyAndFixupObjectsCallback, this); 1839 // Fix up the object previously had hash codes. 1840 for (const auto& hash_pair : saved_hashcode_map_) { 1841 Object* obj = hash_pair.first; 1842 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U); 1843 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false); 1844 } 1845 saved_hashcode_map_.clear(); 1846 } 1847 1848 void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) { 1849 DCHECK(obj != nullptr); 1850 DCHECK(arg != nullptr); 1851 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj); 1852 } 1853 1854 void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr, 1855 mirror::Class* klass, Bin array_type) { 1856 CHECK(klass->IsArrayClass()); 1857 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr; 1858 // Fixup int and long pointers for the ArtMethod or ArtField arrays. 1859 const size_t num_elements = arr->GetLength(); 1860 dst->SetClass(GetImageAddress(arr->GetClass())); 1861 auto* dest_array = down_cast<mirror::PointerArray*>(dst); 1862 for (size_t i = 0, count = num_elements; i < count; ++i) { 1863 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_); 1864 if (elem != nullptr && !IsInBootImage(elem)) { 1865 auto it = native_object_relocations_.find(elem); 1866 if (UNLIKELY(it == native_object_relocations_.end())) { 1867 if (it->second.IsArtMethodRelocation()) { 1868 auto* method = reinterpret_cast<ArtMethod*>(elem); 1869 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ " 1870 << method << " idx=" << i << "/" << num_elements << " with declaring class " 1871 << PrettyClass(method->GetDeclaringClass()); 1872 } else { 1873 CHECK_EQ(array_type, kBinArtField); 1874 auto* field = reinterpret_cast<ArtField*>(elem); 1875 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ " 1876 << field << " idx=" << i << "/" << num_elements << " with declaring class " 1877 << PrettyClass(field->GetDeclaringClass()); 1878 } 1879 UNREACHABLE(); 1880 } else { 1881 ImageInfo& image_info = GetImageInfo(it->second.oat_index); 1882 elem = image_info.image_begin_ + it->second.offset; 1883 } 1884 } 1885 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_); 1886 } 1887 } 1888 1889 void ImageWriter::CopyAndFixupObject(Object* obj) { 1890 if (IsInBootImage(obj)) { 1891 return; 1892 } 1893 size_t offset = GetImageOffset(obj); 1894 size_t oat_index = GetOatIndex(obj); 1895 ImageInfo& image_info = GetImageInfo(oat_index); 1896 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset); 1897 DCHECK_LT(offset, image_info.image_end_); 1898 const auto* src = reinterpret_cast<const uint8_t*>(obj); 1899 1900 image_info.image_bitmap_->Set(dst); // Mark the obj as live. 1901 1902 const size_t n = obj->SizeOf(); 1903 DCHECK_LE(offset + n, image_info.image_->Size()); 1904 memcpy(dst, src, n); 1905 1906 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor 1907 // word. 1908 const auto it = saved_hashcode_map_.find(obj); 1909 dst->SetLockWord(it != saved_hashcode_map_.end() ? 1910 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false); 1911 FixupObject(obj, dst); 1912 } 1913 1914 // Rewrite all the references in the copied object to point to their image address equivalent 1915 class FixupVisitor { 1916 public: 1917 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) { 1918 } 1919 1920 // Ignore class roots since we don't have a way to map them to the destination. These are handled 1921 // with other logic. 1922 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) 1923 const {} 1924 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {} 1925 1926 1927 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const 1928 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) { 1929 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset); 1930 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the 1931 // image. 1932 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>( 1933 offset, 1934 image_writer_->GetImageAddress(ref)); 1935 } 1936 1937 // java.lang.ref.Reference visitor. 1938 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const 1939 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) { 1940 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>( 1941 mirror::Reference::ReferentOffset(), 1942 image_writer_->GetImageAddress(ref->GetReferent())); 1943 } 1944 1945 protected: 1946 ImageWriter* const image_writer_; 1947 mirror::Object* const copy_; 1948 }; 1949 1950 class FixupClassVisitor FINAL : public FixupVisitor { 1951 public: 1952 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) { 1953 } 1954 1955 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const 1956 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) { 1957 DCHECK(obj->IsClass()); 1958 FixupVisitor::operator()(obj, offset, /*is_static*/false); 1959 } 1960 1961 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, 1962 mirror::Reference* ref ATTRIBUTE_UNUSED) const 1963 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) { 1964 LOG(FATAL) << "Reference not expected here."; 1965 } 1966 }; 1967 1968 uintptr_t ImageWriter::NativeOffsetInImage(void* obj) { 1969 DCHECK(obj != nullptr); 1970 DCHECK(!IsInBootImage(obj)); 1971 auto it = native_object_relocations_.find(obj); 1972 CHECK(it != native_object_relocations_.end()) << obj << " spaces " 1973 << Runtime::Current()->GetHeap()->DumpSpaces(); 1974 const NativeObjectRelocation& relocation = it->second; 1975 return relocation.offset; 1976 } 1977 1978 template <typename T> 1979 std::string PrettyPrint(T* ptr) SHARED_REQUIRES(Locks::mutator_lock_) { 1980 std::ostringstream oss; 1981 oss << ptr; 1982 return oss.str(); 1983 } 1984 1985 template <> 1986 std::string PrettyPrint(ArtMethod* method) SHARED_REQUIRES(Locks::mutator_lock_) { 1987 return PrettyMethod(method); 1988 } 1989 1990 template <typename T> 1991 T* ImageWriter::NativeLocationInImage(T* obj) { 1992 if (obj == nullptr || IsInBootImage(obj)) { 1993 return obj; 1994 } else { 1995 auto it = native_object_relocations_.find(obj); 1996 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj) 1997 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces(); 1998 const NativeObjectRelocation& relocation = it->second; 1999 ImageInfo& image_info = GetImageInfo(relocation.oat_index); 2000 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset); 2001 } 2002 } 2003 2004 template <typename T> 2005 T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) { 2006 if (obj == nullptr || IsInBootImage(obj)) { 2007 return obj; 2008 } else { 2009 size_t oat_index = GetOatIndexForDexCache(dex_cache); 2010 ImageInfo& image_info = GetImageInfo(oat_index); 2011 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj)); 2012 } 2013 } 2014 2015 class NativeLocationVisitor { 2016 public: 2017 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {} 2018 2019 template <typename T> 2020 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) { 2021 return image_writer_->NativeLocationInImage(ptr); 2022 } 2023 2024 private: 2025 ImageWriter* const image_writer_; 2026 }; 2027 2028 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) { 2029 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this)); 2030 FixupClassVisitor visitor(this, copy); 2031 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor); 2032 2033 // Remove the clinitThreadId. This is required for image determinism. 2034 copy->SetClinitThreadId(static_cast<pid_t>(0)); 2035 } 2036 2037 void ImageWriter::FixupObject(Object* orig, Object* copy) { 2038 DCHECK(orig != nullptr); 2039 DCHECK(copy != nullptr); 2040 if (kUseBakerOrBrooksReadBarrier) { 2041 orig->AssertReadBarrierPointer(); 2042 if (kUseBrooksReadBarrier) { 2043 // Note the address 'copy' isn't the same as the image address of 'orig'. 2044 copy->SetReadBarrierPointer(GetImageAddress(orig)); 2045 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig)); 2046 } 2047 } 2048 auto* klass = orig->GetClass(); 2049 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) { 2050 // Is this a native pointer array? 2051 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig)); 2052 if (it != pointer_arrays_.end()) { 2053 // Should only need to fixup every pointer array exactly once. 2054 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second); 2055 pointer_arrays_.erase(it); 2056 return; 2057 } 2058 } 2059 if (orig->IsClass()) { 2060 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy)); 2061 } else { 2062 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) { 2063 // Need to go update the ArtMethod. 2064 auto* dest = down_cast<mirror::AbstractMethod*>(copy); 2065 auto* src = down_cast<mirror::AbstractMethod*>(orig); 2066 ArtMethod* src_method = src->GetArtMethod(); 2067 auto it = native_object_relocations_.find(src_method); 2068 CHECK(it != native_object_relocations_.end()) 2069 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method); 2070 dest->SetArtMethod( 2071 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset)); 2072 } else if (!klass->IsArrayClass()) { 2073 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2074 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) { 2075 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy)); 2076 } else if (klass->IsClassLoaderClass()) { 2077 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy); 2078 // If src is a ClassLoader, set the class table to null so that it gets recreated by the 2079 // ClassLoader. 2080 copy_loader->SetClassTable(nullptr); 2081 // Also set allocator to null to be safe. The allocator is created when we create the class 2082 // table. We also never expect to unload things in the image since they are held live as 2083 // roots. 2084 copy_loader->SetAllocator(nullptr); 2085 } 2086 } 2087 FixupVisitor visitor(this, copy); 2088 orig->VisitReferences(visitor, visitor); 2089 } 2090 } 2091 2092 2093 class ImageAddressVisitor { 2094 public: 2095 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {} 2096 2097 template <typename T> 2098 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) { 2099 return image_writer_->GetImageAddress(ptr); 2100 } 2101 2102 private: 2103 ImageWriter* const image_writer_; 2104 }; 2105 2106 2107 void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache, 2108 mirror::DexCache* copy_dex_cache) { 2109 // Though the DexCache array fields are usually treated as native pointers, we set the full 2110 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is 2111 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e. 2112 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))). 2113 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings(); 2114 if (orig_strings != nullptr) { 2115 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(), 2116 NativeLocationInImage(orig_strings), 2117 /*pointer size*/8u); 2118 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), 2119 ImageAddressVisitor(this)); 2120 } 2121 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes(); 2122 if (orig_types != nullptr) { 2123 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(), 2124 NativeLocationInImage(orig_types), 2125 /*pointer size*/8u); 2126 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache), 2127 ImageAddressVisitor(this)); 2128 } 2129 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods(); 2130 if (orig_methods != nullptr) { 2131 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(), 2132 NativeLocationInImage(orig_methods), 2133 /*pointer size*/8u); 2134 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache); 2135 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) { 2136 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_); 2137 // NativeLocationInImage also handles runtime methods since these have relocation info. 2138 ArtMethod* copy = NativeLocationInImage(orig); 2139 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_); 2140 } 2141 } 2142 ArtField** orig_fields = orig_dex_cache->GetResolvedFields(); 2143 if (orig_fields != nullptr) { 2144 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(), 2145 NativeLocationInImage(orig_fields), 2146 /*pointer size*/8u); 2147 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache); 2148 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) { 2149 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_); 2150 ArtField* copy = NativeLocationInImage(orig); 2151 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_); 2152 } 2153 } 2154 2155 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving 2156 // compiler pointers in here will make the output non-deterministic. 2157 copy_dex_cache->SetDexFile(nullptr); 2158 } 2159 2160 const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const { 2161 DCHECK_LT(type, kOatAddressCount); 2162 // If we are compiling an app image, we need to use the stubs of the boot image. 2163 if (compile_app_image_) { 2164 // Use the current image pointers. 2165 const std::vector<gc::space::ImageSpace*>& image_spaces = 2166 Runtime::Current()->GetHeap()->GetBootImageSpaces(); 2167 DCHECK(!image_spaces.empty()); 2168 const OatFile* oat_file = image_spaces[0]->GetOatFile(); 2169 CHECK(oat_file != nullptr); 2170 const OatHeader& header = oat_file->GetOatHeader(); 2171 switch (type) { 2172 // TODO: We could maybe clean this up if we stored them in an array in the oat header. 2173 case kOatAddressQuickGenericJNITrampoline: 2174 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline()); 2175 case kOatAddressInterpreterToInterpreterBridge: 2176 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge()); 2177 case kOatAddressInterpreterToCompiledCodeBridge: 2178 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge()); 2179 case kOatAddressJNIDlsymLookup: 2180 return static_cast<const uint8_t*>(header.GetJniDlsymLookup()); 2181 case kOatAddressQuickIMTConflictTrampoline: 2182 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline()); 2183 case kOatAddressQuickResolutionTrampoline: 2184 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline()); 2185 case kOatAddressQuickToInterpreterBridge: 2186 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge()); 2187 default: 2188 UNREACHABLE(); 2189 } 2190 } 2191 const ImageInfo& primary_image_info = GetImageInfo(0); 2192 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info); 2193 } 2194 2195 const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, 2196 const ImageInfo& image_info, 2197 bool* quick_is_interpreted) { 2198 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method); 2199 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method); 2200 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method); 2201 DCHECK(method->IsInvokable()) << PrettyMethod(method); 2202 DCHECK(!IsInBootImage(method)) << PrettyMethod(method); 2203 2204 // Use original code if it exists. Otherwise, set the code pointer to the resolution 2205 // trampoline. 2206 2207 // Quick entrypoint: 2208 const void* quick_oat_entry_point = 2209 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_); 2210 const uint8_t* quick_code; 2211 2212 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) { 2213 DCHECK(method->IsCopied()); 2214 // If the code is not in the oat file corresponding to this image (e.g. default methods) 2215 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point); 2216 } else { 2217 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point); 2218 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info); 2219 } 2220 2221 *quick_is_interpreted = false; 2222 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() || 2223 method->GetDeclaringClass()->IsInitialized())) { 2224 // We have code for a non-static or initialized method, just use the code. 2225 } else if (quick_code == nullptr && method->IsNative() && 2226 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) { 2227 // Non-static or initialized native method missing compiled code, use generic JNI version. 2228 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline); 2229 } else if (quick_code == nullptr && !method->IsNative()) { 2230 // We don't have code at all for a non-native method, use the interpreter. 2231 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge); 2232 *quick_is_interpreted = true; 2233 } else { 2234 CHECK(!method->GetDeclaringClass()->IsInitialized()); 2235 // We have code for a static method, but need to go through the resolution stub for class 2236 // initialization. 2237 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline); 2238 } 2239 if (!IsInBootOatFile(quick_code)) { 2240 // DCHECK_GE(quick_code, oat_data_begin_); 2241 } 2242 return quick_code; 2243 } 2244 2245 void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, 2246 ArtMethod* copy, 2247 const ImageInfo& image_info) { 2248 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_)); 2249 2250 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked())); 2251 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_); 2252 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_); 2253 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_); 2254 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_); 2255 2256 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to 2257 // oat_begin_ 2258 2259 // The resolution method has a special trampoline to call. 2260 Runtime* runtime = Runtime::Current(); 2261 if (orig->IsRuntimeMethod()) { 2262 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_); 2263 if (orig_table != nullptr) { 2264 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method. 2265 copy->SetEntryPointFromQuickCompiledCodePtrSize( 2266 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_); 2267 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_); 2268 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) { 2269 copy->SetEntryPointFromQuickCompiledCodePtrSize( 2270 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_); 2271 } else { 2272 bool found_one = false; 2273 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) { 2274 auto idx = static_cast<Runtime::CalleeSaveType>(i); 2275 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) { 2276 found_one = true; 2277 break; 2278 } 2279 } 2280 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig); 2281 CHECK(copy->IsRuntimeMethod()); 2282 } 2283 } else { 2284 // We assume all methods have code. If they don't currently then we set them to the use the 2285 // resolution trampoline. Abstract methods never have code and so we need to make sure their 2286 // use results in an AbstractMethodError. We use the interpreter to achieve this. 2287 if (UNLIKELY(!orig->IsInvokable())) { 2288 copy->SetEntryPointFromQuickCompiledCodePtrSize( 2289 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_); 2290 } else { 2291 bool quick_is_interpreted; 2292 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted); 2293 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_); 2294 2295 // JNI entrypoint: 2296 if (orig->IsNative()) { 2297 // The native method's pointer is set to a stub to lookup via dlsym. 2298 // Note this is not the code_ pointer, that is handled above. 2299 copy->SetEntryPointFromJniPtrSize( 2300 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_); 2301 } 2302 } 2303 } 2304 } 2305 2306 size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const { 2307 DCHECK_LE(up_to, kBinSize); 2308 return std::accumulate(&image_info.bin_slot_sizes_[0], 2309 &image_info.bin_slot_sizes_[up_to], 2310 /*init*/0); 2311 } 2312 2313 ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) { 2314 // These values may need to get updated if more bins are added to the enum Bin 2315 static_assert(kBinBits == 3, "wrong number of bin bits"); 2316 static_assert(kBinShift == 27, "wrong number of shift"); 2317 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes"); 2318 2319 DCHECK_LT(GetBin(), kBinSize); 2320 DCHECK_ALIGNED(GetIndex(), kObjectAlignment); 2321 } 2322 2323 ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index) 2324 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) { 2325 DCHECK_EQ(index, GetIndex()); 2326 } 2327 2328 ImageWriter::Bin ImageWriter::BinSlot::GetBin() const { 2329 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift); 2330 } 2331 2332 uint32_t ImageWriter::BinSlot::GetIndex() const { 2333 return lockword_ & ~kBinMask; 2334 } 2335 2336 ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) { 2337 switch (type) { 2338 case kNativeObjectRelocationTypeArtField: 2339 case kNativeObjectRelocationTypeArtFieldArray: 2340 return kBinArtField; 2341 case kNativeObjectRelocationTypeArtMethodClean: 2342 case kNativeObjectRelocationTypeArtMethodArrayClean: 2343 return kBinArtMethodClean; 2344 case kNativeObjectRelocationTypeArtMethodDirty: 2345 case kNativeObjectRelocationTypeArtMethodArrayDirty: 2346 return kBinArtMethodDirty; 2347 case kNativeObjectRelocationTypeDexCacheArray: 2348 return kBinDexCacheArray; 2349 case kNativeObjectRelocationTypeRuntimeMethod: 2350 return kBinRuntimeMethod; 2351 case kNativeObjectRelocationTypeIMTable: 2352 return kBinImTable; 2353 case kNativeObjectRelocationTypeIMTConflictTable: 2354 return kBinIMTConflictTable; 2355 } 2356 UNREACHABLE(); 2357 } 2358 2359 size_t ImageWriter::GetOatIndex(mirror::Object* obj) const { 2360 if (!IsMultiImage()) { 2361 return GetDefaultOatIndex(); 2362 } 2363 auto it = oat_index_map_.find(obj); 2364 DCHECK(it != oat_index_map_.end()); 2365 return it->second; 2366 } 2367 2368 size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const { 2369 if (!IsMultiImage()) { 2370 return GetDefaultOatIndex(); 2371 } 2372 auto it = dex_file_oat_index_map_.find(dex_file); 2373 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation(); 2374 return it->second; 2375 } 2376 2377 size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const { 2378 if (dex_cache == nullptr) { 2379 return GetDefaultOatIndex(); 2380 } else { 2381 return GetOatIndexForDexFile(dex_cache->GetDexFile()); 2382 } 2383 } 2384 2385 void ImageWriter::UpdateOatFileLayout(size_t oat_index, 2386 size_t oat_loaded_size, 2387 size_t oat_data_offset, 2388 size_t oat_data_size) { 2389 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_; 2390 for (const ImageInfo& info : image_infos_) { 2391 DCHECK_LE(info.image_begin_ + info.image_size_, images_end); 2392 } 2393 DCHECK(images_end != nullptr); // Image space must be ready. 2394 2395 ImageInfo& cur_image_info = GetImageInfo(oat_index); 2396 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_; 2397 cur_image_info.oat_loaded_size_ = oat_loaded_size; 2398 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset; 2399 cur_image_info.oat_size_ = oat_data_size; 2400 2401 if (compile_app_image_) { 2402 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image."; 2403 return; 2404 } 2405 2406 // Update the oat_offset of the next image info. 2407 if (oat_index + 1u != oat_filenames_.size()) { 2408 // There is a following one. 2409 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u); 2410 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size; 2411 } 2412 } 2413 2414 void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) { 2415 ImageInfo& cur_image_info = GetImageInfo(oat_index); 2416 cur_image_info.oat_checksum_ = oat_header.GetChecksum(); 2417 2418 if (oat_index == GetDefaultOatIndex()) { 2419 // Primary oat file, read the trampolines. 2420 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] = 2421 oat_header.GetInterpreterToInterpreterBridgeOffset(); 2422 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] = 2423 oat_header.GetInterpreterToCompiledCodeBridgeOffset(); 2424 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] = 2425 oat_header.GetJniDlsymLookupOffset(); 2426 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] = 2427 oat_header.GetQuickGenericJniTrampolineOffset(); 2428 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] = 2429 oat_header.GetQuickImtConflictTrampolineOffset(); 2430 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] = 2431 oat_header.GetQuickResolutionTrampolineOffset(); 2432 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] = 2433 oat_header.GetQuickToInterpreterBridgeOffset(); 2434 } 2435 } 2436 2437 ImageWriter::ImageWriter( 2438 const CompilerDriver& compiler_driver, 2439 uintptr_t image_begin, 2440 bool compile_pic, 2441 bool compile_app_image, 2442 ImageHeader::StorageMode image_storage_mode, 2443 const std::vector<const char*>& oat_filenames, 2444 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map) 2445 : compiler_driver_(compiler_driver), 2446 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)), 2447 image_objects_offset_begin_(0), 2448 compile_pic_(compile_pic), 2449 compile_app_image_(compile_app_image), 2450 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())), 2451 image_infos_(oat_filenames.size()), 2452 dirty_methods_(0u), 2453 clean_methods_(0u), 2454 image_storage_mode_(image_storage_mode), 2455 oat_filenames_(oat_filenames), 2456 dex_file_oat_index_map_(dex_file_oat_index_map) { 2457 CHECK_NE(image_begin, 0U); 2458 std::fill_n(image_methods_, arraysize(image_methods_), nullptr); 2459 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty()) 2460 << "Compiling a boot image should occur iff there are no boot image spaces loaded"; 2461 } 2462 2463 ImageWriter::ImageInfo::ImageInfo() 2464 : intern_table_(new InternTable), 2465 class_table_(new ClassTable) {} 2466 2467 } // namespace art 2468