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