blob: daa4b11967b7a5fe4b2bc67d30e8470606a00ecd [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,
Jeff Haoc23b0c02017-07-27 18:19:38 -0700217 dex_file_to_oat_index_map,
218 /*dirty_image_objects*/nullptr));
Vladimir Marko1352f132017-04-28 15:28:29 +0100219 {
220 {
221 jobject class_loader = nullptr;
222 TimingLogger timings("ImageTest::WriteRead", false, false);
223 TimingLogger::ScopedTiming t("CompileAll", &timings);
224 driver->SetDexFilesForOatFile(class_path);
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +0100225 driver->CompileAll(class_loader, class_path, &timings);
Vladimir Marko1352f132017-04-28 15:28:29 +0100226
227 t.NewTiming("WriteElf");
228 SafeMap<std::string, std::string> key_value_store;
229 std::vector<const char*> dex_filename_vector;
230 for (size_t i = 0; i < class_path.size(); ++i) {
231 dex_filename_vector.push_back("");
232 }
233 key_value_store.Put(OatHeader::kBootClassPathKey,
234 gc::space::ImageSpace::GetMultiImageBootClassPath(
235 dex_filename_vector,
236 oat_filename_vector,
237 image_filename_vector));
238
239 std::vector<std::unique_ptr<ElfWriter>> elf_writers;
240 std::vector<std::unique_ptr<OatWriter>> oat_writers;
241 for (ScratchFile& oat_file : oat_files) {
242 elf_writers.emplace_back(CreateElfWriterQuick(driver->GetInstructionSet(),
243 driver->GetInstructionSetFeatures(),
244 &driver->GetCompilerOptions(),
245 oat_file.GetFile()));
246 elf_writers.back()->Start();
247 oat_writers.emplace_back(new OatWriter(/*compiling_boot_image*/true,
248 &timings,
249 /*profile_compilation_info*/nullptr));
250 }
251
252 std::vector<OutputStream*> rodata;
253 std::vector<std::unique_ptr<MemMap>> opened_dex_files_map;
254 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
255 // Now that we have finalized key_value_store_, start writing the oat file.
256 for (size_t i = 0, size = oat_writers.size(); i != size; ++i) {
257 const DexFile* dex_file = class_path[i];
258 rodata.push_back(elf_writers[i]->StartRoData());
259 ArrayRef<const uint8_t> raw_dex_file(
260 reinterpret_cast<const uint8_t*>(&dex_file->GetHeader()),
261 dex_file->GetHeader().file_size_);
262 oat_writers[i]->AddRawDexFileSource(raw_dex_file,
263 dex_file->GetLocation().c_str(),
264 dex_file->GetLocationChecksum());
265
266 std::unique_ptr<MemMap> cur_opened_dex_files_map;
267 std::vector<std::unique_ptr<const DexFile>> cur_opened_dex_files;
268 bool dex_files_ok = oat_writers[i]->WriteAndOpenDexFiles(
269 kIsVdexEnabled ? vdex_files[i].GetFile() : oat_files[i].GetFile(),
270 rodata.back(),
271 driver->GetInstructionSet(),
272 driver->GetInstructionSetFeatures(),
273 &key_value_store,
274 /* verify */ false, // Dex files may be dex-to-dex-ed, don't verify.
275 /* update_input_vdex */ false,
276 &cur_opened_dex_files_map,
277 &cur_opened_dex_files);
278 ASSERT_TRUE(dex_files_ok);
279
280 if (cur_opened_dex_files_map != nullptr) {
281 opened_dex_files_map.push_back(std::move(cur_opened_dex_files_map));
282 for (std::unique_ptr<const DexFile>& cur_dex_file : cur_opened_dex_files) {
283 // dex_file_oat_index_map_.emplace(dex_file.get(), i);
284 opened_dex_files.push_back(std::move(cur_dex_file));
285 }
286 } else {
287 ASSERT_TRUE(cur_opened_dex_files.empty());
288 }
289 }
290 bool image_space_ok = writer->PrepareImageAddressSpace();
291 ASSERT_TRUE(image_space_ok);
292
293 if (kIsVdexEnabled) {
294 for (size_t i = 0, size = vdex_files.size(); i != size; ++i) {
Andreas Gampe8bdda5a2017-06-08 15:30:36 -0700295 std::unique_ptr<BufferedOutputStream> vdex_out =
296 std::make_unique<BufferedOutputStream>(
297 std::make_unique<FileOutputStream>(vdex_files[i].GetFile()));
Vladimir Marko1352f132017-04-28 15:28:29 +0100298 oat_writers[i]->WriteVerifierDeps(vdex_out.get(), nullptr);
299 oat_writers[i]->WriteChecksumsAndVdexHeader(vdex_out.get());
300 }
301 }
302
303 for (size_t i = 0, size = oat_files.size(); i != size; ++i) {
304 linker::MultiOatRelativePatcher patcher(driver->GetInstructionSet(),
305 driver->GetInstructionSetFeatures());
306 OatWriter* const oat_writer = oat_writers[i].get();
307 ElfWriter* const elf_writer = elf_writers[i].get();
308 std::vector<const DexFile*> cur_dex_files(1u, class_path[i]);
309 oat_writer->Initialize(driver, writer.get(), cur_dex_files);
310 oat_writer->PrepareLayout(&patcher);
311 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
312 size_t text_size = oat_writer->GetOatSize() - rodata_size;
313 elf_writer->PrepareDynamicSection(rodata_size,
314 text_size,
315 oat_writer->GetBssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100316 oat_writer->GetBssMethodsOffset(),
Vladimir Marko1352f132017-04-28 15:28:29 +0100317 oat_writer->GetBssRootsOffset());
318
319 writer->UpdateOatFileLayout(i,
320 elf_writer->GetLoadedSize(),
321 oat_writer->GetOatDataOffset(),
322 oat_writer->GetOatSize());
323
324 bool rodata_ok = oat_writer->WriteRodata(rodata[i]);
325 ASSERT_TRUE(rodata_ok);
326 elf_writer->EndRoData(rodata[i]);
327
328 OutputStream* text = elf_writer->StartText();
329 bool text_ok = oat_writer->WriteCode(text);
330 ASSERT_TRUE(text_ok);
331 elf_writer->EndText(text);
332
333 bool header_ok = oat_writer->WriteHeader(elf_writer->GetStream(), 0u, 0u, 0u);
334 ASSERT_TRUE(header_ok);
335
336 writer->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
337
338 elf_writer->WriteDynamicSection();
339 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
340
341 bool success = elf_writer->End();
342 ASSERT_TRUE(success);
343 }
344 }
345
346 bool success_image = writer->Write(kInvalidFd,
347 image_filename_vector,
348 oat_filename_vector);
349 ASSERT_TRUE(success_image);
350
351 for (size_t i = 0, size = oat_filenames.size(); i != size; ++i) {
352 const char* oat_filename = oat_filenames[i].c_str();
353 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
354 ASSERT_TRUE(oat_file != nullptr);
355 bool success_fixup = ElfWriter::Fixup(oat_file.get(),
356 writer->GetOatDataBegin(i));
357 ASSERT_TRUE(success_fixup);
358 ASSERT_EQ(oat_file->FlushCloseOrErase(), 0) << "Could not flush and close oat file "
359 << oat_filename;
360 }
361 }
362}
363
364inline void ImageTest::Compile(ImageHeader::StorageMode storage_mode,
365 CompilationHelper& helper,
366 const std::string& extra_dex,
367 const std::initializer_list<std::string>& image_classes) {
368 for (const std::string& image_class : image_classes) {
369 image_classes_.insert(image_class);
370 }
371 CreateCompilerDriver(Compiler::kOptimizing, kRuntimeISA, kIsTargetBuild ? 2U : 16U);
372 // Set inline filter values.
373 compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
374 image_classes_.clear();
375 if (!extra_dex.empty()) {
376 helper.extra_dex_files = OpenTestDexFiles(extra_dex.c_str());
377 }
378 helper.Compile(compiler_driver_.get(), storage_mode);
379 if (image_classes.begin() != image_classes.end()) {
380 // Make sure the class got initialized.
381 ScopedObjectAccess soa(Thread::Current());
382 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
383 for (const std::string& image_class : image_classes) {
384 mirror::Class* klass = class_linker->FindSystemClass(Thread::Current(), image_class.c_str());
385 EXPECT_TRUE(klass != nullptr);
386 EXPECT_TRUE(klass->IsInitialized());
387 }
388 }
389}
390
391inline void ImageTest::TestWriteRead(ImageHeader::StorageMode storage_mode) {
392 CompilationHelper helper;
393 Compile(storage_mode, /*out*/ helper);
394 std::vector<uint64_t> image_file_sizes;
395 for (ScratchFile& image_file : helper.image_files) {
396 std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
397 ASSERT_TRUE(file.get() != nullptr);
398 ImageHeader image_header;
399 ASSERT_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
400 ASSERT_TRUE(image_header.IsValid());
401 const auto& bitmap_section = image_header.GetImageSection(ImageHeader::kSectionImageBitmap);
402 ASSERT_GE(bitmap_section.Offset(), sizeof(image_header));
403 ASSERT_NE(0U, bitmap_section.Size());
404
405 gc::Heap* heap = Runtime::Current()->GetHeap();
406 ASSERT_TRUE(heap->HaveContinuousSpaces());
407 gc::space::ContinuousSpace* space = heap->GetNonMovingSpace();
408 ASSERT_FALSE(space->IsImageSpace());
409 ASSERT_TRUE(space != nullptr);
410 ASSERT_TRUE(space->IsMallocSpace());
411 image_file_sizes.push_back(file->GetLength());
412 }
413
414 ASSERT_TRUE(compiler_driver_->GetImageClasses() != nullptr);
415 std::unordered_set<std::string> image_classes(*compiler_driver_->GetImageClasses());
416
417 // Need to delete the compiler since it has worker threads which are attached to runtime.
418 compiler_driver_.reset();
419
420 // Tear down old runtime before making a new one, clearing out misc state.
421
422 // Remove the reservation of the memory for use to load the image.
423 // Need to do this before we reset the runtime.
424 UnreserveImageSpace();
425
426 helper.extra_dex_files.clear();
427 runtime_.reset();
428 java_lang_dex_file_ = nullptr;
429
430 MemMap::Init();
431
432 RuntimeOptions options;
433 std::string image("-Ximage:");
434 image.append(helper.image_locations[0].GetFilename());
435 options.push_back(std::make_pair(image.c_str(), static_cast<void*>(nullptr)));
436 // By default the compiler this creates will not include patch information.
437 options.push_back(std::make_pair("-Xnorelocate", nullptr));
438
439 if (!Runtime::Create(options, false)) {
440 LOG(FATAL) << "Failed to create runtime";
441 return;
442 }
443 runtime_.reset(Runtime::Current());
444 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
445 // give it away now and then switch to a more managable ScopedObjectAccess.
446 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
447 ScopedObjectAccess soa(Thread::Current());
448 ASSERT_TRUE(runtime_.get() != nullptr);
449 class_linker_ = runtime_->GetClassLinker();
450
451 gc::Heap* heap = Runtime::Current()->GetHeap();
452 ASSERT_TRUE(heap->HasBootImageSpace());
453 ASSERT_TRUE(heap->GetNonMovingSpace()->IsMallocSpace());
454
455 // We loaded the runtime with an explicit image, so it must exist.
456 ASSERT_EQ(heap->GetBootImageSpaces().size(), image_file_sizes.size());
457 for (size_t i = 0; i < helper.dex_file_locations.size(); ++i) {
458 std::unique_ptr<const DexFile> dex(
459 LoadExpectSingleDexFile(helper.dex_file_locations[i].c_str()));
460 ASSERT_TRUE(dex != nullptr);
461 uint64_t image_file_size = image_file_sizes[i];
462 gc::space::ImageSpace* image_space = heap->GetBootImageSpaces()[i];
463 ASSERT_TRUE(image_space != nullptr);
464 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
465 // Uncompressed, image should be smaller than file.
466 ASSERT_LE(image_space->GetImageHeader().GetImageSize(), image_file_size);
467 } else if (image_file_size > 16 * KB) {
468 // Compressed, file should be smaller than image. Not really valid for small images.
469 ASSERT_LE(image_file_size, image_space->GetImageHeader().GetImageSize());
470 }
471
472 image_space->VerifyImageAllocations();
473 uint8_t* image_begin = image_space->Begin();
474 uint8_t* image_end = image_space->End();
475 if (i == 0) {
476 // This check is only valid for image 0.
477 CHECK_EQ(kRequestedImageBase, reinterpret_cast<uintptr_t>(image_begin));
478 }
479 for (size_t j = 0; j < dex->NumClassDefs(); ++j) {
480 const DexFile::ClassDef& class_def = dex->GetClassDef(j);
481 const char* descriptor = dex->GetClassDescriptor(class_def);
482 mirror::Class* klass = class_linker_->FindSystemClass(soa.Self(), descriptor);
483 EXPECT_TRUE(klass != nullptr) << descriptor;
484 if (image_classes.find(descriptor) == image_classes.end()) {
485 EXPECT_TRUE(reinterpret_cast<uint8_t*>(klass) >= image_end ||
486 reinterpret_cast<uint8_t*>(klass) < image_begin) << descriptor;
487 } else {
488 // Image classes should be located inside the image.
489 EXPECT_LT(image_begin, reinterpret_cast<uint8_t*>(klass)) << descriptor;
490 EXPECT_LT(reinterpret_cast<uint8_t*>(klass), image_end) << descriptor;
491 }
492 EXPECT_TRUE(Monitor::IsValidLockWord(klass->GetLockWord(false)));
493 }
494 }
495}
496
497
498} // namespace art
499
500#endif // ART_COMPILER_IMAGE_TEST_H_