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 #ifndef ART_DEX2OAT_LINKER_IMAGE_TEST_H_
18 #define ART_DEX2OAT_LINKER_IMAGE_TEST_H_
19
20 #include "oat/image.h"
21
22 #include <memory>
23 #include <string>
24 #include <string_view>
25 #include <vector>
26
27 #include "android-base/stringprintf.h"
28 #include "android-base/strings.h"
29
30 #include "art_method-inl.h"
31 #include "base/file_utils.h"
32 #include "base/hash_set.h"
33 #include "base/stl_util.h"
34 #include "base/unix_file/fd_file.h"
35 #include "base/utils.h"
36 #include "class_linker-inl.h"
37 #include "common_compiler_driver_test.h"
38 #include "compiler_callbacks.h"
39 #include "debug/method_debug_info.h"
40 #include "dex/quick_compiler_callbacks.h"
41 #include "dex/signature-inl.h"
42 #include "driver/compiler_driver.h"
43 #include "driver/compiler_options.h"
44 #include "gc/space/image_space.h"
45 #include "image_writer.h"
46 #include "linker/elf_writer.h"
47 #include "linker/elf_writer_quick.h"
48 #include "linker/multi_oat_relative_patcher.h"
49 #include "lock_word.h"
50 #include "mirror/object-inl.h"
51 #include "oat/oat.h"
52 #include "oat_writer.h"
53 #include "read_barrier_config.h"
54 #include "scoped_thread_state_change-inl.h"
55 #include "signal_catcher.h"
56 #include "stream/buffered_output_stream.h"
57 #include "stream/file_output_stream.h"
58
59 namespace art {
60 namespace linker {
61
62 static const uintptr_t kRequestedImageBase = ART_BASE_ADDRESS;
63
64 struct CompilationHelper {
65 std::vector<std::string> dex_file_locations;
66 std::vector<ScratchFile> image_locations;
67 std::string extra_dex;
68 std::vector<std::unique_ptr<const DexFile>> extra_dex_files;
69 std::vector<ScratchFile> image_files;
70 std::vector<ScratchFile> oat_files;
71 std::vector<ScratchFile> vdex_files;
72 std::string image_dir;
73
74 std::vector<size_t> GetImageObjectSectionSizes();
75
76 ~CompilationHelper();
77 };
78
79 class ImageTest : public CommonCompilerDriverTest {
80 protected:
SetUp()81 void SetUp() override {
82 ReserveImageSpace();
83 CommonCompilerDriverTest::SetUp();
84 }
85
GetCompilerFilter()86 CompilerFilter::Filter GetCompilerFilter() const override {
87 return compiler_filter_;
88 }
89
SetCompilerFilter(CompilerFilter::Filter compiler_filter)90 void SetCompilerFilter(CompilerFilter::Filter compiler_filter) {
91 compiler_filter_ = compiler_filter;
92 }
93
94 void Compile(ImageHeader::StorageMode storage_mode,
95 uint32_t max_image_block_size,
96 /*out*/ CompilationHelper& out_helper,
97 const std::string& extra_dex = "",
98 const std::initializer_list<std::string>& image_classes = {},
99 const std::initializer_list<std::string>& image_classes_failing_aot_clinit = {},
100 const std::initializer_list<std::string>& image_classes_failing_resolution = {});
101
SetUpRuntimeOptions(RuntimeOptions * options)102 void SetUpRuntimeOptions(RuntimeOptions* options) override {
103 CommonCompilerDriverTest::SetUpRuntimeOptions(options);
104 QuickCompilerCallbacks* new_callbacks =
105 new QuickCompilerCallbacks(CompilerCallbacks::CallbackMode::kCompileBootImage);
106 new_callbacks->SetVerificationResults(verification_results_.get());
107 callbacks_.reset(new_callbacks);
108 options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
109 }
110
GetImageClasses()111 std::unique_ptr<HashSet<std::string>> GetImageClasses() override {
112 return std::make_unique<HashSet<std::string>>(image_classes_);
113 }
114
FindCopiedMethod(ArtMethod * origin,ObjPtr<mirror::Class> klass)115 ArtMethod* FindCopiedMethod(ArtMethod* origin, ObjPtr<mirror::Class> klass)
116 REQUIRES_SHARED(Locks::mutator_lock_) {
117 PointerSize pointer_size = class_linker_->GetImagePointerSize();
118 for (ArtMethod& m : klass->GetCopiedMethods(pointer_size)) {
119 if (strcmp(origin->GetName(), m.GetName()) == 0 &&
120 origin->GetSignature() == m.GetSignature()) {
121 return &m;
122 }
123 }
124 return nullptr;
125 }
126
127 private:
128 void DoCompile(ImageHeader::StorageMode storage_mode, /*out*/ CompilationHelper& out_helper);
129
130 HashSet<std::string> image_classes_;
131
132 // By default we compile with "speed-profile" and an empty profile. This compiles only JNI stubs.
133 CompilerFilter::Filter compiler_filter_ = CompilerFilter::kSpeedProfile;
134 };
135
~CompilationHelper()136 inline CompilationHelper::~CompilationHelper() {
137 for (ScratchFile& image_file : image_files) {
138 image_file.Unlink();
139 }
140 for (ScratchFile& oat_file : oat_files) {
141 oat_file.Unlink();
142 }
143 for (ScratchFile& vdex_file : vdex_files) {
144 vdex_file.Unlink();
145 }
146 const int rmdir_result = rmdir(image_dir.c_str());
147 CHECK_EQ(0, rmdir_result);
148 }
149
GetImageObjectSectionSizes()150 inline std::vector<size_t> CompilationHelper::GetImageObjectSectionSizes() {
151 std::vector<size_t> ret;
152 for (ScratchFile& image_file : image_files) {
153 std::unique_ptr<File> file(OS::OpenFileForReading(image_file.GetFilename().c_str()));
154 CHECK(file.get() != nullptr);
155 ImageHeader image_header;
156 CHECK_EQ(file->ReadFully(&image_header, sizeof(image_header)), true);
157 CHECK(image_header.IsValid());
158 ret.push_back(image_header.GetObjectsSection().Size());
159 }
160 return ret;
161 }
162
DoCompile(ImageHeader::StorageMode storage_mode,CompilationHelper & out_helper)163 inline void ImageTest::DoCompile(ImageHeader::StorageMode storage_mode,
164 /*out*/ CompilationHelper& out_helper) {
165 CompilerDriver* driver = compiler_driver_.get();
166 Runtime::Current()->AppendToBootClassPath(
167 out_helper.extra_dex, out_helper.extra_dex, out_helper.extra_dex_files);
168 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
169 std::vector<const DexFile*> class_path = class_linker->GetBootClassPath();
170
171 // Enable write for dex2dex.
172 for (const DexFile* dex_file : class_path) {
173 out_helper.dex_file_locations.push_back(dex_file->GetLocation());
174 if (dex_file->IsReadOnly()) {
175 dex_file->EnableWrite();
176 }
177 }
178 {
179 // Create a generic tmp file, to be the base of the .art and .oat temporary files.
180 ScratchFile location;
181 std::vector<std::string> image_locations =
182 gc::space::ImageSpace::ExpandMultiImageLocations(
183 ArrayRef<const std::string>(out_helper.dex_file_locations),
184 location.GetFilename() + ".art");
185 for (size_t i = 0u; i != class_path.size(); ++i) {
186 out_helper.image_locations.push_back(ScratchFile(image_locations[i]));
187 }
188 }
189 std::vector<std::string> image_filenames;
190 for (ScratchFile& file : out_helper.image_locations) {
191 std::string image_filename(GetSystemImageFilename(file.GetFilename().c_str(), kRuntimeISA));
192 image_filenames.push_back(image_filename);
193 size_t pos = image_filename.rfind('/');
194 CHECK_NE(pos, std::string::npos) << image_filename;
195 if (out_helper.image_dir.empty()) {
196 out_helper.image_dir = image_filename.substr(0, pos);
197 int mkdir_result = mkdir(out_helper.image_dir.c_str(), 0700);
198 CHECK_EQ(0, mkdir_result) << out_helper.image_dir;
199 }
200 out_helper.image_files.push_back(ScratchFile(OS::CreateEmptyFile(image_filename.c_str())));
201 }
202
203 std::vector<std::string> oat_filenames;
204 std::vector<std::string> vdex_filenames;
205 for (const std::string& image_filename : image_filenames) {
206 std::string oat_filename = ReplaceFileExtension(image_filename, "oat");
207 out_helper.oat_files.push_back(ScratchFile(OS::CreateEmptyFile(oat_filename.c_str())));
208 oat_filenames.push_back(oat_filename);
209 std::string vdex_filename = ReplaceFileExtension(image_filename, "vdex");
210 out_helper.vdex_files.push_back(ScratchFile(OS::CreateEmptyFile(vdex_filename.c_str())));
211 vdex_filenames.push_back(vdex_filename);
212 }
213
214 HashMap<const DexFile*, size_t> dex_file_to_oat_index_map;
215 size_t image_idx = 0;
216 for (const DexFile* dex_file : class_path) {
217 dex_file_to_oat_index_map.insert(std::make_pair(dex_file, image_idx));
218 ++image_idx;
219 }
220 std::unique_ptr<ImageWriter> writer(new ImageWriter(*compiler_options_,
221 kRequestedImageBase,
222 storage_mode,
223 oat_filenames,
224 dex_file_to_oat_index_map,
225 /*class_loader=*/ nullptr,
226 /*dirty_image_objects=*/ nullptr));
227 {
228 {
229 jobject class_loader = nullptr;
230 TimingLogger timings("ImageTest::WriteRead", false, false);
231 CompileAll(class_loader, class_path, &timings);
232
233 TimingLogger::ScopedTiming t("WriteElf", &timings);
234 SafeMap<std::string, std::string> key_value_store;
235 key_value_store.Put(OatHeader::kBootClassPathKey,
236 android::base::Join(out_helper.dex_file_locations, ':'));
237 key_value_store.Put(OatHeader::kApexVersionsKey, Runtime::Current()->GetApexVersions());
238 key_value_store.Put(
239 OatHeader::kConcurrentCopying,
240 compiler_options_->EmitReadBarrier() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
241
242 std::vector<std::unique_ptr<ElfWriter>> elf_writers;
243 std::vector<std::unique_ptr<OatWriter>> oat_writers;
244 for (ScratchFile& oat_file : out_helper.oat_files) {
245 elf_writers.emplace_back(CreateElfWriterQuick(*compiler_options_, oat_file.GetFile()));
246 elf_writers.back()->Start();
247 oat_writers.emplace_back(new OatWriter(*compiler_options_,
248 verification_results_.get(),
249 &timings,
250 /*profile_compilation_info*/nullptr));
251 }
252
253 std::vector<OutputStream*> rodata;
254 std::vector<MemMap> opened_dex_files_maps;
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 oat_writers[i]->AddRawDexFileSource(dex_file->GetContainer(),
261 dex_file->Begin(),
262 dex_file->GetLocation().c_str(),
263 dex_file->GetLocationChecksum());
264
265 std::vector<MemMap> cur_opened_dex_files_maps;
266 std::vector<std::unique_ptr<const DexFile>> cur_opened_dex_files;
267 bool dex_files_ok = oat_writers[i]->WriteAndOpenDexFiles(
268 out_helper.vdex_files[i].GetFile(),
269 /* verify */ false, // Dex files may be dex-to-dex-ed, don't verify.
270 /* update_input_vdex */ false,
271 /* copy_dex_files */ CopyOption::kOnlyIfCompressed,
272 &cur_opened_dex_files_maps,
273 &cur_opened_dex_files);
274 ASSERT_TRUE(dex_files_ok);
275
276 if (!cur_opened_dex_files_maps.empty()) {
277 for (MemMap& cur_map : cur_opened_dex_files_maps) {
278 opened_dex_files_maps.push_back(std::move(cur_map));
279 }
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(&timings);
289 ASSERT_TRUE(image_space_ok);
290
291 DCHECK_EQ(out_helper.vdex_files.size(), out_helper.oat_files.size());
292 for (size_t i = 0, size = out_helper.oat_files.size(); i != size; ++i) {
293 MultiOatRelativePatcher patcher(compiler_options_->GetInstructionSet(),
294 compiler_options_->GetInstructionSetFeatures(),
295 driver->GetCompiledMethodStorage());
296 OatWriter* const oat_writer = oat_writers[i].get();
297 ElfWriter* const elf_writer = elf_writers[i].get();
298 std::vector<const DexFile*> cur_dex_files(1u, class_path[i]);
299 bool start_rodata_ok = oat_writer->StartRoData(cur_dex_files,
300 rodata[i],
301 (i == 0u) ? &key_value_store : nullptr);
302 ASSERT_TRUE(start_rodata_ok);
303 oat_writer->Initialize(driver, writer.get(), cur_dex_files);
304
305 oat_writer->FinishVdexFile(out_helper.vdex_files[i].GetFile(), /*verifier_deps=*/ nullptr);
306
307 oat_writer->PrepareLayout(&patcher);
308 elf_writer->PrepareDynamicSection(oat_writer->GetOatHeader().GetExecutableOffset(),
309 oat_writer->GetCodeSize(),
310 oat_writer->GetDataImgRelRoSize(),
311 oat_writer->GetDataImgRelRoAppImageOffset(),
312 oat_writer->GetBssSize(),
313 oat_writer->GetBssMethodsOffset(),
314 oat_writer->GetBssRootsOffset(),
315 oat_writer->GetVdexSize());
316
317 writer->UpdateOatFileLayout(i,
318 elf_writer->GetLoadedSize(),
319 oat_writer->GetOatDataOffset(),
320 oat_writer->GetOatSize());
321
322 bool rodata_ok = oat_writer->WriteRodata(rodata[i]);
323 ASSERT_TRUE(rodata_ok);
324 elf_writer->EndRoData(rodata[i]);
325
326 OutputStream* text = elf_writer->StartText();
327 bool text_ok = oat_writer->WriteCode(text);
328 ASSERT_TRUE(text_ok);
329 elf_writer->EndText(text);
330
331 if (oat_writer->GetDataImgRelRoSize() != 0u) {
332 OutputStream* data_img_rel_ro = elf_writer->StartDataImgRelRo();
333 bool data_img_rel_ro_ok = oat_writer->WriteDataImgRelRo(data_img_rel_ro);
334 ASSERT_TRUE(data_img_rel_ro_ok);
335 elf_writer->EndDataImgRelRo(data_img_rel_ro);
336 }
337
338 bool header_ok = oat_writer->WriteHeader(elf_writer->GetStream());
339 ASSERT_TRUE(header_ok);
340
341 writer->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
342
343 elf_writer->WriteDynamicSection();
344 elf_writer->WriteDebugInfo(oat_writer->GetDebugInfo());
345
346 bool success = elf_writer->End();
347 ASSERT_TRUE(success);
348 }
349 }
350
351 bool success_image = writer->Write(File::kInvalidFd,
352 image_filenames,
353 image_filenames.size());
354 ASSERT_TRUE(success_image);
355 }
356 }
357
Compile(ImageHeader::StorageMode storage_mode,uint32_t max_image_block_size,CompilationHelper & helper,const std::string & extra_dex,const std::initializer_list<std::string> & image_classes,const std::initializer_list<std::string> & image_classes_failing_aot_clinit,const std::initializer_list<std::string> & image_classes_failing_resolution)358 inline void ImageTest::Compile(
359 ImageHeader::StorageMode storage_mode,
360 uint32_t max_image_block_size,
361 CompilationHelper& helper,
362 const std::string& extra_dex,
363 const std::initializer_list<std::string>& image_classes,
364 const std::initializer_list<std::string>& image_classes_failing_aot_clinit,
365 const std::initializer_list<std::string>& image_classes_failing_resolution) {
366 for (const std::string& image_class : image_classes_failing_aot_clinit) {
367 ASSERT_TRUE(ContainsElement(image_classes, image_class));
368 }
369 for (const std::string& image_class : image_classes) {
370 image_classes_.insert(image_class);
371 }
372 number_of_threads_ = kIsTargetBuild ? 2U : 16U;
373 CreateCompilerDriver();
374 // Set inline filter values.
375 compiler_options_->SetInlineMaxCodeUnits(CompilerOptions::kDefaultInlineMaxCodeUnits);
376 compiler_options_->SetMaxImageBlockSize(max_image_block_size);
377 image_classes_.clear();
378 if (!extra_dex.empty()) {
379 helper.extra_dex = extra_dex;
380 helper.extra_dex_files = OpenTestDexFiles(extra_dex.c_str());
381 }
382 DoCompile(storage_mode, helper);
383 if (image_classes.begin() != image_classes.end()) {
384 // Make sure all explicitly specified classes got initialized.
385 ScopedObjectAccess soa(Thread::Current());
386 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
387 for (const std::string& image_class : image_classes) {
388 ObjPtr<mirror::Class> klass =
389 class_linker->LookupClass(Thread::Current(), image_class.c_str(), nullptr);
390 if (ContainsElement(image_classes_failing_resolution, image_class)) {
391 EXPECT_TRUE(klass == nullptr || klass->IsErroneousUnresolved());
392 } else if (ContainsElement(image_classes_failing_aot_clinit, image_class)) {
393 ASSERT_TRUE(klass != nullptr) << image_class;
394 EXPECT_FALSE(klass->IsInitialized());
395 } else {
396 ASSERT_TRUE(klass != nullptr) << image_class;
397 EXPECT_TRUE(klass->IsInitialized());
398 }
399 }
400 }
401 }
402
403 } // namespace linker
404 } // namespace art
405
406 #endif // ART_DEX2OAT_LINKER_IMAGE_TEST_H_
407