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 #include "android-base/stringprintf.h"
18 
19 #include "arch/instruction_set_features.h"
20 #include "art_method-inl.h"
21 #include "base/enums.h"
22 #include "base/file_utils.h"
23 #include "base/stl_util.h"
24 #include "base/unix_file/fd_file.h"
25 #include "class_linker.h"
26 #include "common_compiler_driver_test.h"
27 #include "compiled_method-inl.h"
28 #include "compiler.h"
29 #include "debug/method_debug_info.h"
30 #include "dex/class_accessor-inl.h"
31 #include "dex/dex_file_loader.h"
32 #include "dex/quick_compiler_callbacks.h"
33 #include "dex/test_dex_file_builder.h"
34 #include "dex/verification_results.h"
35 #include "driver/compiler_driver.h"
36 #include "driver/compiler_options.h"
37 #include "entrypoints/quick/quick_entrypoints.h"
38 #include "linker/elf_writer.h"
39 #include "linker/elf_writer_quick.h"
40 #include "linker/multi_oat_relative_patcher.h"
41 #include "mirror/class-inl.h"
42 #include "mirror/object-inl.h"
43 #include "mirror/object_array-inl.h"
44 #include "oat.h"
45 #include "oat_file-inl.h"
46 #include "oat_writer.h"
47 #include "profile/profile_compilation_info.h"
48 #include "scoped_thread_state_change-inl.h"
49 #include "stream/buffered_output_stream.h"
50 #include "stream/file_output_stream.h"
51 #include "stream/vector_output_stream.h"
52 #include "vdex_file.h"
53 
54 namespace art {
55 namespace linker {
56 
57 class OatTest : public CommonCompilerDriverTest {
58  protected:
59   static const bool kCompile = false;  // DISABLED_ due to the time to compile libcore
60 
CheckMethod(ArtMethod * method,const OatFile::OatMethod & oat_method,const DexFile & dex_file)61   void CheckMethod(ArtMethod* method,
62                    const OatFile::OatMethod& oat_method,
63                    const DexFile& dex_file)
64       REQUIRES_SHARED(Locks::mutator_lock_) {
65     const CompiledMethod* compiled_method =
66         compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
67                                                             method->GetDexMethodIndex()));
68 
69     if (compiled_method == nullptr) {
70       EXPECT_TRUE(oat_method.GetQuickCode() == nullptr) << method->PrettyMethod() << " "
71                                                         << oat_method.GetQuickCode();
72       EXPECT_EQ(oat_method.GetFrameSizeInBytes(), 0U);
73       EXPECT_EQ(oat_method.GetCoreSpillMask(), 0U);
74       EXPECT_EQ(oat_method.GetFpSpillMask(), 0U);
75     } else {
76       const void* quick_oat_code = oat_method.GetQuickCode();
77       EXPECT_TRUE(quick_oat_code != nullptr) << method->PrettyMethod();
78       uintptr_t oat_code_aligned = RoundDown(reinterpret_cast<uintptr_t>(quick_oat_code), 2);
79       quick_oat_code = reinterpret_cast<const void*>(oat_code_aligned);
80       ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
81       EXPECT_FALSE(quick_code.empty());
82       size_t code_size = quick_code.size() * sizeof(quick_code[0]);
83       EXPECT_EQ(0, memcmp(quick_oat_code, &quick_code[0], code_size))
84           << method->PrettyMethod() << " " << code_size;
85       CHECK_EQ(0, memcmp(quick_oat_code, &quick_code[0], code_size));
86     }
87   }
88 
SetupCompiler(const std::vector<std::string> & compiler_options)89   void SetupCompiler(const std::vector<std::string>& compiler_options) {
90     std::string error_msg;
91     if (!compiler_options_->ParseCompilerOptions(compiler_options,
92                                                  /*ignore_unrecognized=*/ false,
93                                                  &error_msg)) {
94       LOG(FATAL) << error_msg;
95       UNREACHABLE();
96     }
97     callbacks_.reset(new QuickCompilerCallbacks(CompilerCallbacks::CallbackMode::kCompileApp));
98     callbacks_->SetVerificationResults(verification_results_.get());
99     Runtime::Current()->SetCompilerCallbacks(callbacks_.get());
100   }
101 
WriteElf(File * vdex_file,File * oat_file,const std::vector<const DexFile * > & dex_files,SafeMap<std::string,std::string> & key_value_store,bool verify)102   bool WriteElf(File* vdex_file,
103                 File* oat_file,
104                 const std::vector<const DexFile*>& dex_files,
105                 SafeMap<std::string, std::string>& key_value_store,
106                 bool verify) {
107     TimingLogger timings("WriteElf", false, false);
108     ClearBootImageOption();
109     OatWriter oat_writer(*compiler_options_,
110                          &timings,
111                          /*profile_compilation_info*/nullptr,
112                          CompactDexLevel::kCompactDexLevelNone);
113     for (const DexFile* dex_file : dex_files) {
114       ArrayRef<const uint8_t> raw_dex_file(
115           reinterpret_cast<const uint8_t*>(&dex_file->GetHeader()),
116           dex_file->GetHeader().file_size_);
117       if (!oat_writer.AddRawDexFileSource(raw_dex_file,
118                                           dex_file->GetLocation().c_str(),
119                                           dex_file->GetLocationChecksum())) {
120         return false;
121       }
122     }
123     return DoWriteElf(
124         vdex_file, oat_file, oat_writer, key_value_store, verify, CopyOption::kOnlyIfCompressed);
125   }
126 
WriteElf(File * vdex_file,File * oat_file,const std::vector<const char * > & dex_filenames,SafeMap<std::string,std::string> & key_value_store,bool verify,CopyOption copy,ProfileCompilationInfo * profile_compilation_info)127   bool WriteElf(File* vdex_file,
128                 File* oat_file,
129                 const std::vector<const char*>& dex_filenames,
130                 SafeMap<std::string, std::string>& key_value_store,
131                 bool verify,
132                 CopyOption copy,
133                 ProfileCompilationInfo* profile_compilation_info) {
134     TimingLogger timings("WriteElf", false, false);
135     ClearBootImageOption();
136     OatWriter oat_writer(*compiler_options_,
137                          &timings,
138                          profile_compilation_info,
139                          CompactDexLevel::kCompactDexLevelNone);
140     for (const char* dex_filename : dex_filenames) {
141       if (!oat_writer.AddDexFileSource(dex_filename, dex_filename)) {
142         return false;
143       }
144     }
145     return DoWriteElf(vdex_file, oat_file, oat_writer, key_value_store, verify, copy);
146   }
147 
WriteElf(File * vdex_file,File * oat_file,File && dex_file_fd,const char * location,SafeMap<std::string,std::string> & key_value_store,bool verify,CopyOption copy,ProfileCompilationInfo * profile_compilation_info=nullptr)148   bool WriteElf(File* vdex_file,
149                 File* oat_file,
150                 File&& dex_file_fd,
151                 const char* location,
152                 SafeMap<std::string, std::string>& key_value_store,
153                 bool verify,
154                 CopyOption copy,
155                 ProfileCompilationInfo* profile_compilation_info = nullptr) {
156     TimingLogger timings("WriteElf", false, false);
157     ClearBootImageOption();
158     OatWriter oat_writer(*compiler_options_,
159                          &timings,
160                          profile_compilation_info,
161                          CompactDexLevel::kCompactDexLevelNone);
162     if (!oat_writer.AddDexFileSource(std::move(dex_file_fd), location)) {
163       return false;
164     }
165     return DoWriteElf(vdex_file, oat_file, oat_writer, key_value_store, verify, copy);
166   }
167 
DoWriteElf(File * vdex_file,File * oat_file,OatWriter & oat_writer,SafeMap<std::string,std::string> & key_value_store,bool verify,CopyOption copy)168   bool DoWriteElf(File* vdex_file,
169                   File* oat_file,
170                   OatWriter& oat_writer,
171                   SafeMap<std::string, std::string>& key_value_store,
172                   bool verify,
173                   CopyOption copy) {
174     std::unique_ptr<ElfWriter> elf_writer = CreateElfWriterQuick(
175         compiler_driver_->GetCompilerOptions(),
176         oat_file);
177     elf_writer->Start();
178     OutputStream* oat_rodata = elf_writer->StartRoData();
179     std::vector<MemMap> opened_dex_files_maps;
180     std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
181     if (!oat_writer.WriteAndOpenDexFiles(
182         vdex_file,
183         verify,
184         /*update_input_vdex=*/ false,
185         copy,
186         &opened_dex_files_maps,
187         &opened_dex_files)) {
188       return false;
189     }
190 
191     Runtime* runtime = Runtime::Current();
192     ClassLinker* const class_linker = runtime->GetClassLinker();
193     std::vector<const DexFile*> dex_files;
194     for (const std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
195       dex_files.push_back(dex_file.get());
196       ScopedObjectAccess soa(Thread::Current());
197       class_linker->RegisterDexFile(*dex_file, nullptr);
198     }
199     MultiOatRelativePatcher patcher(compiler_options_->GetInstructionSet(),
200                                     compiler_options_->GetInstructionSetFeatures(),
201                                     compiler_driver_->GetCompiledMethodStorage());
202     if (!oat_writer.StartRoData(dex_files, oat_rodata, &key_value_store)) {
203       return false;
204     }
205     oat_writer.Initialize(compiler_driver_.get(), /*image_writer=*/ nullptr, dex_files);
206     oat_writer.PrepareLayout(&patcher);
207     elf_writer->PrepareDynamicSection(oat_writer.GetOatHeader().GetExecutableOffset(),
208                                       oat_writer.GetCodeSize(),
209                                       oat_writer.GetDataBimgRelRoSize(),
210                                       oat_writer.GetBssSize(),
211                                       oat_writer.GetBssMethodsOffset(),
212                                       oat_writer.GetBssRootsOffset(),
213                                       oat_writer.GetVdexSize());
214 
215     if (!oat_writer.FinishVdexFile(vdex_file, /*verifier_deps=*/ nullptr)) {
216       return false;
217     }
218 
219     if (!oat_writer.WriteRodata(oat_rodata)) {
220       return false;
221     }
222     elf_writer->EndRoData(oat_rodata);
223 
224     OutputStream* text = elf_writer->StartText();
225     if (!oat_writer.WriteCode(text)) {
226       return false;
227     }
228     elf_writer->EndText(text);
229 
230     if (oat_writer.GetDataBimgRelRoSize() != 0u) {
231       OutputStream* data_bimg_rel_ro = elf_writer->StartDataBimgRelRo();
232       if (!oat_writer.WriteDataBimgRelRo(data_bimg_rel_ro)) {
233         return false;
234       }
235       elf_writer->EndDataBimgRelRo(data_bimg_rel_ro);
236     }
237 
238     if (!oat_writer.WriteHeader(elf_writer->GetStream())) {
239       return false;
240     }
241 
242     elf_writer->WriteDynamicSection();
243     elf_writer->WriteDebugInfo(oat_writer.GetDebugInfo());
244 
245     if (!elf_writer->End()) {
246       return false;
247     }
248 
249     for (MemMap& map : opened_dex_files_maps) {
250       opened_dex_files_maps_.emplace_back(std::move(map));
251     }
252     for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
253       opened_dex_files_.emplace_back(dex_file.release());
254     }
255     return true;
256   }
257 
CheckOatWriteResult(ScratchFile & oat_file,ScratchFile & vdex_file,std::vector<std::unique_ptr<const DexFile>> & input_dexfiles,const unsigned int expected_oat_dexfile_count,bool low_4gb)258   void CheckOatWriteResult(ScratchFile& oat_file,
259                            ScratchFile& vdex_file,
260                            std::vector<std::unique_ptr<const DexFile>>& input_dexfiles,
261                            const unsigned int expected_oat_dexfile_count,
262                            bool low_4gb) {
263     ASSERT_EQ(expected_oat_dexfile_count, input_dexfiles.size());
264 
265     std::string error_msg;
266     std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(/*zip_fd=*/ -1,
267                                                            oat_file.GetFilename(),
268                                                            oat_file.GetFilename(),
269                                                            /*executable=*/ false,
270                                                            low_4gb,
271                                                            &error_msg));
272     ASSERT_TRUE(opened_oat_file != nullptr) << error_msg;
273     ASSERT_EQ(expected_oat_dexfile_count, opened_oat_file->GetOatDexFiles().size());
274 
275     if (low_4gb) {
276       uintptr_t begin = reinterpret_cast<uintptr_t>(opened_oat_file->Begin());
277       EXPECT_EQ(begin, static_cast<uint32_t>(begin));
278     }
279 
280     for (uint32_t i = 0; i <  input_dexfiles.size(); i++) {
281       const std::unique_ptr<const DexFile>& dex_file_data = input_dexfiles[i];
282       std::unique_ptr<const DexFile> opened_dex_file =
283           opened_oat_file->GetOatDexFiles()[i]->OpenDexFile(&error_msg);
284 
285       ASSERT_EQ(opened_oat_file->GetOatDexFiles()[i]->GetDexFileLocationChecksum(),
286                 dex_file_data->GetHeader().checksum_);
287 
288       ASSERT_EQ(dex_file_data->GetHeader().file_size_, opened_dex_file->GetHeader().file_size_);
289       ASSERT_EQ(0, memcmp(&dex_file_data->GetHeader(),
290                           &opened_dex_file->GetHeader(),
291                           dex_file_data->GetHeader().file_size_));
292       ASSERT_EQ(dex_file_data->GetLocation(), opened_dex_file->GetLocation());
293     }
294 
295     int64_t actual_vdex_size = vdex_file.GetFile()->GetLength();
296     ASSERT_GE(actual_vdex_size, 0);
297     ASSERT_EQ(dchecked_integral_cast<uint64_t>(actual_vdex_size),
298               opened_oat_file->GetVdexFile()->GetComputedFileSize());
299   }
300 
301   void TestDexFileInput(bool verify, bool low_4gb, bool use_profile);
302   void TestZipFileInput(bool verify, CopyOption copy);
303   void TestZipFileInputWithEmptyDex();
304 
305   std::unique_ptr<QuickCompilerCallbacks> callbacks_;
306 
307   std::vector<MemMap> opened_dex_files_maps_;
308   std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
309 };
310 
311 class ZipBuilder {
312  public:
ZipBuilder(File * zip_file)313   explicit ZipBuilder(File* zip_file) : zip_file_(zip_file) { }
314 
AddFile(const char * location,const void * data,size_t size)315   bool AddFile(const char* location, const void* data, size_t size) {
316     off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
317     if (offset == static_cast<off_t>(-1)) {
318       return false;
319     }
320 
321     ZipFileHeader file_header;
322     file_header.crc32 = crc32(0u, reinterpret_cast<const Bytef*>(data), size);
323     file_header.compressed_size = size;
324     file_header.uncompressed_size = size;
325     file_header.filename_length = strlen(location);
326 
327     if (!zip_file_->WriteFully(&file_header, sizeof(file_header)) ||
328         !zip_file_->WriteFully(location, file_header.filename_length) ||
329         !zip_file_->WriteFully(data, size)) {
330       return false;
331     }
332 
333     CentralDirectoryFileHeader cdfh;
334     cdfh.crc32 = file_header.crc32;
335     cdfh.compressed_size = size;
336     cdfh.uncompressed_size = size;
337     cdfh.filename_length = file_header.filename_length;
338     cdfh.relative_offset_of_local_file_header = offset;
339     file_data_.push_back(FileData { cdfh, location });
340     return true;
341   }
342 
Finish()343   bool Finish() {
344     off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
345     if (offset == static_cast<off_t>(-1)) {
346       return false;
347     }
348 
349     size_t central_directory_size = 0u;
350     for (const FileData& file_data : file_data_) {
351       if (!zip_file_->WriteFully(&file_data.cdfh, sizeof(file_data.cdfh)) ||
352           !zip_file_->WriteFully(file_data.location, file_data.cdfh.filename_length)) {
353         return false;
354       }
355       central_directory_size += sizeof(file_data.cdfh) + file_data.cdfh.filename_length;
356     }
357     EndOfCentralDirectoryRecord eocd_record;
358     eocd_record.number_of_central_directory_records_on_this_disk = file_data_.size();
359     eocd_record.total_number_of_central_directory_records = file_data_.size();
360     eocd_record.size_of_central_directory = central_directory_size;
361     eocd_record.offset_of_start_of_central_directory = offset;
362     return
363         zip_file_->WriteFully(&eocd_record, sizeof(eocd_record)) &&
364         zip_file_->Flush() == 0;
365   }
366 
367  private:
368   struct PACKED(1) ZipFileHeader {
369     uint32_t signature = 0x04034b50;
370     uint16_t version_needed_to_extract = 10;
371     uint16_t general_purpose_bit_flag = 0;
372     uint16_t compression_method = 0;            // 0 = store only.
373     uint16_t file_last_modification_time = 0u;
374     uint16_t file_last_modification_date = 0u;
375     uint32_t crc32;
376     uint32_t compressed_size;
377     uint32_t uncompressed_size;
378     uint16_t filename_length;
379     uint16_t extra_field_length = 0u;           // No extra fields.
380   };
381 
382   struct PACKED(1) CentralDirectoryFileHeader {
383     uint32_t signature = 0x02014b50;
384     uint16_t version_made_by = 10;
385     uint16_t version_needed_to_extract = 10;
386     uint16_t general_purpose_bit_flag = 0;
387     uint16_t compression_method = 0;            // 0 = store only.
388     uint16_t file_last_modification_time = 0u;
389     uint16_t file_last_modification_date = 0u;
390     uint32_t crc32;
391     uint32_t compressed_size;
392     uint32_t uncompressed_size;
393     uint16_t filename_length;
394     uint16_t extra_field_length = 0u;           // No extra fields.
395     uint16_t file_comment_length = 0u;          // No file comment.
396     uint16_t disk_number_where_file_starts = 0u;
397     uint16_t internal_file_attributes = 0u;
398     uint32_t external_file_attributes = 0u;
399     uint32_t relative_offset_of_local_file_header;
400   };
401 
402   struct PACKED(1) EndOfCentralDirectoryRecord {
403     uint32_t signature = 0x06054b50;
404     uint16_t number_of_this_disk = 0u;
405     uint16_t disk_where_central_directory_starts = 0u;
406     uint16_t number_of_central_directory_records_on_this_disk;
407     uint16_t total_number_of_central_directory_records;
408     uint32_t size_of_central_directory;
409     uint32_t offset_of_start_of_central_directory;
410     uint16_t comment_length = 0u;               // No file comment.
411   };
412 
413   struct FileData {
414     CentralDirectoryFileHeader cdfh;
415     const char* location;
416   };
417 
418   File* zip_file_;
419   std::vector<FileData> file_data_;
420 };
421 
TEST_F(OatTest,WriteRead)422 TEST_F(OatTest, WriteRead) {
423   TimingLogger timings("OatTest::WriteRead", false, false);
424   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
425 
426   std::string error_msg;
427   SetupCompiler(std::vector<std::string>());
428 
429   jobject class_loader = nullptr;
430   if (kCompile) {
431     TimingLogger timings2("OatTest::WriteRead", false, false);
432     CompileAll(class_loader, class_linker->GetBootClassPath(), &timings2);
433   }
434 
435   ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
436   SafeMap<std::string, std::string> key_value_store;
437   key_value_store.Put(OatHeader::kBootClassPathChecksumsKey, "testkey");
438   bool success = WriteElf(tmp_vdex.GetFile(),
439                           tmp_oat.GetFile(),
440                           class_linker->GetBootClassPath(),
441                           key_value_store,
442                           false);
443   ASSERT_TRUE(success);
444 
445   if (kCompile) {  // OatWriter strips the code, regenerate to compare
446     CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
447   }
448   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
449                                                   tmp_oat.GetFilename(),
450                                                   tmp_oat.GetFilename(),
451                                                   /*executable=*/ false,
452                                                   /*low_4gb=*/ true,
453                                                   &error_msg));
454   ASSERT_TRUE(oat_file.get() != nullptr) << error_msg;
455   const OatHeader& oat_header = oat_file->GetOatHeader();
456   ASSERT_TRUE(oat_header.IsValid());
457   ASSERT_EQ(class_linker->GetBootClassPath().size(), oat_header.GetDexFileCount());  // core
458   ASSERT_TRUE(oat_header.GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey) != nullptr);
459   ASSERT_STREQ("testkey", oat_header.GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey));
460 
461   ASSERT_TRUE(java_lang_dex_file_ != nullptr);
462   const DexFile& dex_file = *java_lang_dex_file_;
463   uint32_t dex_file_checksum = dex_file.GetLocationChecksum();
464   const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
465                                                            &dex_file_checksum);
466   ASSERT_TRUE(oat_dex_file != nullptr);
467   CHECK_EQ(dex_file.GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
468   ScopedObjectAccess soa(Thread::Current());
469   auto pointer_size = class_linker->GetImagePointerSize();
470   for (ClassAccessor accessor : dex_file.GetClasses()) {
471     size_t num_virtual_methods = accessor.NumVirtualMethods();
472 
473     const char* descriptor = accessor.GetDescriptor();
474     ObjPtr<mirror::Class> klass = class_linker->FindClass(soa.Self(),
475                                                           descriptor,
476                                                           ScopedNullHandle<mirror::ClassLoader>());
477 
478     const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(accessor.GetClassDefIndex());
479     CHECK_EQ(ClassStatus::kNotReady, oat_class.GetStatus()) << descriptor;
480     CHECK_EQ(kCompile ? OatClassType::kAllCompiled : OatClassType::kNoneCompiled,
481              oat_class.GetType()) << descriptor;
482 
483     size_t method_index = 0;
484     for (auto& m : klass->GetDirectMethods(pointer_size)) {
485       CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
486       ++method_index;
487     }
488     size_t visited_virtuals = 0;
489     // TODO We should also check copied methods in this test.
490     for (auto& m : klass->GetDeclaredVirtualMethods(pointer_size)) {
491       if (!klass->IsInterface()) {
492         EXPECT_FALSE(m.IsCopied());
493       }
494       CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
495       ++method_index;
496       ++visited_virtuals;
497     }
498     EXPECT_EQ(visited_virtuals, num_virtual_methods);
499   }
500 }
501 
TEST_F(OatTest,OatHeaderSizeCheck)502 TEST_F(OatTest, OatHeaderSizeCheck) {
503   // If this test is failing and you have to update these constants,
504   // it is time to update OatHeader::kOatVersion
505   EXPECT_EQ(64U, sizeof(OatHeader));
506   EXPECT_EQ(4U, sizeof(OatMethodOffsets));
507   EXPECT_EQ(4U, sizeof(OatQuickMethodHeader));
508   EXPECT_EQ(169 * static_cast<size_t>(GetInstructionSetPointerSize(kRuntimeISA)),
509             sizeof(QuickEntryPoints));
510 }
511 
TEST_F(OatTest,OatHeaderIsValid)512 TEST_F(OatTest, OatHeaderIsValid) {
513   InstructionSet insn_set = InstructionSet::kX86;
514   std::string error_msg;
515   std::unique_ptr<const InstructionSetFeatures> insn_features(
516     InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
517   ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
518   std::unique_ptr<OatHeader> oat_header(OatHeader::Create(insn_set,
519                                                           insn_features.get(),
520                                                           0u,
521                                                           nullptr));
522   ASSERT_NE(oat_header.get(), nullptr);
523   ASSERT_TRUE(oat_header->IsValid());
524 
525   char* magic = const_cast<char*>(oat_header->GetMagic());
526   strcpy(magic, "");  // bad magic
527   ASSERT_FALSE(oat_header->IsValid());
528   strcpy(magic, "oat\n000");  // bad version
529   ASSERT_FALSE(oat_header->IsValid());
530 }
531 
TEST_F(OatTest,EmptyTextSection)532 TEST_F(OatTest, EmptyTextSection) {
533   TimingLogger timings("OatTest::EmptyTextSection", false, false);
534 
535   std::vector<std::string> compiler_options;
536   compiler_options.push_back("--compiler-filter=extract");
537   SetupCompiler(compiler_options);
538 
539   jobject class_loader;
540   {
541     ScopedObjectAccess soa(Thread::Current());
542     class_loader = LoadDex("Main");
543   }
544   ASSERT_TRUE(class_loader != nullptr);
545   std::vector<const DexFile*> dex_files = GetDexFiles(class_loader);
546   ASSERT_TRUE(!dex_files.empty());
547 
548   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
549   for (const DexFile* dex_file : dex_files) {
550     ScopedObjectAccess soa(Thread::Current());
551     class_linker->RegisterDexFile(*dex_file, soa.Decode<mirror::ClassLoader>(class_loader));
552   }
553   CompileAll(class_loader, dex_files, &timings);
554 
555   ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
556   SafeMap<std::string, std::string> key_value_store;
557   bool success = WriteElf(tmp_vdex.GetFile(),
558                           tmp_oat.GetFile(),
559                           dex_files,
560                           key_value_store,
561                           /*verify=*/ false);
562   ASSERT_TRUE(success);
563 
564   std::string error_msg;
565   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
566                                                   tmp_oat.GetFilename(),
567                                                   tmp_oat.GetFilename(),
568                                                   /*executable=*/ false,
569                                                   /*low_4gb=*/ false,
570                                                   &error_msg));
571   ASSERT_TRUE(oat_file != nullptr);
572   EXPECT_LT(static_cast<size_t>(oat_file->Size()),
573             static_cast<size_t>(tmp_oat.GetFile()->GetLength()));
574 }
575 
MaybeModifyDexFileToFail(bool verify,std::unique_ptr<const DexFile> & data)576 static void MaybeModifyDexFileToFail(bool verify, std::unique_ptr<const DexFile>& data) {
577   // If in verify mode (= fail the verifier mode), make sure we fail early. We'll fail already
578   // because of the missing map, but that may lead to out of bounds reads.
579   if (verify) {
580     const_cast<DexFile::Header*>(&data->GetHeader())->checksum_++;
581   }
582 }
583 
TestDexFileInput(bool verify,bool low_4gb,bool use_profile)584 void OatTest::TestDexFileInput(bool verify, bool low_4gb, bool use_profile) {
585   TimingLogger timings("OatTest::DexFileInput", false, false);
586 
587   std::vector<const char*> input_filenames;
588   std::vector<std::unique_ptr<const DexFile>> input_dexfiles;
589   std::vector<const ScratchFile*> scratch_files;
590 
591   ScratchFile dex_file1;
592   TestDexFileBuilder builder1;
593   builder1.AddField("Lsome/TestClass;", "int", "someField");
594   builder1.AddMethod("Lsome/TestClass;", "()I", "foo");
595   std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
596 
597   MaybeModifyDexFileToFail(verify, dex_file1_data);
598 
599   bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
600                                                  dex_file1_data->GetHeader().file_size_);
601   ASSERT_TRUE(success);
602   success = dex_file1.GetFile()->Flush() == 0;
603   ASSERT_TRUE(success);
604   input_filenames.push_back(dex_file1.GetFilename().c_str());
605   input_dexfiles.push_back(std::move(dex_file1_data));
606   scratch_files.push_back(&dex_file1);
607 
608   ScratchFile dex_file2;
609   TestDexFileBuilder builder2;
610   builder2.AddField("Land/AnotherTestClass;", "boolean", "someOtherField");
611   builder2.AddMethod("Land/AnotherTestClass;", "()J", "bar");
612   std::unique_ptr<const DexFile> dex_file2_data = builder2.Build(dex_file2.GetFilename());
613 
614   MaybeModifyDexFileToFail(verify, dex_file2_data);
615 
616   success = dex_file2.GetFile()->WriteFully(&dex_file2_data->GetHeader(),
617                                             dex_file2_data->GetHeader().file_size_);
618   ASSERT_TRUE(success);
619   success = dex_file2.GetFile()->Flush() == 0;
620   ASSERT_TRUE(success);
621   input_filenames.push_back(dex_file2.GetFilename().c_str());
622   input_dexfiles.push_back(std::move(dex_file2_data));
623   scratch_files.push_back(&dex_file2);
624 
625   SafeMap<std::string, std::string> key_value_store;
626   {
627     // Test using the AddDexFileSource() interface with the dex files.
628     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
629     std::unique_ptr<ProfileCompilationInfo>
630         profile_compilation_info(use_profile ? new ProfileCompilationInfo() : nullptr);
631     success = WriteElf(tmp_vdex.GetFile(),
632                        tmp_oat.GetFile(),
633                        input_filenames,
634                        key_value_store,
635                        verify,
636                        CopyOption::kOnlyIfCompressed,
637                        profile_compilation_info.get());
638 
639     // In verify mode, we expect failure.
640     if (verify) {
641       ASSERT_FALSE(success);
642       return;
643     }
644 
645     ASSERT_TRUE(success);
646 
647     CheckOatWriteResult(tmp_oat,
648                         tmp_vdex,
649                         input_dexfiles,
650                         /* oat_dexfile_count */ 2,
651                         low_4gb);
652   }
653 
654   {
655     // Test using the AddDexFileSource() interface with the dexfile1's fd.
656     // Only need one input dexfile.
657     std::vector<std::unique_ptr<const DexFile>> input_dexfiles2;
658     input_dexfiles2.push_back(std::move(input_dexfiles[0]));
659     const ScratchFile* dex_file = scratch_files[0];
660     File dex_file_fd(DupCloexec(dex_file->GetFd()), /*check_usage=*/ false);
661 
662     ASSERT_NE(-1, dex_file_fd.Fd());
663     ASSERT_EQ(0, lseek(dex_file_fd.Fd(), 0, SEEK_SET));
664 
665     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
666     std::unique_ptr<ProfileCompilationInfo>
667         profile_compilation_info(use_profile ? new ProfileCompilationInfo() : nullptr);
668     success = WriteElf(tmp_vdex.GetFile(),
669                        tmp_oat.GetFile(),
670                        std::move(dex_file_fd),
671                        dex_file->GetFilename().c_str(),
672                        key_value_store,
673                        verify,
674                        CopyOption::kOnlyIfCompressed,
675                        profile_compilation_info.get());
676 
677     // In verify mode, we expect failure.
678     if (verify) {
679       ASSERT_FALSE(success);
680       return;
681     }
682 
683     ASSERT_TRUE(success);
684 
685     CheckOatWriteResult(tmp_oat,
686                         tmp_vdex,
687                         input_dexfiles2,
688                         /* oat_dexfile_count */ 1,
689                         low_4gb);
690   }
691 }
692 
TEST_F(OatTest,DexFileInputCheckOutput)693 TEST_F(OatTest, DexFileInputCheckOutput) {
694   TestDexFileInput(/*verify*/false, /*low_4gb*/false, /*use_profile*/false);
695 }
696 
TEST_F(OatTest,DexFileInputCheckOutputLow4GB)697 TEST_F(OatTest, DexFileInputCheckOutputLow4GB) {
698   TestDexFileInput(/*verify*/false, /*low_4gb*/true, /*use_profile*/false);
699 }
700 
TEST_F(OatTest,DexFileInputCheckVerifier)701 TEST_F(OatTest, DexFileInputCheckVerifier) {
702   TestDexFileInput(/*verify*/true, /*low_4gb*/false, /*use_profile*/false);
703 }
704 
TEST_F(OatTest,DexFileFailsVerifierWithLayout)705 TEST_F(OatTest, DexFileFailsVerifierWithLayout) {
706   TestDexFileInput(/*verify*/true, /*low_4gb*/false, /*use_profile*/true);
707 }
708 
TestZipFileInput(bool verify,CopyOption copy)709 void OatTest::TestZipFileInput(bool verify, CopyOption copy) {
710   TimingLogger timings("OatTest::DexFileInput", false, false);
711 
712   ScratchFile zip_file;
713   ZipBuilder zip_builder(zip_file.GetFile());
714 
715   ScratchFile dex_file1;
716   TestDexFileBuilder builder1;
717   builder1.AddField("Lsome/TestClass;", "long", "someField");
718   builder1.AddMethod("Lsome/TestClass;", "()D", "foo");
719   std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
720 
721   MaybeModifyDexFileToFail(verify, dex_file1_data);
722 
723   bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
724                                                  dex_file1_data->GetHeader().file_size_);
725   ASSERT_TRUE(success);
726   success = dex_file1.GetFile()->Flush() == 0;
727   ASSERT_TRUE(success);
728   success = zip_builder.AddFile("classes.dex",
729                                 &dex_file1_data->GetHeader(),
730                                 dex_file1_data->GetHeader().file_size_);
731   ASSERT_TRUE(success);
732 
733   ScratchFile dex_file2;
734   TestDexFileBuilder builder2;
735   builder2.AddField("Land/AnotherTestClass;", "boolean", "someOtherField");
736   builder2.AddMethod("Land/AnotherTestClass;", "()J", "bar");
737   std::unique_ptr<const DexFile> dex_file2_data = builder2.Build(dex_file2.GetFilename());
738 
739   MaybeModifyDexFileToFail(verify, dex_file2_data);
740 
741   success = dex_file2.GetFile()->WriteFully(&dex_file2_data->GetHeader(),
742                                             dex_file2_data->GetHeader().file_size_);
743   ASSERT_TRUE(success);
744   success = dex_file2.GetFile()->Flush() == 0;
745   ASSERT_TRUE(success);
746   success = zip_builder.AddFile("classes2.dex",
747                                 &dex_file2_data->GetHeader(),
748                                 dex_file2_data->GetHeader().file_size_);
749   ASSERT_TRUE(success);
750 
751   success = zip_builder.Finish();
752   ASSERT_TRUE(success) << strerror(errno);
753 
754   SafeMap<std::string, std::string> key_value_store;
755   {
756     // Test using the AddDexFileSource() interface with the zip file.
757     std::vector<const char*> input_filenames = { zip_file.GetFilename().c_str() };
758 
759     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
760     success = WriteElf(tmp_vdex.GetFile(),
761                        tmp_oat.GetFile(),
762                        input_filenames,
763                        key_value_store,
764                        verify,
765                        copy,
766                        /*profile_compilation_info=*/ nullptr);
767 
768     if (verify) {
769       ASSERT_FALSE(success);
770     } else {
771       ASSERT_TRUE(success);
772 
773       std::string error_msg;
774       std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(/*zip_fd=*/ -1,
775                                                              tmp_oat.GetFilename(),
776                                                              tmp_oat.GetFilename(),
777                                                              /*executable=*/ false,
778                                                              /*low_4gb=*/ false,
779                                                              &error_msg));
780       ASSERT_TRUE(opened_oat_file != nullptr) << error_msg;
781       ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
782       std::unique_ptr<const DexFile> opened_dex_file1 =
783           opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
784       std::unique_ptr<const DexFile> opened_dex_file2 =
785           opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
786 
787       ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
788       ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
789                           &opened_dex_file1->GetHeader(),
790                           dex_file1_data->GetHeader().file_size_));
791       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
792                 opened_dex_file1->GetLocation());
793 
794       ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
795       ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
796                           &opened_dex_file2->GetHeader(),
797                           dex_file2_data->GetHeader().file_size_));
798       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
799                 opened_dex_file2->GetLocation());
800     }
801   }
802 
803   {
804     // Test using the AddDexFileSource() interface with the zip file handle.
805     File zip_fd(DupCloexec(zip_file.GetFd()), /*check_usage=*/ false);
806     ASSERT_NE(-1, zip_fd.Fd());
807     ASSERT_EQ(0, lseek(zip_fd.Fd(), 0, SEEK_SET));
808 
809     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
810     success = WriteElf(tmp_vdex.GetFile(),
811                        tmp_oat.GetFile(),
812                        std::move(zip_fd),
813                        zip_file.GetFilename().c_str(),
814                        key_value_store,
815                        verify,
816                        copy);
817     if (verify) {
818       ASSERT_FALSE(success);
819     } else {
820       ASSERT_TRUE(success);
821 
822       std::string error_msg;
823       std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(/*zip_fd=*/ -1,
824                                                              tmp_oat.GetFilename(),
825                                                              tmp_oat.GetFilename(),
826                                                              /*executable=*/ false,
827                                                              /*low_4gb=*/ false,
828                                                              &error_msg));
829       ASSERT_TRUE(opened_oat_file != nullptr) << error_msg;
830       ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
831       std::unique_ptr<const DexFile> opened_dex_file1 =
832           opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
833       std::unique_ptr<const DexFile> opened_dex_file2 =
834           opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
835 
836       ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
837       ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
838                           &opened_dex_file1->GetHeader(),
839                           dex_file1_data->GetHeader().file_size_));
840       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
841                 opened_dex_file1->GetLocation());
842 
843       ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
844       ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
845                           &opened_dex_file2->GetHeader(),
846                           dex_file2_data->GetHeader().file_size_));
847       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
848                 opened_dex_file2->GetLocation());
849     }
850   }
851 }
852 
TEST_F(OatTest,ZipFileInputCheckOutput)853 TEST_F(OatTest, ZipFileInputCheckOutput) {
854   TestZipFileInput(false, CopyOption::kOnlyIfCompressed);
855 }
856 
TEST_F(OatTest,ZipFileInputCheckOutputWithoutCopy)857 TEST_F(OatTest, ZipFileInputCheckOutputWithoutCopy) {
858   TestZipFileInput(false, CopyOption::kNever);
859 }
860 
TEST_F(OatTest,ZipFileInputCheckVerifier)861 TEST_F(OatTest, ZipFileInputCheckVerifier) {
862   TestZipFileInput(true, CopyOption::kOnlyIfCompressed);
863 }
864 
TestZipFileInputWithEmptyDex()865 void OatTest::TestZipFileInputWithEmptyDex() {
866   ScratchFile zip_file;
867   ZipBuilder zip_builder(zip_file.GetFile());
868   bool success = zip_builder.AddFile("classes.dex", nullptr, 0);
869   ASSERT_TRUE(success);
870   success = zip_builder.Finish();
871   ASSERT_TRUE(success) << strerror(errno);
872 
873   SafeMap<std::string, std::string> key_value_store;
874   std::vector<const char*> input_filenames = { zip_file.GetFilename().c_str() };
875   ScratchFile oat_file, vdex_file(oat_file, ".vdex");
876   std::unique_ptr<ProfileCompilationInfo> profile_compilation_info(new ProfileCompilationInfo());
877   success = WriteElf(vdex_file.GetFile(),
878                      oat_file.GetFile(),
879                      input_filenames,
880                      key_value_store,
881                      /*verify=*/ false,
882                      CopyOption::kOnlyIfCompressed,
883                      profile_compilation_info.get());
884   ASSERT_FALSE(success);
885 }
886 
TEST_F(OatTest,ZipFileInputWithEmptyDex)887 TEST_F(OatTest, ZipFileInputWithEmptyDex) {
888   TestZipFileInputWithEmptyDex();
889 }
890 
891 }  // namespace linker
892 }  // namespace art
893