Home | History | Annotate | Download | only in compiler
      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.h"
     18 
     19 #include <memory>
     20 #include <string>
     21 #include <vector>
     22 
     23 #include "android-base/stringprintf.h"
     24 
     25 #include "art_method-inl.h"
     26 #include "base/unix_file/fd_file.h"
     27 #include "class_linker-inl.h"
     28 #include "compiler_callbacks.h"
     29 #include "common_compiler_test.h"
     30 #include "debug/method_debug_info.h"
     31 #include "dex/quick_compiler_callbacks.h"
     32 #include "driver/compiler_options.h"
     33 #include "elf_writer.h"
     34 #include "elf_writer_quick.h"
     35 #include "gc/space/image_space.h"
     36 #include "image_writer.h"
     37 #include "linker/buffered_output_stream.h"
     38 #include "linker/file_output_stream.h"
     39 #include "linker/multi_oat_relative_patcher.h"
     40 #include "lock_word.h"
     41 #include "mirror/object-inl.h"
     42 #include "oat_writer.h"
     43 #include "scoped_thread_state_change-inl.h"
     44 #include "signal_catcher.h"
     45 #include "utils.h"
     46 
     47 namespace art {
     48 
     49 static const uintptr_t kRequestedImageBase = ART_BASE_ADDRESS;
     50 
     51 struct CompilationHelper {
     52   std::vector<std::string> dex_file_locations;
     53   std::vector<ScratchFile> image_locations;
     54   std::vector<std::unique_ptr<const DexFile>> extra_dex_files;
     55   std::vector<ScratchFile> image_files;
     56   std::vector<ScratchFile> oat_files;
     57   std::vector<ScratchFile> vdex_files;
     58   std::string image_dir;
     59 
     60   void Compile(CompilerDriver* driver,
     61                ImageHeader::StorageMode storage_mode);
     62 
     63   std::vector<size_t> GetImageObjectSectionSizes();
     64 
     65   ~CompilationHelper();
     66 };
     67 
     68 class ImageTest : public CommonCompilerTest {
     69  protected:
     70   virtual void SetUp() {
     71     ReserveImageSpace();
     72     CommonCompilerTest::SetUp();
     73   }
     74 
     75   void TestWriteRead(ImageHeader::StorageMode storage_mode);
     76 
     77   void Compile(ImageHeader::StorageMode storage_mode,
     78                CompilationHelper& out_helper,
     79                const std::string& extra_dex = "",
     80                const std::initializer_list<std::string>& image_classes = {});
     81 
     82   void SetUpRuntimeOptions(RuntimeOptions* options) OVERRIDE {
     83     CommonCompilerTest::SetUpRuntimeOptions(options);
     84     callbacks_.reset(new QuickCompilerCallbacks(
     85         verification_results_.get(),
     86         CompilerCallbacks::CallbackMode::kCompileBootImage));
     87     options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
     88   }
     89 
     90   std::unordered_set<std::string>* GetImageClasses() OVERRIDE {
     91     return new std::unordered_set<std::string>(image_classes_);
     92   }
     93 
     94   ArtMethod* FindCopiedMethod(ArtMethod* origin, mirror::Class* klass)
     95       REQUIRES_SHARED(Locks::mutator_lock_) {
     96     PointerSize pointer_size = class_linker_->GetImagePointerSize();
     97     for (ArtMethod& m : klass->GetCopiedMethods(pointer_size)) {
     98       if (strcmp(origin->GetName(), m.GetName()) == 0 &&
     99           origin->GetSignature() == m.GetSignature()) {
    100         return &m;
    101       }
    102     }
    103     return nullptr;
    104   }
    105 
    106  private:
    107   std::unordered_set<std::string> image_classes_;
    108 };
    109 
    110 CompilationHelper::~CompilationHelper() {
    111   for (ScratchFile& image_file : image_files) {
    112     image_file.Unlink();
    113   }
    114   for (ScratchFile& oat_file : oat_files) {
    115     oat_file.Unlink();
    116   }
    117   for (ScratchFile& vdex_file : vdex_files) {
    118     vdex_file.Unlink();
    119   }
    120   const int rmdir_result = rmdir(image_dir.c_str());
    121   CHECK_EQ(0, rmdir_result);
    122 }
    123 
    124 std::vector<size_t> CompilationHelper::GetImageObjectSectionSizes() {
    125   std::vector<size_t> ret;
    126   for (ScratchFile& image_file : image_files) {
    127     std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
    128     CHECK(file.get() != nullptr);
    129     ImageHeader image_header;
    130     CHECK_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
    131     CHECK(image_header.IsValid());
    132     ret.push_back(image_header.GetImageSize());
    133   }
    134   return ret;
    135 }
    136 
    137 void CompilationHelper::Compile(CompilerDriver* driver,
    138                                 ImageHeader::StorageMode storage_mode) {
    139   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
    140   std::vector<const DexFile*> class_path = class_linker->GetBootClassPath();
    141 
    142   for (const std::unique_ptr<const DexFile>& dex_file : extra_dex_files) {
    143     {
    144       ScopedObjectAccess soa(Thread::Current());
    145       // Inject in boot class path so that the compiler driver can see it.
    146       class_linker->AppendToBootClassPath(soa.Self(), *dex_file.get());
    147     }
    148     class_path.push_back(dex_file.get());
    149   }
    150 
    151   // Enable write for dex2dex.
    152   for (const DexFile* dex_file : class_path) {
    153     dex_file_locations.push_back(dex_file->GetLocation());
    154     if (dex_file->IsReadOnly()) {
    155       dex_file->EnableWrite();
    156     }
    157   }
    158   {
    159     // Create a generic tmp file, to be the base of the .art and .oat temporary files.
    160     ScratchFile location;
    161     for (int i = 0; i < static_cast<int>(class_path.size()); ++i) {
    162       std::string cur_location =
    163           android::base::StringPrintf("%s-%d.art", location.GetFilename().c_str(), i);
    164       image_locations.push_back(ScratchFile(cur_location));
    165     }
    166   }
    167   std::vector<std::string> image_filenames;
    168   for (ScratchFile& file : image_locations) {
    169     std::string image_filename(GetSystemImageFilename(file.GetFilename().c_str(), kRuntimeISA));
    170     image_filenames.push_back(image_filename);
    171     size_t pos = image_filename.rfind('/');
    172     CHECK_NE(pos, std::string::npos) << image_filename;
    173     if (image_dir.empty()) {
    174       image_dir = image_filename.substr(0, pos);
    175       int mkdir_result = mkdir(image_dir.c_str(), 0700);
    176       CHECK_EQ(0, mkdir_result) << image_dir;
    177     }
    178     image_files.push_back(ScratchFile(OS::CreateEmptyFile(image_filename.c_str())));
    179   }
    180 
    181   std::vector<std::string> oat_filenames;
    182   std::vector<std::string> vdex_filenames;
    183   for (const std::string& image_filename : image_filenames) {
    184     std::string oat_filename = ReplaceFileExtension(image_filename, "oat");
    185     oat_files.push_back(ScratchFile(OS::CreateEmptyFile(oat_filename.c_str())));
    186     oat_filenames.push_back(oat_filename);
    187     std::string vdex_filename = ReplaceFileExtension(image_filename, "vdex");
    188     vdex_files.push_back(ScratchFile(OS::CreateEmptyFile(vdex_filename.c_str())));
    189     vdex_filenames.push_back(vdex_filename);
    190   }
    191 
    192   std::unordered_map<const DexFile*, size_t> dex_file_to_oat_index_map;
    193   std::vector<const char*> oat_filename_vector;
    194   for (const std::string& file : oat_filenames) {
    195     oat_filename_vector.push_back(file.c_str());
    196   }
    197   std::vector<const char*> image_filename_vector;
    198   for (const std::string& file : image_filenames) {
    199     image_filename_vector.push_back(file.c_str());
    200   }
    201   size_t image_idx = 0;
    202   for (const DexFile* dex_file : class_path) {
    203     dex_file_to_oat_index_map.emplace(dex_file, image_idx);
    204     ++image_idx;
    205   }
    206   // TODO: compile_pic should be a test argument.
    207   std::unique_ptr<ImageWriter> writer(new ImageWriter(*driver,
    208                                                       kRequestedImageBase,
    209                                                       /*compile_pic*/false,
    210                                                       /*compile_app_image*/false,
    211                                                       storage_mode,
    212                                                       oat_filename_vector,
    213                                                       dex_file_to_oat_index_map));
    214   {
    215     {
    216       jobject class_loader = nullptr;
    217       TimingLogger timings("ImageTest::WriteRead", false, false);
    218       TimingLogger::ScopedTiming t("CompileAll", &timings);
    219       driver->SetDexFilesForOatFile(class_path);
    220       driver->CompileAll(class_loader, class_path, /* verifier_deps */ nullptr, &timings);
    221 
    222       t.NewTiming("WriteElf");
    223       SafeMap<std::string, std::string> key_value_store;
    224       std::vector<const char*> dex_filename_vector;
    225       for (size_t i = 0; i < class_path.size(); ++i) {
    226         dex_filename_vector.push_back("");
    227       }
    228       key_value_store.Put(OatHeader::kBootClassPathKey,
    229                           gc::space::ImageSpace::GetMultiImageBootClassPath(
    230                               dex_filename_vector,
    231                               oat_filename_vector,
    232                               image_filename_vector));
    233 
    234       std::vector<std::unique_ptr<ElfWriter>> elf_writers;
    235       std::vector<std::unique_ptr<OatWriter>> oat_writers;
    236       for (ScratchFile& oat_file : oat_files) {
    237         elf_writers.emplace_back(CreateElfWriterQuick(driver->GetInstructionSet(),
    238                                                       driver->GetInstructionSetFeatures(),
    239                                                       &driver->GetCompilerOptions(),
    240                                                       oat_file.GetFile()));
    241         elf_writers.back()->Start();
    242         oat_writers.emplace_back(new OatWriter(/*compiling_boot_image*/true,
    243                                                &timings,
    244                                                /*profile_compilation_info*/nullptr));
    245       }
    246 
    247       std::vector<OutputStream*> rodata;
    248       std::vector<std::unique_ptr<MemMap>> opened_dex_files_map;
    249       std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
    250       // Now that we have finalized key_value_store_, start writing the oat file.
    251       for (size_t i = 0, size = oat_writers.size(); i != size; ++i) {
    252         const DexFile* dex_file = class_path[i];
    253         rodata.push_back(elf_writers[i]->StartRoData());
    254         ArrayRef<const uint8_t> raw_dex_file(
    255             reinterpret_cast<const uint8_t*>(&dex_file->GetHeader()),
    256             dex_file->GetHeader().file_size_);
    257         oat_writers[i]->AddRawDexFileSource(raw_dex_file,
    258                                             dex_file->GetLocation().c_str(),
    259                                             dex_file->GetLocationChecksum());
    260 
    261         std::unique_ptr<MemMap> cur_opened_dex_files_map;
    262         std::vector<std::unique_ptr<const DexFile>> cur_opened_dex_files;
    263         bool dex_files_ok = oat_writers[i]->WriteAndOpenDexFiles(
    264             kIsVdexEnabled ? vdex_files[i].GetFile() : oat_files[i].GetFile(),
    265             rodata.back(),
    266             driver->GetInstructionSet(),
    267             driver->GetInstructionSetFeatures(),
    268             &key_value_store,
    269             /* verify */ false,           // Dex files may be dex-to-dex-ed, don't verify.
    270             /* update_input_vdex */ false,
    271             &cur_opened_dex_files_map,
    272             &cur_opened_dex_files);
    273         ASSERT_TRUE(dex_files_ok);
    274 
    275         if (cur_opened_dex_files_map != nullptr) {
    276           opened_dex_files_map.push_back(std::move(cur_opened_dex_files_map));
    277           for (std::unique_ptr<const DexFile>& cur_dex_file : cur_opened_dex_files) {
    278             // dex_file_oat_index_map_.emplace(dex_file.get(), i);
    279             opened_dex_files.push_back(std::move(cur_dex_file));
    280           }
    281         } else {
    282           ASSERT_TRUE(cur_opened_dex_files.empty());
    283         }
    284       }
    285       bool image_space_ok = writer->PrepareImageAddressSpace();
    286       ASSERT_TRUE(image_space_ok);
    287 
    288       if (kIsVdexEnabled) {
    289         for (size_t i = 0, size = vdex_files.size(); i != size; ++i) {
    290           std::unique_ptr<BufferedOutputStream> vdex_out(
    291               MakeUnique<BufferedOutputStream>(
    292                   MakeUnique<FileOutputStream>(vdex_files[i].GetFile())));
    293           oat_writers[i]->WriteVerifierDeps(vdex_out.get(), nullptr);
    294           oat_writers[i]->WriteChecksumsAndVdexHeader(vdex_out.get());
    295         }
    296       }
    297 
    298       for (size_t i = 0, size = oat_files.size(); i != size; ++i) {
    299         linker::MultiOatRelativePatcher patcher(driver->GetInstructionSet(),
    300                                                 driver->GetInstructionSetFeatures());
    301         OatWriter* const oat_writer = oat_writers[i].get();
    302         ElfWriter* const elf_writer = elf_writers[i].get();
    303         std::vector<const DexFile*> cur_dex_files(1u, class_path[i]);
    304         oat_writer->Initialize(driver, writer.get(), cur_dex_files);
    305         oat_writer->PrepareLayout(&patcher);
    306         size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
    307         size_t text_size = oat_writer->GetOatSize() - rodata_size;
    308         elf_writer->PrepareDynamicSection(rodata_size,
    309                                           text_size,
    310                                           oat_writer->GetBssSize(),
    311                                           oat_writer->GetBssRootsOffset());
    312 
    313         writer->UpdateOatFileLayout(i,
    314                                     elf_writer->GetLoadedSize(),
    315                                     oat_writer->GetOatDataOffset(),
    316                                     oat_writer->GetOatSize());
    317 
    318         bool rodata_ok = oat_writer->WriteRodata(rodata[i]);
    319         ASSERT_TRUE(rodata_ok);
    320         elf_writer->EndRoData(rodata[i]);
    321 
    322         OutputStream* text = elf_writer->StartText();
    323         bool text_ok = oat_writer->WriteCode(text);
    324         ASSERT_TRUE(text_ok);
    325         elf_writer->EndText(text);
    326 
    327         bool header_ok = oat_writer->WriteHeader(elf_writer->GetStream(), 0u, 0u, 0u);
    328         ASSERT_TRUE(header_ok);
    329 
    330         writer->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
    331 
    332         elf_writer->WriteDynamicSection();
    333         elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
    334 
    335         bool success = elf_writer->End();
    336         ASSERT_TRUE(success);
    337       }
    338     }
    339 
    340     bool success_image = writer->Write(kInvalidFd,
    341                                        image_filename_vector,
    342                                        oat_filename_vector);
    343     ASSERT_TRUE(success_image);
    344 
    345     for (size_t i = 0, size = oat_filenames.size(); i != size; ++i) {
    346       const char* oat_filename = oat_filenames[i].c_str();
    347       std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
    348       ASSERT_TRUE(oat_file != nullptr);
    349       bool success_fixup = ElfWriter::Fixup(oat_file.get(),
    350                                             writer->GetOatDataBegin(i));
    351       ASSERT_TRUE(success_fixup);
    352       ASSERT_EQ(oat_file->FlushCloseOrErase(), 0) << "Could not flush and close oat file "
    353                                                   << oat_filename;
    354     }
    355   }
    356 }
    357 
    358 void ImageTest::Compile(ImageHeader::StorageMode storage_mode,
    359                         CompilationHelper& helper,
    360                         const std::string& extra_dex,
    361                         const std::initializer_list<std::string>& image_classes) {
    362   for (const std::string& image_class : image_classes) {
    363     image_classes_.insert(image_class);
    364   }
    365   CreateCompilerDriver(Compiler::kOptimizing, kRuntimeISA, kIsTargetBuild ? 2U : 16U);
    366   // Set inline filter values.
    367   compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
    368   image_classes_.clear();
    369   if (!extra_dex.empty()) {
    370     helper.extra_dex_files = OpenTestDexFiles(extra_dex.c_str());
    371   }
    372   helper.Compile(compiler_driver_.get(), storage_mode);
    373   if (image_classes.begin() != image_classes.end()) {
    374     // Make sure the class got initialized.
    375     ScopedObjectAccess soa(Thread::Current());
    376     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
    377     for (const std::string& image_class : image_classes) {
    378       mirror::Class* klass = class_linker->FindSystemClass(Thread::Current(), image_class.c_str());
    379       EXPECT_TRUE(klass != nullptr);
    380       EXPECT_TRUE(klass->IsInitialized());
    381     }
    382   }
    383 }
    384 
    385 void ImageTest::TestWriteRead(ImageHeader::StorageMode storage_mode) {
    386   CompilationHelper helper;
    387   Compile(storage_mode, /*out*/ helper);
    388   std::vector<uint64_t> image_file_sizes;
    389   for (ScratchFile& image_file : helper.image_files) {
    390     std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
    391     ASSERT_TRUE(file.get() != nullptr);
    392     ImageHeader image_header;
    393     ASSERT_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
    394     ASSERT_TRUE(image_header.IsValid());
    395     const auto& bitmap_section = image_header.GetImageSection(ImageHeader::kSectionImageBitmap);
    396     ASSERT_GE(bitmap_section.Offset(), sizeof(image_header));
    397     ASSERT_NE(0U, bitmap_section.Size());
    398 
    399     gc::Heap* heap = Runtime::Current()->GetHeap();
    400     ASSERT_TRUE(heap->HaveContinuousSpaces());
    401     gc::space::ContinuousSpace* space = heap->GetNonMovingSpace();
    402     ASSERT_FALSE(space->IsImageSpace());
    403     ASSERT_TRUE(space != nullptr);
    404     ASSERT_TRUE(space->IsMallocSpace());
    405     image_file_sizes.push_back(file->GetLength());
    406   }
    407 
    408   ASSERT_TRUE(compiler_driver_->GetImageClasses() != nullptr);
    409   std::unordered_set<std::string> image_classes(*compiler_driver_->GetImageClasses());
    410 
    411   // Need to delete the compiler since it has worker threads which are attached to runtime.
    412   compiler_driver_.reset();
    413 
    414   // Tear down old runtime before making a new one, clearing out misc state.
    415 
    416   // Remove the reservation of the memory for use to load the image.
    417   // Need to do this before we reset the runtime.
    418   UnreserveImageSpace();
    419 
    420   helper.extra_dex_files.clear();
    421   runtime_.reset();
    422   java_lang_dex_file_ = nullptr;
    423 
    424   MemMap::Init();
    425 
    426   RuntimeOptions options;
    427   std::string image("-Ximage:");
    428   image.append(helper.image_locations[0].GetFilename());
    429   options.push_back(std::make_pair(image.c_str(), static_cast<void*>(nullptr)));
    430   // By default the compiler this creates will not include patch information.
    431   options.push_back(std::make_pair("-Xnorelocate", nullptr));
    432 
    433   if (!Runtime::Create(options, false)) {
    434     LOG(FATAL) << "Failed to create runtime";
    435     return;
    436   }
    437   runtime_.reset(Runtime::Current());
    438   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
    439   // give it away now and then switch to a more managable ScopedObjectAccess.
    440   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
    441   ScopedObjectAccess soa(Thread::Current());
    442   ASSERT_TRUE(runtime_.get() != nullptr);
    443   class_linker_ = runtime_->GetClassLinker();
    444 
    445   gc::Heap* heap = Runtime::Current()->GetHeap();
    446   ASSERT_TRUE(heap->HasBootImageSpace());
    447   ASSERT_TRUE(heap->GetNonMovingSpace()->IsMallocSpace());
    448 
    449   // We loaded the runtime with an explicit image, so it must exist.
    450   ASSERT_EQ(heap->GetBootImageSpaces().size(), image_file_sizes.size());
    451   for (size_t i = 0; i < helper.dex_file_locations.size(); ++i) {
    452     std::unique_ptr<const DexFile> dex(
    453         LoadExpectSingleDexFile(helper.dex_file_locations[i].c_str()));
    454     ASSERT_TRUE(dex != nullptr);
    455     uint64_t image_file_size = image_file_sizes[i];
    456     gc::space::ImageSpace* image_space = heap->GetBootImageSpaces()[i];
    457     ASSERT_TRUE(image_space != nullptr);
    458     if (storage_mode == ImageHeader::kStorageModeUncompressed) {
    459       // Uncompressed, image should be smaller than file.
    460       ASSERT_LE(image_space->GetImageHeader().GetImageSize(), image_file_size);
    461     } else if (image_file_size > 16 * KB) {
    462       // Compressed, file should be smaller than image. Not really valid for small images.
    463       ASSERT_LE(image_file_size, image_space->GetImageHeader().GetImageSize());
    464     }
    465 
    466     image_space->VerifyImageAllocations();
    467     uint8_t* image_begin = image_space->Begin();
    468     uint8_t* image_end = image_space->End();
    469     if (i == 0) {
    470       // This check is only valid for image 0.
    471       CHECK_EQ(kRequestedImageBase, reinterpret_cast<uintptr_t>(image_begin));
    472     }
    473     for (size_t j = 0; j < dex->NumClassDefs(); ++j) {
    474       const DexFile::ClassDef& class_def = dex->GetClassDef(j);
    475       const char* descriptor = dex->GetClassDescriptor(class_def);
    476       mirror::Class* klass = class_linker_->FindSystemClass(soa.Self(), descriptor);
    477       EXPECT_TRUE(klass != nullptr) << descriptor;
    478       if (image_classes.find(descriptor) == image_classes.end()) {
    479         EXPECT_TRUE(reinterpret_cast<uint8_t*>(klass) >= image_end ||
    480                     reinterpret_cast<uint8_t*>(klass) < image_begin) << descriptor;
    481       } else {
    482         // Image classes should be located inside the image.
    483         EXPECT_LT(image_begin, reinterpret_cast<uint8_t*>(klass)) << descriptor;
    484         EXPECT_LT(reinterpret_cast<uint8_t*>(klass), image_end) << descriptor;
    485       }
    486       EXPECT_TRUE(Monitor::IsValidLockWord(klass->GetLockWord(false)));
    487     }
    488   }
    489 }
    490 
    491 TEST_F(ImageTest, WriteReadUncompressed) {
    492   TestWriteRead(ImageHeader::kStorageModeUncompressed);
    493 }
    494 
    495 TEST_F(ImageTest, WriteReadLZ4) {
    496   TestWriteRead(ImageHeader::kStorageModeLZ4);
    497 }
    498 
    499 TEST_F(ImageTest, WriteReadLZ4HC) {
    500   TestWriteRead(ImageHeader::kStorageModeLZ4HC);
    501 }
    502 
    503 TEST_F(ImageTest, TestImageLayout) {
    504   std::vector<size_t> image_sizes;
    505   std::vector<size_t> image_sizes_extra;
    506   // Compile multi-image with ImageLayoutA being the last image.
    507   {
    508     CompilationHelper helper;
    509     Compile(ImageHeader::kStorageModeUncompressed, helper, "ImageLayoutA", {"LMyClass;"});
    510     image_sizes = helper.GetImageObjectSectionSizes();
    511   }
    512   TearDown();
    513   runtime_.reset();
    514   SetUp();
    515   // Compile multi-image with ImageLayoutB being the last image.
    516   {
    517     CompilationHelper helper;
    518     Compile(ImageHeader::kStorageModeUncompressed, helper, "ImageLayoutB", {"LMyClass;"});
    519     image_sizes_extra = helper.GetImageObjectSectionSizes();
    520   }
    521   // Make sure that the new stuff in the clinit in ImageLayoutB is in the last image and not in the
    522   // first two images.
    523   ASSERT_EQ(image_sizes.size(), image_sizes.size());
    524   // Sizes of the images should be the same. These sizes are for the whole image unrounded.
    525   for (size_t i = 0; i < image_sizes.size() - 1; ++i) {
    526     EXPECT_EQ(image_sizes[i], image_sizes_extra[i]);
    527   }
    528   // Last image should be larger since it has a hash map and a string.
    529   EXPECT_LT(image_sizes.back(), image_sizes_extra.back());
    530 }
    531 
    532 TEST_F(ImageTest, ImageHeaderIsValid) {
    533     uint32_t image_begin = ART_BASE_ADDRESS;
    534     uint32_t image_size_ = 16 * KB;
    535     uint32_t image_roots = ART_BASE_ADDRESS + (1 * KB);
    536     uint32_t oat_checksum = 0;
    537     uint32_t oat_file_begin = ART_BASE_ADDRESS + (4 * KB);  // page aligned
    538     uint32_t oat_data_begin = ART_BASE_ADDRESS + (8 * KB);  // page aligned
    539     uint32_t oat_data_end = ART_BASE_ADDRESS + (9 * KB);
    540     uint32_t oat_file_end = ART_BASE_ADDRESS + (10 * KB);
    541     ImageSection sections[ImageHeader::kSectionCount];
    542     ImageHeader image_header(image_begin,
    543                              image_size_,
    544                              sections,
    545                              image_roots,
    546                              oat_checksum,
    547                              oat_file_begin,
    548                              oat_data_begin,
    549                              oat_data_end,
    550                              oat_file_end,
    551                              /*boot_image_begin*/0U,
    552                              /*boot_image_size*/0U,
    553                              /*boot_oat_begin*/0U,
    554                              /*boot_oat_size_*/0U,
    555                              sizeof(void*),
    556                              /*compile_pic*/false,
    557                              /*is_pic*/false,
    558                              ImageHeader::kDefaultStorageMode,
    559                              /*data_size*/0u);
    560     ASSERT_TRUE(image_header.IsValid());
    561     ASSERT_TRUE(!image_header.IsAppImage());
    562 
    563     char* magic = const_cast<char*>(image_header.GetMagic());
    564     strcpy(magic, "");  // bad magic
    565     ASSERT_FALSE(image_header.IsValid());
    566     strcpy(magic, "art\n000");  // bad version
    567     ASSERT_FALSE(image_header.IsValid());
    568 }
    569 
    570 // Test that pointer to quick code is the same in
    571 // a default method of an interface and in a copied method
    572 // of a class which implements the interface. This should be true
    573 // only if the copied method and the origin method are located in the
    574 // same oat file.
    575 TEST_F(ImageTest, TestDefaultMethods) {
    576   CompilationHelper helper;
    577   Compile(ImageHeader::kStorageModeUncompressed,
    578       helper,
    579       "DefaultMethods",
    580       {"LIface;", "LImpl;", "LIterableBase;"});
    581 
    582   PointerSize pointer_size = class_linker_->GetImagePointerSize();
    583   Thread* self = Thread::Current();
    584   ScopedObjectAccess soa(self);
    585 
    586   // Test the pointer to quick code is the same in origin method
    587   // and in the copied method form the same oat file.
    588   mirror::Class* iface_klass = class_linker_->LookupClass(
    589       self, "LIface;", ObjPtr<mirror::ClassLoader>());
    590   ASSERT_NE(nullptr, iface_klass);
    591   ArtMethod* origin = iface_klass->FindDeclaredVirtualMethod(
    592       "defaultMethod", "()V", pointer_size);
    593   ASSERT_NE(nullptr, origin);
    594   const void* code = origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
    595   // The origin method should have a pointer to quick code
    596   ASSERT_NE(nullptr, code);
    597   ASSERT_FALSE(class_linker_->IsQuickToInterpreterBridge(code));
    598   mirror::Class* impl_klass = class_linker_->LookupClass(
    599       self, "LImpl;", ObjPtr<mirror::ClassLoader>());
    600   ASSERT_NE(nullptr, impl_klass);
    601   ArtMethod* copied = FindCopiedMethod(origin, impl_klass);
    602   ASSERT_NE(nullptr, copied);
    603   // the copied method should have pointer to the same quick code as the origin method
    604   ASSERT_EQ(code, copied->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size));
    605 
    606   // Test the origin method has pointer to quick code
    607   // but the copied method has pointer to interpreter
    608   // because these methods are in different oat files.
    609   mirror::Class* iterable_klass = class_linker_->LookupClass(
    610       self, "Ljava/lang/Iterable;", ObjPtr<mirror::ClassLoader>());
    611   ASSERT_NE(nullptr, iterable_klass);
    612   origin = iterable_klass->FindDeclaredVirtualMethod(
    613       "forEach", "(Ljava/util/function/Consumer;)V", pointer_size);
    614   ASSERT_NE(nullptr, origin);
    615   code = origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
    616   // the origin method should have a pointer to quick code
    617   ASSERT_NE(nullptr, code);
    618   ASSERT_FALSE(class_linker_->IsQuickToInterpreterBridge(code));
    619   mirror::Class* iterablebase_klass = class_linker_->LookupClass(
    620       self, "LIterableBase;", ObjPtr<mirror::ClassLoader>());
    621   ASSERT_NE(nullptr, iterablebase_klass);
    622   copied = FindCopiedMethod(origin, iterablebase_klass);
    623   ASSERT_NE(nullptr, copied);
    624   code = copied->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size);
    625   // the copied method should have a pointer to interpreter
    626   ASSERT_TRUE(class_linker_->IsQuickToInterpreterBridge(code));
    627 }
    628 
    629 }  // namespace art
    630