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