blob: 57d098798246005e97e58b047a9384b7a0b974fd [file] [log] [blame]
Vladimir Marko1352f132017-04-28 15:28:29 +01001/*
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#ifndef ART_COMPILER_IMAGE_TEST_H_
18#define ART_COMPILER_IMAGE_TEST_H_
19
20#include "image.h"
21
22#include <memory>
23#include <string>
24#include <vector>
25
26#include "android-base/stringprintf.h"
27
28#include "art_method-inl.h"
29#include "base/unix_file/fd_file.h"
30#include "class_linker-inl.h"
Vladimir Marko1352f132017-04-28 15:28:29 +010031#include "common_compiler_test.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070032#include "compiler_callbacks.h"
Vladimir Marko1352f132017-04-28 15:28:29 +010033#include "debug/method_debug_info.h"
34#include "dex/quick_compiler_callbacks.h"
35#include "driver/compiler_options.h"
36#include "elf_writer.h"
37#include "elf_writer_quick.h"
38#include "gc/space/image_space.h"
39#include "image_writer.h"
40#include "linker/buffered_output_stream.h"
41#include "linker/file_output_stream.h"
42#include "linker/multi_oat_relative_patcher.h"
43#include "lock_word.h"
44#include "mirror/object-inl.h"
45#include "oat_writer.h"
46#include "scoped_thread_state_change-inl.h"
47#include "signal_catcher.h"
48#include "utils.h"
49
50namespace art {
51
52static const uintptr_t kRequestedImageBase = ART_BASE_ADDRESS;
53
54struct CompilationHelper {
55 std::vector<std::string> dex_file_locations;
56 std::vector<ScratchFile> image_locations;
57 std::vector<std::unique_ptr<const DexFile>> extra_dex_files;
58 std::vector<ScratchFile> image_files;
59 std::vector<ScratchFile> oat_files;
60 std::vector<ScratchFile> vdex_files;
61 std::string image_dir;
62
63 void Compile(CompilerDriver* driver,
64 ImageHeader::StorageMode storage_mode);
65
66 std::vector<size_t> GetImageObjectSectionSizes();
67
68 ~CompilationHelper();
69};
70
71class ImageTest : public CommonCompilerTest {
72 protected:
73 virtual void SetUp() {
74 ReserveImageSpace();
75 CommonCompilerTest::SetUp();
76 }
77
78 void TestWriteRead(ImageHeader::StorageMode storage_mode);
79
80 void Compile(ImageHeader::StorageMode storage_mode,
81 CompilationHelper& out_helper,
82 const std::string& extra_dex = "",
83 const std::initializer_list<std::string>& image_classes = {});
84
85 void SetUpRuntimeOptions(RuntimeOptions* options) OVERRIDE {
86 CommonCompilerTest::SetUpRuntimeOptions(options);
Mathieu Chartiere01b6f62017-07-19 16:55:04 -070087 QuickCompilerCallbacks* new_callbacks =
88 new QuickCompilerCallbacks(CompilerCallbacks::CallbackMode::kCompileBootImage);
89 new_callbacks->SetVerificationResults(verification_results_.get());
90 callbacks_.reset(new_callbacks);
Vladimir Marko1352f132017-04-28 15:28:29 +010091 options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
92 }
93
94 std::unordered_set<std::string>* GetImageClasses() OVERRIDE {
95 return new std::unordered_set<std::string>(image_classes_);
96 }
97
98 ArtMethod* FindCopiedMethod(ArtMethod* origin, mirror::Class* klass)
99 REQUIRES_SHARED(Locks::mutator_lock_) {
100 PointerSize pointer_size = class_linker_->GetImagePointerSize();
101 for (ArtMethod& m : klass->GetCopiedMethods(pointer_size)) {
102 if (strcmp(origin->GetName(), m.GetName()) == 0 &&
103 origin->GetSignature() == m.GetSignature()) {
104 return &m;
105 }
106 }
107 return nullptr;
108 }
109
110 private:
111 std::unordered_set<std::string> image_classes_;
112};
113
114inline CompilationHelper::~CompilationHelper() {
115 for (ScratchFile& image_file : image_files) {
116 image_file.Unlink();
117 }
118 for (ScratchFile& oat_file : oat_files) {
119 oat_file.Unlink();
120 }
121 for (ScratchFile& vdex_file : vdex_files) {
122 vdex_file.Unlink();
123 }
124 const int rmdir_result = rmdir(image_dir.c_str());
125 CHECK_EQ(0, rmdir_result);
126}
127
128inline std::vector<size_t> CompilationHelper::GetImageObjectSectionSizes() {
129 std::vector<size_t> ret;
130 for (ScratchFile& image_file : image_files) {
131 std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
132 CHECK(file.get() != nullptr);
133 ImageHeader image_header;
134 CHECK_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
135 CHECK(image_header.IsValid());
136 ret.push_back(image_header.GetImageSize());
137 }
138 return ret;
139}
140
141inline void CompilationHelper::Compile(CompilerDriver* driver,
142 ImageHeader::StorageMode storage_mode) {
143 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
144 std::vector<const DexFile*> class_path = class_linker->GetBootClassPath();
145
146 for (const std::unique_ptr<const DexFile>& dex_file : extra_dex_files) {
147 {
148 ScopedObjectAccess soa(Thread::Current());
149 // Inject in boot class path so that the compiler driver can see it.
150 class_linker->AppendToBootClassPath(soa.Self(), *dex_file.get());
151 }
152 class_path.push_back(dex_file.get());
153 }
154
155 // Enable write for dex2dex.
156 for (const DexFile* dex_file : class_path) {
157 dex_file_locations.push_back(dex_file->GetLocation());
158 if (dex_file->IsReadOnly()) {
159 dex_file->EnableWrite();
160 }
161 }
162 {
163 // Create a generic tmp file, to be the base of the .art and .oat temporary files.
164 ScratchFile location;
165 for (int i = 0; i < static_cast<int>(class_path.size()); ++i) {
166 std::string cur_location =
167 android::base::StringPrintf("%s-%d.art", location.GetFilename().c_str(), i);
168 image_locations.push_back(ScratchFile(cur_location));
169 }
170 }
171 std::vector<std::string> image_filenames;
172 for (ScratchFile& file : image_locations) {
173 std::string image_filename(GetSystemImageFilename(file.GetFilename().c_str(), kRuntimeISA));
174 image_filenames.push_back(image_filename);
175 size_t pos = image_filename.rfind('/');
176 CHECK_NE(pos, std::string::npos) << image_filename;
177 if (image_dir.empty()) {
178 image_dir = image_filename.substr(0, pos);
179 int mkdir_result = mkdir(image_dir.c_str(), 0700);
180 CHECK_EQ(0, mkdir_result) << image_dir;
181 }
182 image_files.push_back(ScratchFile(OS::CreateEmptyFile(image_filename.c_str())));
183 }
184
185 std::vector<std::string> oat_filenames;
186 std::vector<std::string> vdex_filenames;
187 for (const std::string& image_filename : image_filenames) {
188 std::string oat_filename = ReplaceFileExtension(image_filename, "oat");
189 oat_files.push_back(ScratchFile(OS::CreateEmptyFile(oat_filename.c_str())));
190 oat_filenames.push_back(oat_filename);
191 std::string vdex_filename = ReplaceFileExtension(image_filename, "vdex");
192 vdex_files.push_back(ScratchFile(OS::CreateEmptyFile(vdex_filename.c_str())));
193 vdex_filenames.push_back(vdex_filename);
194 }
195
196 std::unordered_map<const DexFile*, size_t> dex_file_to_oat_index_map;
197 std::vector<const char*> oat_filename_vector;
198 for (const std::string& file : oat_filenames) {
199 oat_filename_vector.push_back(file.c_str());
200 }
201 std::vector<const char*> image_filename_vector;
202 for (const std::string& file : image_filenames) {
203 image_filename_vector.push_back(file.c_str());
204 }
205 size_t image_idx = 0;
206 for (const DexFile* dex_file : class_path) {
207 dex_file_to_oat_index_map.emplace(dex_file, image_idx);
208 ++image_idx;
209 }
210 // TODO: compile_pic should be a test argument.
211 std::unique_ptr<ImageWriter> writer(new ImageWriter(*driver,
212 kRequestedImageBase,
213 /*compile_pic*/false,
214 /*compile_app_image*/false,
215 storage_mode,
216 oat_filename_vector,
217 dex_file_to_oat_index_map));
218 {
219 {
220 jobject class_loader = nullptr;
221 TimingLogger timings("ImageTest::WriteRead", false, false);
222 TimingLogger::ScopedTiming t("CompileAll", &timings);
223 driver->SetDexFilesForOatFile(class_path);
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +0100224 driver->CompileAll(class_loader, class_path, &timings);
Vladimir Marko1352f132017-04-28 15:28:29 +0100225
226 t.NewTiming("WriteElf");
227 SafeMap<std::string, std::string> key_value_store;
228 std::vector<const char*> dex_filename_vector;
229 for (size_t i = 0; i < class_path.size(); ++i) {
230 dex_filename_vector.push_back("");
231 }
232 key_value_store.Put(OatHeader::kBootClassPathKey,
233 gc::space::ImageSpace::GetMultiImageBootClassPath(
234 dex_filename_vector,
235 oat_filename_vector,
236 image_filename_vector));
237
238 std::vector<std::unique_ptr<ElfWriter>> elf_writers;
239 std::vector<std::unique_ptr<OatWriter>> oat_writers;
240 for (ScratchFile& oat_file : oat_files) {
241 elf_writers.emplace_back(CreateElfWriterQuick(driver->GetInstructionSet(),
242 driver->GetInstructionSetFeatures(),
243 &driver->GetCompilerOptions(),
244 oat_file.GetFile()));
245 elf_writers.back()->Start();
246 oat_writers.emplace_back(new OatWriter(/*compiling_boot_image*/true,
247 &timings,
248 /*profile_compilation_info*/nullptr));
249 }
250
251 std::vector<OutputStream*> rodata;
252 std::vector<std::unique_ptr<MemMap>> opened_dex_files_map;
253 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
254 // Now that we have finalized key_value_store_, start writing the oat file.
255 for (size_t i = 0, size = oat_writers.size(); i != size; ++i) {
256 const DexFile* dex_file = class_path[i];
257 rodata.push_back(elf_writers[i]->StartRoData());
258 ArrayRef<const uint8_t> raw_dex_file(
259 reinterpret_cast<const uint8_t*>(&dex_file->GetHeader()),
260 dex_file->GetHeader().file_size_);
261 oat_writers[i]->AddRawDexFileSource(raw_dex_file,
262 dex_file->GetLocation().c_str(),
263 dex_file->GetLocationChecksum());
264
265 std::unique_ptr<MemMap> cur_opened_dex_files_map;
266 std::vector<std::unique_ptr<const DexFile>> cur_opened_dex_files;
267 bool dex_files_ok = oat_writers[i]->WriteAndOpenDexFiles(
268 kIsVdexEnabled ? vdex_files[i].GetFile() : oat_files[i].GetFile(),
269 rodata.back(),
270 driver->GetInstructionSet(),
271 driver->GetInstructionSetFeatures(),
272 &key_value_store,
273 /* verify */ false, // Dex files may be dex-to-dex-ed, don't verify.
274 /* update_input_vdex */ false,
275 &cur_opened_dex_files_map,
276 &cur_opened_dex_files);
277 ASSERT_TRUE(dex_files_ok);
278
279 if (cur_opened_dex_files_map != nullptr) {
280 opened_dex_files_map.push_back(std::move(cur_opened_dex_files_map));
281 for (std::unique_ptr<const DexFile>& cur_dex_file : cur_opened_dex_files) {
282 // dex_file_oat_index_map_.emplace(dex_file.get(), i);
283 opened_dex_files.push_back(std::move(cur_dex_file));
284 }
285 } else {
286 ASSERT_TRUE(cur_opened_dex_files.empty());
287 }
288 }
289 bool image_space_ok = writer->PrepareImageAddressSpace();
290 ASSERT_TRUE(image_space_ok);
291
292 if (kIsVdexEnabled) {
293 for (size_t i = 0, size = vdex_files.size(); i != size; ++i) {
Andreas Gampe8bdda5a2017-06-08 15:30:36 -0700294 std::unique_ptr<BufferedOutputStream> vdex_out =
295 std::make_unique<BufferedOutputStream>(
296 std::make_unique<FileOutputStream>(vdex_files[i].GetFile()));
Vladimir Marko1352f132017-04-28 15:28:29 +0100297 oat_writers[i]->WriteVerifierDeps(vdex_out.get(), nullptr);
298 oat_writers[i]->WriteChecksumsAndVdexHeader(vdex_out.get());
299 }
300 }
301
302 for (size_t i = 0, size = oat_files.size(); i != size; ++i) {
303 linker::MultiOatRelativePatcher patcher(driver->GetInstructionSet(),
304 driver->GetInstructionSetFeatures());
305 OatWriter* const oat_writer = oat_writers[i].get();
306 ElfWriter* const elf_writer = elf_writers[i].get();
307 std::vector<const DexFile*> cur_dex_files(1u, class_path[i]);
308 oat_writer->Initialize(driver, writer.get(), cur_dex_files);
309 oat_writer->PrepareLayout(&patcher);
310 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
311 size_t text_size = oat_writer->GetOatSize() - rodata_size;
312 elf_writer->PrepareDynamicSection(rodata_size,
313 text_size,
314 oat_writer->GetBssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100315 oat_writer->GetBssMethodsOffset(),
Vladimir Marko1352f132017-04-28 15:28:29 +0100316 oat_writer->GetBssRootsOffset());
317
318 writer->UpdateOatFileLayout(i,
319 elf_writer->GetLoadedSize(),
320 oat_writer->GetOatDataOffset(),
321 oat_writer->GetOatSize());
322
323 bool rodata_ok = oat_writer->WriteRodata(rodata[i]);
324 ASSERT_TRUE(rodata_ok);
325 elf_writer->EndRoData(rodata[i]);
326
327 OutputStream* text = elf_writer->StartText();
328 bool text_ok = oat_writer->WriteCode(text);
329 ASSERT_TRUE(text_ok);
330 elf_writer->EndText(text);
331
332 bool header_ok = oat_writer->WriteHeader(elf_writer->GetStream(), 0u, 0u, 0u);
333 ASSERT_TRUE(header_ok);
334
335 writer->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
336
337 elf_writer->WriteDynamicSection();
338 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
339
340 bool success = elf_writer->End();
341 ASSERT_TRUE(success);
342 }
343 }
344
345 bool success_image = writer->Write(kInvalidFd,
346 image_filename_vector,
347 oat_filename_vector);
348 ASSERT_TRUE(success_image);
349
350 for (size_t i = 0, size = oat_filenames.size(); i != size; ++i) {
351 const char* oat_filename = oat_filenames[i].c_str();
352 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
353 ASSERT_TRUE(oat_file != nullptr);
354 bool success_fixup = ElfWriter::Fixup(oat_file.get(),
355 writer->GetOatDataBegin(i));
356 ASSERT_TRUE(success_fixup);
357 ASSERT_EQ(oat_file->FlushCloseOrErase(), 0) << "Could not flush and close oat file "
358 << oat_filename;
359 }
360 }
361}
362
363inline void ImageTest::Compile(ImageHeader::StorageMode storage_mode,
364 CompilationHelper& helper,
365 const std::string& extra_dex,
366 const std::initializer_list<std::string>& image_classes) {
367 for (const std::string& image_class : image_classes) {
368 image_classes_.insert(image_class);
369 }
370 CreateCompilerDriver(Compiler::kOptimizing, kRuntimeISA, kIsTargetBuild ? 2U : 16U);
371 // Set inline filter values.
372 compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
373 image_classes_.clear();
374 if (!extra_dex.empty()) {
375 helper.extra_dex_files = OpenTestDexFiles(extra_dex.c_str());
376 }
377 helper.Compile(compiler_driver_.get(), storage_mode);
378 if (image_classes.begin() != image_classes.end()) {
379 // Make sure the class got initialized.
380 ScopedObjectAccess soa(Thread::Current());
381 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
382 for (const std::string& image_class : image_classes) {
383 mirror::Class* klass = class_linker->FindSystemClass(Thread::Current(), image_class.c_str());
384 EXPECT_TRUE(klass != nullptr);
385 EXPECT_TRUE(klass->IsInitialized());
386 }
387 }
388}
389
390inline void ImageTest::TestWriteRead(ImageHeader::StorageMode storage_mode) {
391 CompilationHelper helper;
392 Compile(storage_mode, /*out*/ helper);
393 std::vector<uint64_t> image_file_sizes;
394 for (ScratchFile& image_file : helper.image_files) {
395 std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
396 ASSERT_TRUE(file.get() != nullptr);
397 ImageHeader image_header;
398 ASSERT_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
399 ASSERT_TRUE(image_header.IsValid());
400 const auto& bitmap_section = image_header.GetImageSection(ImageHeader::kSectionImageBitmap);
401 ASSERT_GE(bitmap_section.Offset(), sizeof(image_header));
402 ASSERT_NE(0U, bitmap_section.Size());
403
404 gc::Heap* heap = Runtime::Current()->GetHeap();
405 ASSERT_TRUE(heap->HaveContinuousSpaces());
406 gc::space::ContinuousSpace* space = heap->GetNonMovingSpace();
407 ASSERT_FALSE(space->IsImageSpace());
408 ASSERT_TRUE(space != nullptr);
409 ASSERT_TRUE(space->IsMallocSpace());
410 image_file_sizes.push_back(file->GetLength());
411 }
412
413 ASSERT_TRUE(compiler_driver_->GetImageClasses() != nullptr);
414 std::unordered_set<std::string> image_classes(*compiler_driver_->GetImageClasses());
415
416 // Need to delete the compiler since it has worker threads which are attached to runtime.
417 compiler_driver_.reset();
418
419 // Tear down old runtime before making a new one, clearing out misc state.
420
421 // Remove the reservation of the memory for use to load the image.
422 // Need to do this before we reset the runtime.
423 UnreserveImageSpace();
424
425 helper.extra_dex_files.clear();
426 runtime_.reset();
427 java_lang_dex_file_ = nullptr;
428
429 MemMap::Init();
430
431 RuntimeOptions options;
432 std::string image("-Ximage:");
433 image.append(helper.image_locations[0].GetFilename());
434 options.push_back(std::make_pair(image.c_str(), static_cast<void*>(nullptr)));
435 // By default the compiler this creates will not include patch information.
436 options.push_back(std::make_pair("-Xnorelocate", nullptr));
437
438 if (!Runtime::Create(options, false)) {
439 LOG(FATAL) << "Failed to create runtime";
440 return;
441 }
442 runtime_.reset(Runtime::Current());
443 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
444 // give it away now and then switch to a more managable ScopedObjectAccess.
445 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
446 ScopedObjectAccess soa(Thread::Current());
447 ASSERT_TRUE(runtime_.get() != nullptr);
448 class_linker_ = runtime_->GetClassLinker();
449
450 gc::Heap* heap = Runtime::Current()->GetHeap();
451 ASSERT_TRUE(heap->HasBootImageSpace());
452 ASSERT_TRUE(heap->GetNonMovingSpace()->IsMallocSpace());
453
454 // We loaded the runtime with an explicit image, so it must exist.
455 ASSERT_EQ(heap->GetBootImageSpaces().size(), image_file_sizes.size());
456 for (size_t i = 0; i < helper.dex_file_locations.size(); ++i) {
457 std::unique_ptr<const DexFile> dex(
458 LoadExpectSingleDexFile(helper.dex_file_locations[i].c_str()));
459 ASSERT_TRUE(dex != nullptr);
460 uint64_t image_file_size = image_file_sizes[i];
461 gc::space::ImageSpace* image_space = heap->GetBootImageSpaces()[i];
462 ASSERT_TRUE(image_space != nullptr);
463 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
464 // Uncompressed, image should be smaller than file.
465 ASSERT_LE(image_space->GetImageHeader().GetImageSize(), image_file_size);
466 } else if (image_file_size > 16 * KB) {
467 // Compressed, file should be smaller than image. Not really valid for small images.
468 ASSERT_LE(image_file_size, image_space->GetImageHeader().GetImageSize());
469 }
470
471 image_space->VerifyImageAllocations();
472 uint8_t* image_begin = image_space->Begin();
473 uint8_t* image_end = image_space->End();
474 if (i == 0) {
475 // This check is only valid for image 0.
476 CHECK_EQ(kRequestedImageBase, reinterpret_cast<uintptr_t>(image_begin));
477 }
478 for (size_t j = 0; j < dex->NumClassDefs(); ++j) {
479 const DexFile::ClassDef& class_def = dex->GetClassDef(j);
480 const char* descriptor = dex->GetClassDescriptor(class_def);
481 mirror::Class* klass = class_linker_->FindSystemClass(soa.Self(), descriptor);
482 EXPECT_TRUE(klass != nullptr) << descriptor;
483 if (image_classes.find(descriptor) == image_classes.end()) {
484 EXPECT_TRUE(reinterpret_cast<uint8_t*>(klass) >= image_end ||
485 reinterpret_cast<uint8_t*>(klass) < image_begin) << descriptor;
486 } else {
487 // Image classes should be located inside the image.
488 EXPECT_LT(image_begin, reinterpret_cast<uint8_t*>(klass)) << descriptor;
489 EXPECT_LT(reinterpret_cast<uint8_t*>(klass), image_end) << descriptor;
490 }
491 EXPECT_TRUE(Monitor::IsValidLockWord(klass->GetLockWord(false)));
492 }
493 }
494}
495
496
497} // namespace art
498
499#endif // ART_COMPILER_IMAGE_TEST_H_