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