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