• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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:
SetUp()40   virtual void SetUp() {
41     ReserveImageSpace();
42     CommonCompilerTest::SetUp();
43   }
44 };
45 
TEST_F(ImageTest,WriteRead)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());
102     ASSERT_TRUE(success_image);
103     bool success_fixup = ElfFixup::Fixup(dup_oat.get(), writer.GetOatDataBegin());
104     ASSERT_TRUE(success_fixup);
105   }
106 
107   {
108     std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
109     ASSERT_TRUE(file.get() != NULL);
110     ImageHeader image_header;
111     file->ReadFully(&image_header, sizeof(image_header));
112     ASSERT_TRUE(image_header.IsValid());
113     ASSERT_GE(image_header.GetImageBitmapOffset(), sizeof(image_header));
114     ASSERT_NE(0U, image_header.GetImageBitmapSize());
115 
116     gc::Heap* heap = Runtime::Current()->GetHeap();
117     ASSERT_TRUE(!heap->GetContinuousSpaces().empty());
118     gc::space::ContinuousSpace* space = heap->GetNonMovingSpace();
119     ASSERT_FALSE(space->IsImageSpace());
120     ASSERT_TRUE(space != NULL);
121     ASSERT_TRUE(space->IsMallocSpace());
122     ASSERT_GE(sizeof(image_header) + space->Size(), static_cast<size_t>(file->GetLength()));
123   }
124 
125   ASSERT_TRUE(compiler_driver_->GetImageClasses() != NULL);
126   std::set<std::string> image_classes(*compiler_driver_->GetImageClasses());
127 
128   // Need to delete the compiler since it has worker threads which are attached to runtime.
129   compiler_driver_.reset();
130 
131   // Tear down old runtime before making a new one, clearing out misc state.
132 
133   // Remove the reservation of the memory for use to load the image.
134   // Need to do this before we reset the runtime.
135   UnreserveImageSpace();
136 
137   runtime_.reset();
138   java_lang_dex_file_ = NULL;
139 
140   MemMap::Init();
141   std::unique_ptr<const DexFile> dex(LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str()));
142 
143   RuntimeOptions options;
144   std::string image("-Ximage:");
145   image.append(image_location.GetFilename());
146   options.push_back(std::make_pair(image.c_str(), reinterpret_cast<void*>(NULL)));
147   // By default the compiler this creates will not include patch information.
148   options.push_back(std::make_pair("-Xnorelocate", nullptr));
149 
150   if (!Runtime::Create(options, false)) {
151     LOG(FATAL) << "Failed to create runtime";
152     return;
153   }
154   runtime_.reset(Runtime::Current());
155   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
156   // give it away now and then switch to a more managable ScopedObjectAccess.
157   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
158   ScopedObjectAccess soa(Thread::Current());
159   ASSERT_TRUE(runtime_.get() != NULL);
160   class_linker_ = runtime_->GetClassLinker();
161 
162   gc::Heap* heap = Runtime::Current()->GetHeap();
163   ASSERT_TRUE(heap->HasImageSpace());
164   ASSERT_TRUE(heap->GetNonMovingSpace()->IsMallocSpace());
165 
166   gc::space::ImageSpace* image_space = heap->GetImageSpace();
167   image_space->VerifyImageAllocations();
168   byte* image_begin = image_space->Begin();
169   byte* image_end = image_space->End();
170   CHECK_EQ(requested_image_base, reinterpret_cast<uintptr_t>(image_begin));
171   for (size_t i = 0; i < dex->NumClassDefs(); ++i) {
172     const DexFile::ClassDef& class_def = dex->GetClassDef(i);
173     const char* descriptor = dex->GetClassDescriptor(class_def);
174     mirror::Class* klass = class_linker_->FindSystemClass(soa.Self(), descriptor);
175     EXPECT_TRUE(klass != nullptr) << descriptor;
176     if (image_classes.find(descriptor) != image_classes.end()) {
177       // Image classes should be located inside the image.
178       EXPECT_LT(image_begin, reinterpret_cast<byte*>(klass)) << descriptor;
179       EXPECT_LT(reinterpret_cast<byte*>(klass), image_end) << descriptor;
180     } else {
181       EXPECT_TRUE(reinterpret_cast<byte*>(klass) >= image_end ||
182                   reinterpret_cast<byte*>(klass) < image_begin) << descriptor;
183     }
184     EXPECT_TRUE(Monitor::IsValidLockWord(klass->GetLockWord(false)));
185   }
186 
187   image_file.Unlink();
188   oat_file.Unlink();
189   int rmdir_result = rmdir(image_dir.c_str());
190   CHECK_EQ(0, rmdir_result);
191 }
192 
TEST_F(ImageTest,ImageHeaderIsValid)193 TEST_F(ImageTest, ImageHeaderIsValid) {
194     uint32_t image_begin = ART_BASE_ADDRESS;
195     uint32_t image_size_ = 16 * KB;
196     uint32_t image_bitmap_offset = 0;
197     uint32_t image_bitmap_size = 0;
198     uint32_t image_roots = ART_BASE_ADDRESS + (1 * KB);
199     uint32_t oat_checksum = 0;
200     uint32_t oat_file_begin = ART_BASE_ADDRESS + (4 * KB);  // page aligned
201     uint32_t oat_data_begin = ART_BASE_ADDRESS + (8 * KB);  // page aligned
202     uint32_t oat_data_end = ART_BASE_ADDRESS + (9 * KB);
203     uint32_t oat_file_end = ART_BASE_ADDRESS + (10 * KB);
204     ImageHeader image_header(image_begin,
205                              image_size_,
206                              image_bitmap_offset,
207                              image_bitmap_size,
208                              image_roots,
209                              oat_checksum,
210                              oat_file_begin,
211                              oat_data_begin,
212                              oat_data_end,
213                              oat_file_end);
214     ASSERT_TRUE(image_header.IsValid());
215 
216     char* magic = const_cast<char*>(image_header.GetMagic());
217     strcpy(magic, "");  // bad magic
218     ASSERT_FALSE(image_header.IsValid());
219     strcpy(magic, "art\n000");  // bad version
220     ASSERT_FALSE(image_header.IsValid());
221 }
222 
223 }  // namespace art
224