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