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 "base/unix_file/fd_file.h"
     24 #include "common_compiler_test.h"
     25 #include "elf_fixup.h"
     26 #include "gc/space/image_space.h"
     27 #include "image_writer.h"
     28 #include "lock_word.h"
     29 #include "mirror/object-inl.h"
     30 #include "oat_writer.h"
     31 #include "scoped_thread_state_change.h"
     32 #include "signal_catcher.h"
     33 #include "utils.h"
     34 #include "vector_output_stream.h"
     35 
     36 namespace art {
     37 
     38 class ImageTest : public CommonCompilerTest {
     39  protected:
     40   virtual void SetUp() {
     41     ReserveImageSpace();
     42     CommonCompilerTest::SetUp();
     43   }
     44 };
     45 
     46 TEST_F(ImageTest, WriteRead) {
     47   // Create a generic location tmp file, to be the base of the .art and .oat temporary files.
     48   ScratchFile location;
     49   ScratchFile image_location(location, ".art");
     50 
     51   std::string image_filename(GetSystemImageFilename(image_location.GetFilename().c_str(),
     52                                                     kRuntimeISA));
     53   size_t pos = image_filename.rfind('/');
     54   CHECK_NE(pos, std::string::npos) << image_filename;
     55   std::string image_dir(image_filename, 0, pos);
     56   int mkdir_result = mkdir(image_dir.c_str(), 0700);
     57   CHECK_EQ(0, mkdir_result) << image_dir;
     58   ScratchFile image_file(OS::CreateEmptyFile(image_filename.c_str()));
     59 
     60   std::string oat_filename(image_filename, 0, image_filename.size() - 3);
     61   oat_filename += "oat";
     62   ScratchFile oat_file(OS::CreateEmptyFile(oat_filename.c_str()));
     63 
     64   {
     65     {
     66       jobject class_loader = NULL;
     67       ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
     68       TimingLogger timings("ImageTest::WriteRead", false, false);
     69       TimingLogger::ScopedTiming t("CompileAll", &timings);
     70       if (kUsePortableCompiler) {
     71         // TODO: we disable this for portable so the test executes in a reasonable amount of time.
     72         //       We shouldn't need to do this.
     73         compiler_options_->SetCompilerFilter(CompilerOptions::kInterpretOnly);
     74       }
     75       for (const DexFile* dex_file : class_linker->GetBootClassPath()) {
     76         dex_file->EnableWrite();
     77       }
     78       compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
     79 
     80       t.NewTiming("WriteElf");
     81       ScopedObjectAccess soa(Thread::Current());
     82       SafeMap<std::string, std::string> key_value_store;
     83       OatWriter oat_writer(class_linker->GetBootClassPath(), 0, 0, 0, compiler_driver_.get(), &timings,
     84                            &key_value_store);
     85       bool success = compiler_driver_->WriteElf(GetTestAndroidRoot(),
     86                                                 !kIsTargetBuild,
     87                                                 class_linker->GetBootClassPath(),
     88                                                 &oat_writer,
     89                                                 oat_file.GetFile());
     90       ASSERT_TRUE(success);
     91     }
     92   }
     93   // Workound bug that mcld::Linker::emit closes oat_file by reopening as dup_oat.
     94   std::unique_ptr<File> dup_oat(OS::OpenFileReadWrite(oat_file.GetFilename().c_str()));
     95   ASSERT_TRUE(dup_oat.get() != NULL);
     96 
     97   const uintptr_t requested_image_base = ART_BASE_ADDRESS;
     98   {
     99     ImageWriter writer(*compiler_driver_.get());
    100     bool success_image = writer.Write(image_file.GetFilename(), requested_image_base,
    101                                       dup_oat->GetPath(), dup_oat->GetPath(), /*compile_pic*/false);
    102     ASSERT_TRUE(success_image);
    103     bool success_fixup = ElfFixup::Fixup(dup_oat.get(), writer.GetOatDataBegin());
    104     ASSERT_TRUE(success_fixup);
    105 
    106     ASSERT_EQ(dup_oat->FlushCloseOrErase(), 0) << "Could not flush and close oat file "
    107                                                << oat_file.GetFilename();
    108   }
    109 
    110   {
    111     std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
    112     ASSERT_TRUE(file.get() != NULL);
    113     ImageHeader image_header;
    114     ASSERT_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
    115     ASSERT_TRUE(image_header.IsValid());
    116     ASSERT_GE(image_header.GetImageBitmapOffset(), sizeof(image_header));
    117     ASSERT_NE(0U, image_header.GetImageBitmapSize());
    118 
    119     gc::Heap* heap = Runtime::Current()->GetHeap();
    120     ASSERT_TRUE(!heap->GetContinuousSpaces().empty());
    121     gc::space::ContinuousSpace* space = heap->GetNonMovingSpace();
    122     ASSERT_FALSE(space->IsImageSpace());
    123     ASSERT_TRUE(space != NULL);
    124     ASSERT_TRUE(space->IsMallocSpace());
    125     ASSERT_GE(sizeof(image_header) + space->Size(), static_cast<size_t>(file->GetLength()));
    126   }
    127 
    128   ASSERT_TRUE(compiler_driver_->GetImageClasses() != NULL);
    129   std::set<std::string> image_classes(*compiler_driver_->GetImageClasses());
    130 
    131   // Need to delete the compiler since it has worker threads which are attached to runtime.
    132   compiler_driver_.reset();
    133 
    134   // Tear down old runtime before making a new one, clearing out misc state.
    135 
    136   // Remove the reservation of the memory for use to load the image.
    137   // Need to do this before we reset the runtime.
    138   UnreserveImageSpace();
    139 
    140   runtime_.reset();
    141   java_lang_dex_file_ = NULL;
    142 
    143   MemMap::Init();
    144   std::unique_ptr<const DexFile> dex(LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str()));
    145 
    146   RuntimeOptions options;
    147   std::string image("-Ximage:");
    148   image.append(image_location.GetFilename());
    149   options.push_back(std::make_pair(image.c_str(), reinterpret_cast<void*>(NULL)));
    150   // By default the compiler this creates will not include patch information.
    151   options.push_back(std::make_pair("-Xnorelocate", nullptr));
    152 
    153   if (!Runtime::Create(options, false)) {
    154     LOG(FATAL) << "Failed to create runtime";
    155     return;
    156   }
    157   runtime_.reset(Runtime::Current());
    158   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
    159   // give it away now and then switch to a more managable ScopedObjectAccess.
    160   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
    161   ScopedObjectAccess soa(Thread::Current());
    162   ASSERT_TRUE(runtime_.get() != NULL);
    163   class_linker_ = runtime_->GetClassLinker();
    164 
    165   gc::Heap* heap = Runtime::Current()->GetHeap();
    166   ASSERT_TRUE(heap->HasImageSpace());
    167   ASSERT_TRUE(heap->GetNonMovingSpace()->IsMallocSpace());
    168 
    169   gc::space::ImageSpace* image_space = heap->GetImageSpace();
    170   image_space->VerifyImageAllocations();
    171   byte* image_begin = image_space->Begin();
    172   byte* image_end = image_space->End();
    173   CHECK_EQ(requested_image_base, reinterpret_cast<uintptr_t>(image_begin));
    174   for (size_t i = 0; i < dex->NumClassDefs(); ++i) {
    175     const DexFile::ClassDef& class_def = dex->GetClassDef(i);
    176     const char* descriptor = dex->GetClassDescriptor(class_def);
    177     mirror::Class* klass = class_linker_->FindSystemClass(soa.Self(), descriptor);
    178     EXPECT_TRUE(klass != nullptr) << descriptor;
    179     if (image_classes.find(descriptor) != image_classes.end()) {
    180       // Image classes should be located inside the image.
    181       EXPECT_LT(image_begin, reinterpret_cast<byte*>(klass)) << descriptor;
    182       EXPECT_LT(reinterpret_cast<byte*>(klass), image_end) << descriptor;
    183     } else {
    184       EXPECT_TRUE(reinterpret_cast<byte*>(klass) >= image_end ||
    185                   reinterpret_cast<byte*>(klass) < image_begin) << descriptor;
    186     }
    187     EXPECT_TRUE(Monitor::IsValidLockWord(klass->GetLockWord(false)));
    188   }
    189 
    190   image_file.Unlink();
    191   oat_file.Unlink();
    192   int rmdir_result = rmdir(image_dir.c_str());
    193   CHECK_EQ(0, rmdir_result);
    194 }
    195 
    196 TEST_F(ImageTest, ImageHeaderIsValid) {
    197     uint32_t image_begin = ART_BASE_ADDRESS;
    198     uint32_t image_size_ = 16 * KB;
    199     uint32_t image_bitmap_offset = 0;
    200     uint32_t image_bitmap_size = 0;
    201     uint32_t image_roots = ART_BASE_ADDRESS + (1 * KB);
    202     uint32_t oat_checksum = 0;
    203     uint32_t oat_file_begin = ART_BASE_ADDRESS + (4 * KB);  // page aligned
    204     uint32_t oat_data_begin = ART_BASE_ADDRESS + (8 * KB);  // page aligned
    205     uint32_t oat_data_end = ART_BASE_ADDRESS + (9 * KB);
    206     uint32_t oat_file_end = ART_BASE_ADDRESS + (10 * KB);
    207     ImageHeader image_header(image_begin,
    208                              image_size_,
    209                              image_bitmap_offset,
    210                              image_bitmap_size,
    211                              image_roots,
    212                              oat_checksum,
    213                              oat_file_begin,
    214                              oat_data_begin,
    215                              oat_data_end,
    216                              oat_file_end,
    217                              /*compile_pic*/false);
    218     ASSERT_TRUE(image_header.IsValid());
    219 
    220     char* magic = const_cast<char*>(image_header.GetMagic());
    221     strcpy(magic, "");  // bad magic
    222     ASSERT_FALSE(image_header.IsValid());
    223     strcpy(magic, "art\n000");  // bad version
    224     ASSERT_FALSE(image_header.IsValid());
    225 }
    226 
    227 }  // namespace art
    228