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     const VdexFile::DexSectionHeader &vdex_header =
295         opened_oat_file->GetVdexFile()->GetDexSectionHeader();
296     if (!compiler_driver_->GetCompilerOptions().IsQuickeningCompilationEnabled()) {
297       // If quickening is enabled we will always write the table since there is no special logic
298       // that checks for all methods not being quickened (not worth the complexity).
299       ASSERT_EQ(vdex_header.GetQuickeningInfoSize(), 0u);
300     }
301 
302     int64_t actual_vdex_size = vdex_file.GetFile()->GetLength();
303     ASSERT_GE(actual_vdex_size, 0);
304     ASSERT_EQ(dchecked_integral_cast<uint64_t>(actual_vdex_size),
305               opened_oat_file->GetVdexFile()->GetComputedFileSize());
306   }
307 
308   void TestDexFileInput(bool verify, bool low_4gb, bool use_profile);
309   void TestZipFileInput(bool verify, CopyOption copy);
310   void TestZipFileInputWithEmptyDex();
311 
312   std::unique_ptr<QuickCompilerCallbacks> callbacks_;
313 
314   std::vector<MemMap> opened_dex_files_maps_;
315   std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
316 };
317 
318 class ZipBuilder {
319  public:
ZipBuilder(File * zip_file)320   explicit ZipBuilder(File* zip_file) : zip_file_(zip_file) { }
321 
AddFile(const char * location,const void * data,size_t size)322   bool AddFile(const char* location, const void* data, size_t size) {
323     off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
324     if (offset == static_cast<off_t>(-1)) {
325       return false;
326     }
327 
328     ZipFileHeader file_header;
329     file_header.crc32 = crc32(0u, reinterpret_cast<const Bytef*>(data), size);
330     file_header.compressed_size = size;
331     file_header.uncompressed_size = size;
332     file_header.filename_length = strlen(location);
333 
334     if (!zip_file_->WriteFully(&file_header, sizeof(file_header)) ||
335         !zip_file_->WriteFully(location, file_header.filename_length) ||
336         !zip_file_->WriteFully(data, size)) {
337       return false;
338     }
339 
340     CentralDirectoryFileHeader cdfh;
341     cdfh.crc32 = file_header.crc32;
342     cdfh.compressed_size = size;
343     cdfh.uncompressed_size = size;
344     cdfh.filename_length = file_header.filename_length;
345     cdfh.relative_offset_of_local_file_header = offset;
346     file_data_.push_back(FileData { cdfh, location });
347     return true;
348   }
349 
Finish()350   bool Finish() {
351     off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
352     if (offset == static_cast<off_t>(-1)) {
353       return false;
354     }
355 
356     size_t central_directory_size = 0u;
357     for (const FileData& file_data : file_data_) {
358       if (!zip_file_->WriteFully(&file_data.cdfh, sizeof(file_data.cdfh)) ||
359           !zip_file_->WriteFully(file_data.location, file_data.cdfh.filename_length)) {
360         return false;
361       }
362       central_directory_size += sizeof(file_data.cdfh) + file_data.cdfh.filename_length;
363     }
364     EndOfCentralDirectoryRecord eocd_record;
365     eocd_record.number_of_central_directory_records_on_this_disk = file_data_.size();
366     eocd_record.total_number_of_central_directory_records = file_data_.size();
367     eocd_record.size_of_central_directory = central_directory_size;
368     eocd_record.offset_of_start_of_central_directory = offset;
369     return
370         zip_file_->WriteFully(&eocd_record, sizeof(eocd_record)) &&
371         zip_file_->Flush() == 0;
372   }
373 
374  private:
375   struct PACKED(1) ZipFileHeader {
376     uint32_t signature = 0x04034b50;
377     uint16_t version_needed_to_extract = 10;
378     uint16_t general_purpose_bit_flag = 0;
379     uint16_t compression_method = 0;            // 0 = store only.
380     uint16_t file_last_modification_time = 0u;
381     uint16_t file_last_modification_date = 0u;
382     uint32_t crc32;
383     uint32_t compressed_size;
384     uint32_t uncompressed_size;
385     uint16_t filename_length;
386     uint16_t extra_field_length = 0u;           // No extra fields.
387   };
388 
389   struct PACKED(1) CentralDirectoryFileHeader {
390     uint32_t signature = 0x02014b50;
391     uint16_t version_made_by = 10;
392     uint16_t version_needed_to_extract = 10;
393     uint16_t general_purpose_bit_flag = 0;
394     uint16_t compression_method = 0;            // 0 = store only.
395     uint16_t file_last_modification_time = 0u;
396     uint16_t file_last_modification_date = 0u;
397     uint32_t crc32;
398     uint32_t compressed_size;
399     uint32_t uncompressed_size;
400     uint16_t filename_length;
401     uint16_t extra_field_length = 0u;           // No extra fields.
402     uint16_t file_comment_length = 0u;          // No file comment.
403     uint16_t disk_number_where_file_starts = 0u;
404     uint16_t internal_file_attributes = 0u;
405     uint32_t external_file_attributes = 0u;
406     uint32_t relative_offset_of_local_file_header;
407   };
408 
409   struct PACKED(1) EndOfCentralDirectoryRecord {
410     uint32_t signature = 0x06054b50;
411     uint16_t number_of_this_disk = 0u;
412     uint16_t disk_where_central_directory_starts = 0u;
413     uint16_t number_of_central_directory_records_on_this_disk;
414     uint16_t total_number_of_central_directory_records;
415     uint32_t size_of_central_directory;
416     uint32_t offset_of_start_of_central_directory;
417     uint16_t comment_length = 0u;               // No file comment.
418   };
419 
420   struct FileData {
421     CentralDirectoryFileHeader cdfh;
422     const char* location;
423   };
424 
425   File* zip_file_;
426   std::vector<FileData> file_data_;
427 };
428 
TEST_F(OatTest,WriteRead)429 TEST_F(OatTest, WriteRead) {
430   TimingLogger timings("OatTest::WriteRead", false, false);
431   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
432 
433   std::string error_msg;
434   SetupCompiler(std::vector<std::string>());
435 
436   jobject class_loader = nullptr;
437   if (kCompile) {
438     TimingLogger timings2("OatTest::WriteRead", false, false);
439     CompileAll(class_loader, class_linker->GetBootClassPath(), &timings2);
440   }
441 
442   ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
443   SafeMap<std::string, std::string> key_value_store;
444   key_value_store.Put(OatHeader::kBootClassPathChecksumsKey, "testkey");
445   bool success = WriteElf(tmp_vdex.GetFile(),
446                           tmp_oat.GetFile(),
447                           class_linker->GetBootClassPath(),
448                           key_value_store,
449                           false);
450   ASSERT_TRUE(success);
451 
452   if (kCompile) {  // OatWriter strips the code, regenerate to compare
453     CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
454   }
455   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
456                                                   tmp_oat.GetFilename(),
457                                                   tmp_oat.GetFilename(),
458                                                   /*executable=*/ false,
459                                                   /*low_4gb=*/ true,
460                                                   &error_msg));
461   ASSERT_TRUE(oat_file.get() != nullptr) << error_msg;
462   const OatHeader& oat_header = oat_file->GetOatHeader();
463   ASSERT_TRUE(oat_header.IsValid());
464   ASSERT_EQ(class_linker->GetBootClassPath().size(), oat_header.GetDexFileCount());  // core
465   ASSERT_TRUE(oat_header.GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey) != nullptr);
466   ASSERT_STREQ("testkey", oat_header.GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey));
467 
468   ASSERT_TRUE(java_lang_dex_file_ != nullptr);
469   const DexFile& dex_file = *java_lang_dex_file_;
470   uint32_t dex_file_checksum = dex_file.GetLocationChecksum();
471   const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
472                                                            &dex_file_checksum);
473   ASSERT_TRUE(oat_dex_file != nullptr);
474   CHECK_EQ(dex_file.GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
475   ScopedObjectAccess soa(Thread::Current());
476   auto pointer_size = class_linker->GetImagePointerSize();
477   for (ClassAccessor accessor : dex_file.GetClasses()) {
478     size_t num_virtual_methods = accessor.NumVirtualMethods();
479 
480     const char* descriptor = accessor.GetDescriptor();
481     ObjPtr<mirror::Class> klass = class_linker->FindClass(soa.Self(),
482                                                           descriptor,
483                                                           ScopedNullHandle<mirror::ClassLoader>());
484 
485     const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(accessor.GetClassDefIndex());
486     CHECK_EQ(ClassStatus::kNotReady, oat_class.GetStatus()) << descriptor;
487     CHECK_EQ(kCompile ? OatClassType::kOatClassAllCompiled : OatClassType::kOatClassNoneCompiled,
488              oat_class.GetType()) << descriptor;
489 
490     size_t method_index = 0;
491     for (auto& m : klass->GetDirectMethods(pointer_size)) {
492       CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
493       ++method_index;
494     }
495     size_t visited_virtuals = 0;
496     // TODO We should also check copied methods in this test.
497     for (auto& m : klass->GetDeclaredVirtualMethods(pointer_size)) {
498       if (!klass->IsInterface()) {
499         EXPECT_FALSE(m.IsCopied());
500       }
501       CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
502       ++method_index;
503       ++visited_virtuals;
504     }
505     EXPECT_EQ(visited_virtuals, num_virtual_methods);
506   }
507 }
508 
TEST_F(OatTest,OatHeaderSizeCheck)509 TEST_F(OatTest, OatHeaderSizeCheck) {
510   // If this test is failing and you have to update these constants,
511   // it is time to update OatHeader::kOatVersion
512   EXPECT_EQ(60U, sizeof(OatHeader));
513   EXPECT_EQ(4U, sizeof(OatMethodOffsets));
514   EXPECT_EQ(8U, sizeof(OatQuickMethodHeader));
515   EXPECT_EQ(169 * static_cast<size_t>(GetInstructionSetPointerSize(kRuntimeISA)),
516             sizeof(QuickEntryPoints));
517 }
518 
TEST_F(OatTest,OatHeaderIsValid)519 TEST_F(OatTest, OatHeaderIsValid) {
520   InstructionSet insn_set = InstructionSet::kX86;
521   std::string error_msg;
522   std::unique_ptr<const InstructionSetFeatures> insn_features(
523     InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
524   ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
525   std::unique_ptr<OatHeader> oat_header(OatHeader::Create(insn_set,
526                                                           insn_features.get(),
527                                                           0u,
528                                                           nullptr));
529   ASSERT_NE(oat_header.get(), nullptr);
530   ASSERT_TRUE(oat_header->IsValid());
531 
532   char* magic = const_cast<char*>(oat_header->GetMagic());
533   strcpy(magic, "");  // bad magic
534   ASSERT_FALSE(oat_header->IsValid());
535   strcpy(magic, "oat\n000");  // bad version
536   ASSERT_FALSE(oat_header->IsValid());
537 }
538 
TEST_F(OatTest,EmptyTextSection)539 TEST_F(OatTest, EmptyTextSection) {
540   TimingLogger timings("OatTest::EmptyTextSection", false, false);
541 
542   std::vector<std::string> compiler_options;
543   compiler_options.push_back("--compiler-filter=extract");
544   SetupCompiler(compiler_options);
545 
546   jobject class_loader;
547   {
548     ScopedObjectAccess soa(Thread::Current());
549     class_loader = LoadDex("Main");
550   }
551   ASSERT_TRUE(class_loader != nullptr);
552   std::vector<const DexFile*> dex_files = GetDexFiles(class_loader);
553   ASSERT_TRUE(!dex_files.empty());
554 
555   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
556   for (const DexFile* dex_file : dex_files) {
557     ScopedObjectAccess soa(Thread::Current());
558     class_linker->RegisterDexFile(*dex_file, soa.Decode<mirror::ClassLoader>(class_loader));
559   }
560   CompileAll(class_loader, dex_files, &timings);
561 
562   ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
563   SafeMap<std::string, std::string> key_value_store;
564   bool success = WriteElf(tmp_vdex.GetFile(),
565                           tmp_oat.GetFile(),
566                           dex_files,
567                           key_value_store,
568                           /*verify=*/ false);
569   ASSERT_TRUE(success);
570 
571   std::string error_msg;
572   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
573                                                   tmp_oat.GetFilename(),
574                                                   tmp_oat.GetFilename(),
575                                                   /*executable=*/ false,
576                                                   /*low_4gb=*/ false,
577                                                   &error_msg));
578   ASSERT_TRUE(oat_file != nullptr);
579   EXPECT_LT(static_cast<size_t>(oat_file->Size()),
580             static_cast<size_t>(tmp_oat.GetFile()->GetLength()));
581 }
582 
MaybeModifyDexFileToFail(bool verify,std::unique_ptr<const DexFile> & data)583 static void MaybeModifyDexFileToFail(bool verify, std::unique_ptr<const DexFile>& data) {
584   // If in verify mode (= fail the verifier mode), make sure we fail early. We'll fail already
585   // because of the missing map, but that may lead to out of bounds reads.
586   if (verify) {
587     const_cast<DexFile::Header*>(&data->GetHeader())->checksum_++;
588   }
589 }
590 
TestDexFileInput(bool verify,bool low_4gb,bool use_profile)591 void OatTest::TestDexFileInput(bool verify, bool low_4gb, bool use_profile) {
592   TimingLogger timings("OatTest::DexFileInput", false, false);
593 
594   std::vector<const char*> input_filenames;
595   std::vector<std::unique_ptr<const DexFile>> input_dexfiles;
596   std::vector<const ScratchFile*> scratch_files;
597 
598   ScratchFile dex_file1;
599   TestDexFileBuilder builder1;
600   builder1.AddField("Lsome.TestClass;", "int", "someField");
601   builder1.AddMethod("Lsome.TestClass;", "()I", "foo");
602   std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
603 
604   MaybeModifyDexFileToFail(verify, dex_file1_data);
605 
606   bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
607                                                  dex_file1_data->GetHeader().file_size_);
608   ASSERT_TRUE(success);
609   success = dex_file1.GetFile()->Flush() == 0;
610   ASSERT_TRUE(success);
611   input_filenames.push_back(dex_file1.GetFilename().c_str());
612   input_dexfiles.push_back(std::move(dex_file1_data));
613   scratch_files.push_back(&dex_file1);
614 
615   ScratchFile dex_file2;
616   TestDexFileBuilder builder2;
617   builder2.AddField("Land.AnotherTestClass;", "boolean", "someOtherField");
618   builder2.AddMethod("Land.AnotherTestClass;", "()J", "bar");
619   std::unique_ptr<const DexFile> dex_file2_data = builder2.Build(dex_file2.GetFilename());
620 
621   MaybeModifyDexFileToFail(verify, dex_file2_data);
622 
623   success = dex_file2.GetFile()->WriteFully(&dex_file2_data->GetHeader(),
624                                             dex_file2_data->GetHeader().file_size_);
625   ASSERT_TRUE(success);
626   success = dex_file2.GetFile()->Flush() == 0;
627   ASSERT_TRUE(success);
628   input_filenames.push_back(dex_file2.GetFilename().c_str());
629   input_dexfiles.push_back(std::move(dex_file2_data));
630   scratch_files.push_back(&dex_file2);
631 
632   SafeMap<std::string, std::string> key_value_store;
633   {
634     // Test using the AddDexFileSource() interface with the dex files.
635     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
636     std::unique_ptr<ProfileCompilationInfo>
637         profile_compilation_info(use_profile ? new ProfileCompilationInfo() : nullptr);
638     success = WriteElf(tmp_vdex.GetFile(),
639                        tmp_oat.GetFile(),
640                        input_filenames,
641                        key_value_store,
642                        verify,
643                        CopyOption::kOnlyIfCompressed,
644                        profile_compilation_info.get());
645 
646     // In verify mode, we expect failure.
647     if (verify) {
648       ASSERT_FALSE(success);
649       return;
650     }
651 
652     ASSERT_TRUE(success);
653 
654     CheckOatWriteResult(tmp_oat,
655                         tmp_vdex,
656                         input_dexfiles,
657                         /* oat_dexfile_count */ 2,
658                         low_4gb);
659   }
660 
661   {
662     // Test using the AddDexFileSource() interface with the dexfile1's fd.
663     // Only need one input dexfile.
664     std::vector<std::unique_ptr<const DexFile>> input_dexfiles2;
665     input_dexfiles2.push_back(std::move(input_dexfiles[0]));
666     const ScratchFile* dex_file = scratch_files[0];
667     File dex_file_fd(DupCloexec(dex_file->GetFd()), /*check_usage=*/ false);
668 
669     ASSERT_NE(-1, dex_file_fd.Fd());
670     ASSERT_EQ(0, lseek(dex_file_fd.Fd(), 0, SEEK_SET));
671 
672     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
673     std::unique_ptr<ProfileCompilationInfo>
674         profile_compilation_info(use_profile ? new ProfileCompilationInfo() : nullptr);
675     success = WriteElf(tmp_vdex.GetFile(),
676                        tmp_oat.GetFile(),
677                        std::move(dex_file_fd),
678                        dex_file->GetFilename().c_str(),
679                        key_value_store,
680                        verify,
681                        CopyOption::kOnlyIfCompressed,
682                        profile_compilation_info.get());
683 
684     // In verify mode, we expect failure.
685     if (verify) {
686       ASSERT_FALSE(success);
687       return;
688     }
689 
690     ASSERT_TRUE(success);
691 
692     CheckOatWriteResult(tmp_oat,
693                         tmp_vdex,
694                         input_dexfiles2,
695                         /* oat_dexfile_count */ 1,
696                         low_4gb);
697   }
698 }
699 
TEST_F(OatTest,DexFileInputCheckOutput)700 TEST_F(OatTest, DexFileInputCheckOutput) {
701   TestDexFileInput(/*verify*/false, /*low_4gb*/false, /*use_profile*/false);
702 }
703 
TEST_F(OatTest,DexFileInputCheckOutputLow4GB)704 TEST_F(OatTest, DexFileInputCheckOutputLow4GB) {
705   TestDexFileInput(/*verify*/false, /*low_4gb*/true, /*use_profile*/false);
706 }
707 
TEST_F(OatTest,DexFileInputCheckVerifier)708 TEST_F(OatTest, DexFileInputCheckVerifier) {
709   TestDexFileInput(/*verify*/true, /*low_4gb*/false, /*use_profile*/false);
710 }
711 
TEST_F(OatTest,DexFileFailsVerifierWithLayout)712 TEST_F(OatTest, DexFileFailsVerifierWithLayout) {
713   TestDexFileInput(/*verify*/true, /*low_4gb*/false, /*use_profile*/true);
714 }
715 
TestZipFileInput(bool verify,CopyOption copy)716 void OatTest::TestZipFileInput(bool verify, CopyOption copy) {
717   TimingLogger timings("OatTest::DexFileInput", false, false);
718 
719   ScratchFile zip_file;
720   ZipBuilder zip_builder(zip_file.GetFile());
721 
722   ScratchFile dex_file1;
723   TestDexFileBuilder builder1;
724   builder1.AddField("Lsome.TestClass;", "long", "someField");
725   builder1.AddMethod("Lsome.TestClass;", "()D", "foo");
726   std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
727 
728   MaybeModifyDexFileToFail(verify, dex_file1_data);
729 
730   bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
731                                                  dex_file1_data->GetHeader().file_size_);
732   ASSERT_TRUE(success);
733   success = dex_file1.GetFile()->Flush() == 0;
734   ASSERT_TRUE(success);
735   success = zip_builder.AddFile("classes.dex",
736                                 &dex_file1_data->GetHeader(),
737                                 dex_file1_data->GetHeader().file_size_);
738   ASSERT_TRUE(success);
739 
740   ScratchFile dex_file2;
741   TestDexFileBuilder builder2;
742   builder2.AddField("Land.AnotherTestClass;", "boolean", "someOtherField");
743   builder2.AddMethod("Land.AnotherTestClass;", "()J", "bar");
744   std::unique_ptr<const DexFile> dex_file2_data = builder2.Build(dex_file2.GetFilename());
745 
746   MaybeModifyDexFileToFail(verify, dex_file2_data);
747 
748   success = dex_file2.GetFile()->WriteFully(&dex_file2_data->GetHeader(),
749                                             dex_file2_data->GetHeader().file_size_);
750   ASSERT_TRUE(success);
751   success = dex_file2.GetFile()->Flush() == 0;
752   ASSERT_TRUE(success);
753   success = zip_builder.AddFile("classes2.dex",
754                                 &dex_file2_data->GetHeader(),
755                                 dex_file2_data->GetHeader().file_size_);
756   ASSERT_TRUE(success);
757 
758   success = zip_builder.Finish();
759   ASSERT_TRUE(success) << strerror(errno);
760 
761   SafeMap<std::string, std::string> key_value_store;
762   {
763     // Test using the AddDexFileSource() interface with the zip file.
764     std::vector<const char*> input_filenames = { zip_file.GetFilename().c_str() };
765 
766     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
767     success = WriteElf(tmp_vdex.GetFile(),
768                        tmp_oat.GetFile(),
769                        input_filenames,
770                        key_value_store,
771                        verify,
772                        copy,
773                        /*profile_compilation_info=*/ nullptr);
774 
775     if (verify) {
776       ASSERT_FALSE(success);
777     } else {
778       ASSERT_TRUE(success);
779 
780       std::string error_msg;
781       std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(/*zip_fd=*/ -1,
782                                                              tmp_oat.GetFilename(),
783                                                              tmp_oat.GetFilename(),
784                                                              /*executable=*/ false,
785                                                              /*low_4gb=*/ false,
786                                                              &error_msg));
787       ASSERT_TRUE(opened_oat_file != nullptr) << error_msg;
788       ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
789       std::unique_ptr<const DexFile> opened_dex_file1 =
790           opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
791       std::unique_ptr<const DexFile> opened_dex_file2 =
792           opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
793 
794       ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
795       ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
796                           &opened_dex_file1->GetHeader(),
797                           dex_file1_data->GetHeader().file_size_));
798       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
799                 opened_dex_file1->GetLocation());
800 
801       ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
802       ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
803                           &opened_dex_file2->GetHeader(),
804                           dex_file2_data->GetHeader().file_size_));
805       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
806                 opened_dex_file2->GetLocation());
807     }
808   }
809 
810   {
811     // Test using the AddDexFileSource() interface with the zip file handle.
812     File zip_fd(DupCloexec(zip_file.GetFd()), /*check_usage=*/ false);
813     ASSERT_NE(-1, zip_fd.Fd());
814     ASSERT_EQ(0, lseek(zip_fd.Fd(), 0, SEEK_SET));
815 
816     ScratchFile tmp_base, tmp_oat(tmp_base, ".oat"), tmp_vdex(tmp_base, ".vdex");
817     success = WriteElf(tmp_vdex.GetFile(),
818                        tmp_oat.GetFile(),
819                        std::move(zip_fd),
820                        zip_file.GetFilename().c_str(),
821                        key_value_store,
822                        verify,
823                        copy);
824     if (verify) {
825       ASSERT_FALSE(success);
826     } else {
827       ASSERT_TRUE(success);
828 
829       std::string error_msg;
830       std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(/*zip_fd=*/ -1,
831                                                              tmp_oat.GetFilename(),
832                                                              tmp_oat.GetFilename(),
833                                                              /*executable=*/ false,
834                                                              /*low_4gb=*/ false,
835                                                              &error_msg));
836       ASSERT_TRUE(opened_oat_file != nullptr) << error_msg;
837       ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
838       std::unique_ptr<const DexFile> opened_dex_file1 =
839           opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
840       std::unique_ptr<const DexFile> opened_dex_file2 =
841           opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
842 
843       ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
844       ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
845                           &opened_dex_file1->GetHeader(),
846                           dex_file1_data->GetHeader().file_size_));
847       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
848                 opened_dex_file1->GetLocation());
849 
850       ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
851       ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
852                           &opened_dex_file2->GetHeader(),
853                           dex_file2_data->GetHeader().file_size_));
854       ASSERT_EQ(DexFileLoader::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
855                 opened_dex_file2->GetLocation());
856     }
857   }
858 }
859 
TEST_F(OatTest,ZipFileInputCheckOutput)860 TEST_F(OatTest, ZipFileInputCheckOutput) {
861   TestZipFileInput(false, CopyOption::kOnlyIfCompressed);
862 }
863 
TEST_F(OatTest,ZipFileInputCheckOutputWithoutCopy)864 TEST_F(OatTest, ZipFileInputCheckOutputWithoutCopy) {
865   TestZipFileInput(false, CopyOption::kNever);
866 }
867 
TEST_F(OatTest,ZipFileInputCheckVerifier)868 TEST_F(OatTest, ZipFileInputCheckVerifier) {
869   TestZipFileInput(true, CopyOption::kOnlyIfCompressed);
870 }
871 
TestZipFileInputWithEmptyDex()872 void OatTest::TestZipFileInputWithEmptyDex() {
873   ScratchFile zip_file;
874   ZipBuilder zip_builder(zip_file.GetFile());
875   bool success = zip_builder.AddFile("classes.dex", nullptr, 0);
876   ASSERT_TRUE(success);
877   success = zip_builder.Finish();
878   ASSERT_TRUE(success) << strerror(errno);
879 
880   SafeMap<std::string, std::string> key_value_store;
881   std::vector<const char*> input_filenames = { zip_file.GetFilename().c_str() };
882   ScratchFile oat_file, vdex_file(oat_file, ".vdex");
883   std::unique_ptr<ProfileCompilationInfo> profile_compilation_info(new ProfileCompilationInfo());
884   success = WriteElf(vdex_file.GetFile(),
885                      oat_file.GetFile(),
886                      input_filenames,
887                      key_value_store,
888                      /*verify=*/ false,
889                      CopyOption::kOnlyIfCompressed,
890                      profile_compilation_info.get());
891   ASSERT_FALSE(success);
892 }
893 
TEST_F(OatTest,ZipFileInputWithEmptyDex)894 TEST_F(OatTest, ZipFileInputWithEmptyDex) {
895   TestZipFileInputWithEmptyDex();
896 }
897 
898 }  // namespace linker
899 }  // namespace art
900