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