oat_test.cc revision 3612149aee482ab7a17da68b0ef5fef3879729a2
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 "arch/instruction_set_features.h"
18#include "art_method-inl.h"
19#include "base/unix_file/fd_file.h"
20#include "class_linker.h"
21#include "common_compiler_test.h"
22#include "compiled_method.h"
23#include "compiler.h"
24#include "debug/method_debug_info.h"
25#include "dex/pass_manager.h"
26#include "dex/quick/dex_file_to_method_inliner_map.h"
27#include "dex/quick_compiler_callbacks.h"
28#include "dex/verification_results.h"
29#include "driver/compiler_driver.h"
30#include "driver/compiler_options.h"
31#include "elf_writer.h"
32#include "elf_writer_quick.h"
33#include "entrypoints/quick/quick_entrypoints.h"
34#include "linker/vector_output_stream.h"
35#include "mirror/class-inl.h"
36#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
38#include "oat_file-inl.h"
39#include "oat_writer.h"
40#include "scoped_thread_state_change.h"
41#include "utils/test_dex_file_builder.h"
42
43namespace art {
44
45NO_RETURN static void Usage(const char* fmt, ...) {
46  va_list ap;
47  va_start(ap, fmt);
48  std::string error;
49  StringAppendV(&error, fmt, ap);
50  LOG(FATAL) << error;
51  va_end(ap);
52  UNREACHABLE();
53}
54
55class OatTest : public CommonCompilerTest {
56 protected:
57  static const bool kCompile = false;  // DISABLED_ due to the time to compile libcore
58
59  void CheckMethod(ArtMethod* method,
60                   const OatFile::OatMethod& oat_method,
61                   const DexFile& dex_file)
62      SHARED_REQUIRES(Locks::mutator_lock_) {
63    const CompiledMethod* compiled_method =
64        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
65                                                            method->GetDexMethodIndex()));
66
67    if (compiled_method == nullptr) {
68      EXPECT_TRUE(oat_method.GetQuickCode() == nullptr) << PrettyMethod(method) << " "
69                                                        << oat_method.GetQuickCode();
70      EXPECT_EQ(oat_method.GetFrameSizeInBytes(), 0U);
71      EXPECT_EQ(oat_method.GetCoreSpillMask(), 0U);
72      EXPECT_EQ(oat_method.GetFpSpillMask(), 0U);
73    } else {
74      const void* quick_oat_code = oat_method.GetQuickCode();
75      EXPECT_TRUE(quick_oat_code != nullptr) << PrettyMethod(method);
76      EXPECT_EQ(oat_method.GetFrameSizeInBytes(), compiled_method->GetFrameSizeInBytes());
77      EXPECT_EQ(oat_method.GetCoreSpillMask(), compiled_method->GetCoreSpillMask());
78      EXPECT_EQ(oat_method.GetFpSpillMask(), compiled_method->GetFpSpillMask());
79      uintptr_t oat_code_aligned = RoundDown(reinterpret_cast<uintptr_t>(quick_oat_code), 2);
80      quick_oat_code = reinterpret_cast<const void*>(oat_code_aligned);
81      ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
82      EXPECT_FALSE(quick_code.empty());
83      size_t code_size = quick_code.size() * sizeof(quick_code[0]);
84      EXPECT_EQ(0, memcmp(quick_oat_code, &quick_code[0], code_size))
85          << PrettyMethod(method) << " " << code_size;
86      CHECK_EQ(0, memcmp(quick_oat_code, &quick_code[0], code_size));
87    }
88  }
89
90  void SetupCompiler(Compiler::Kind compiler_kind,
91                     InstructionSet insn_set,
92                     const std::vector<std::string>& compiler_options,
93                     /*out*/std::string* error_msg) {
94    ASSERT_TRUE(error_msg != nullptr);
95    insn_features_.reset(InstructionSetFeatures::FromVariant(insn_set, "default", error_msg));
96    ASSERT_TRUE(insn_features_ != nullptr) << error_msg;
97    compiler_options_.reset(new CompilerOptions);
98    for (const std::string& option : compiler_options) {
99      compiler_options_->ParseCompilerOption(option, Usage);
100    }
101    verification_results_.reset(new VerificationResults(compiler_options_.get()));
102    method_inliner_map_.reset(new DexFileToMethodInlinerMap);
103    callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
104                                                method_inliner_map_.get(),
105                                                CompilerCallbacks::CallbackMode::kCompileApp));
106    Runtime::Current()->SetCompilerCallbacks(callbacks_.get());
107    timer_.reset(new CumulativeLogger("Compilation times"));
108    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
109                                              verification_results_.get(),
110                                              method_inliner_map_.get(),
111                                              compiler_kind,
112                                              insn_set,
113                                              insn_features_.get(),
114                                              false,
115                                              nullptr,
116                                              nullptr,
117                                              nullptr,
118                                              2,
119                                              true,
120                                              true,
121                                              timer_.get(),
122                                              -1,
123                                              nullptr,
124                                              nullptr));
125  }
126
127  bool WriteElf(File* file,
128                const std::vector<const DexFile*>& dex_files,
129                SafeMap<std::string, std::string>& key_value_store,
130                bool verify) {
131    TimingLogger timings("WriteElf", false, false);
132    OatWriter oat_writer(/*compiling_boot_image*/false, &timings);
133    for (const DexFile* dex_file : dex_files) {
134      ArrayRef<const uint8_t> raw_dex_file(
135          reinterpret_cast<const uint8_t*>(&dex_file->GetHeader()),
136          dex_file->GetHeader().file_size_);
137      if (!oat_writer.AddRawDexFileSource(raw_dex_file,
138                                          dex_file->GetLocation().c_str(),
139                                          dex_file->GetLocationChecksum())) {
140        return false;
141      }
142    }
143    return DoWriteElf(file, oat_writer, key_value_store, verify);
144  }
145
146  bool WriteElf(File* file,
147                const std::vector<const char*>& dex_filenames,
148                SafeMap<std::string, std::string>& key_value_store,
149                bool verify) {
150    TimingLogger timings("WriteElf", false, false);
151    OatWriter oat_writer(/*compiling_boot_image*/false, &timings);
152    for (const char* dex_filename : dex_filenames) {
153      if (!oat_writer.AddDexFileSource(dex_filename, dex_filename)) {
154        return false;
155      }
156    }
157    return DoWriteElf(file, oat_writer, key_value_store, verify);
158  }
159
160  bool WriteElf(File* file,
161                ScopedFd&& zip_fd,
162                const char* location,
163                SafeMap<std::string, std::string>& key_value_store,
164                bool verify) {
165    TimingLogger timings("WriteElf", false, false);
166    OatWriter oat_writer(/*compiling_boot_image*/false, &timings);
167    if (!oat_writer.AddZippedDexFilesSource(std::move(zip_fd), location)) {
168      return false;
169    }
170    return DoWriteElf(file, oat_writer, key_value_store, verify);
171  }
172
173  bool DoWriteElf(File* file,
174                  OatWriter& oat_writer,
175                  SafeMap<std::string, std::string>& key_value_store,
176                  bool verify) {
177    std::unique_ptr<ElfWriter> elf_writer = CreateElfWriterQuick(
178        compiler_driver_->GetInstructionSet(),
179        &compiler_driver_->GetCompilerOptions(),
180        file);
181    elf_writer->Start();
182    OutputStream* rodata = elf_writer->StartRoData();
183    std::unique_ptr<MemMap> opened_dex_files_map;
184    std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
185    if (!oat_writer.WriteAndOpenDexFiles(rodata,
186                                         file,
187                                         compiler_driver_->GetInstructionSet(),
188                                         compiler_driver_->GetInstructionSetFeatures(),
189                                         &key_value_store,
190                                         verify,
191                                         &opened_dex_files_map,
192                                         &opened_dex_files)) {
193      return false;
194    }
195    Runtime* runtime = Runtime::Current();
196    ClassLinker* const class_linker = runtime->GetClassLinker();
197    std::vector<const DexFile*> dex_files;
198    for (const std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
199      dex_files.push_back(dex_file.get());
200      ScopedObjectAccess soa(Thread::Current());
201      class_linker->RegisterDexFile(*dex_file, runtime->GetLinearAlloc());
202    }
203    oat_writer.PrepareLayout(compiler_driver_.get(), nullptr, dex_files);
204    if (!oat_writer.WriteRodata(rodata)) {
205      return false;
206    }
207    elf_writer->EndRoData(rodata);
208
209    OutputStream* text = elf_writer->StartText();
210    if (!oat_writer.WriteCode(text)) {
211      return false;
212    }
213    elf_writer->EndText(text);
214
215    if (!oat_writer.WriteHeader(elf_writer->GetStream(), 42U, 4096U, 0)) {
216      return false;
217    }
218
219    elf_writer->SetBssSize(oat_writer.GetBssSize());
220    elf_writer->WriteDynamicSection();
221    elf_writer->WriteDebugInfo(oat_writer.GetMethodDebugInfo());
222    elf_writer->WritePatchLocations(oat_writer.GetAbsolutePatchLocations());
223
224    return elf_writer->End();
225  }
226
227  void TestDexFileInput(bool verify);
228  void TestZipFileInput(bool verify);
229
230  std::unique_ptr<const InstructionSetFeatures> insn_features_;
231  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
232};
233
234class ZipBuilder {
235 public:
236  explicit ZipBuilder(File* zip_file) : zip_file_(zip_file) { }
237
238  bool AddFile(const char* location, const void* data, size_t size) {
239    off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
240    if (offset == static_cast<off_t>(-1)) {
241      return false;
242    }
243
244    ZipFileHeader file_header;
245    file_header.crc32 = crc32(0u, reinterpret_cast<const Bytef*>(data), size);
246    file_header.compressed_size = size;
247    file_header.uncompressed_size = size;
248    file_header.filename_length = strlen(location);
249
250    if (!zip_file_->WriteFully(&file_header, sizeof(file_header)) ||
251        !zip_file_->WriteFully(location, file_header.filename_length) ||
252        !zip_file_->WriteFully(data, size)) {
253      return false;
254    }
255
256    CentralDirectoryFileHeader cdfh;
257    cdfh.crc32 = file_header.crc32;
258    cdfh.compressed_size = size;
259    cdfh.uncompressed_size = size;
260    cdfh.filename_length = file_header.filename_length;
261    cdfh.relative_offset_of_local_file_header = offset;
262    file_data_.push_back(FileData { cdfh, location });
263    return true;
264  }
265
266  bool Finish() {
267    off_t offset = lseek(zip_file_->Fd(), 0, SEEK_CUR);
268    if (offset == static_cast<off_t>(-1)) {
269      return false;
270    }
271
272    size_t central_directory_size = 0u;
273    for (const FileData& file_data : file_data_) {
274      if (!zip_file_->WriteFully(&file_data.cdfh, sizeof(file_data.cdfh)) ||
275          !zip_file_->WriteFully(file_data.location, file_data.cdfh.filename_length)) {
276        return false;
277      }
278      central_directory_size += sizeof(file_data.cdfh) + file_data.cdfh.filename_length;
279    }
280    EndOfCentralDirectoryRecord eocd_record;
281    eocd_record.number_of_central_directory_records_on_this_disk = file_data_.size();
282    eocd_record.total_number_of_central_directory_records = file_data_.size();
283    eocd_record.size_of_central_directory = central_directory_size;
284    eocd_record.offset_of_start_of_central_directory = offset;
285    return
286        zip_file_->WriteFully(&eocd_record, sizeof(eocd_record)) &&
287        zip_file_->Flush() == 0;
288  }
289
290 private:
291  struct PACKED(1) ZipFileHeader {
292    uint32_t signature = 0x04034b50;
293    uint16_t version_needed_to_extract = 10;
294    uint16_t general_purpose_bit_flag = 0;
295    uint16_t compression_method = 0;            // 0 = store only.
296    uint16_t file_last_modification_time = 0u;
297    uint16_t file_last_modification_date = 0u;
298    uint32_t crc32;
299    uint32_t compressed_size;
300    uint32_t uncompressed_size;
301    uint16_t filename_length;
302    uint16_t extra_field_length = 0u;           // No extra fields.
303  };
304
305  struct PACKED(1) CentralDirectoryFileHeader {
306    uint32_t signature = 0x02014b50;
307    uint16_t version_made_by = 10;
308    uint16_t version_needed_to_extract = 10;
309    uint16_t general_purpose_bit_flag = 0;
310    uint16_t compression_method = 0;            // 0 = store only.
311    uint16_t file_last_modification_time = 0u;
312    uint16_t file_last_modification_date = 0u;
313    uint32_t crc32;
314    uint32_t compressed_size;
315    uint32_t uncompressed_size;
316    uint16_t filename_length;
317    uint16_t extra_field_length = 0u;           // No extra fields.
318    uint16_t file_comment_length = 0u;          // No file comment.
319    uint16_t disk_number_where_file_starts = 0u;
320    uint16_t internal_file_attributes = 0u;
321    uint32_t external_file_attributes = 0u;
322    uint32_t relative_offset_of_local_file_header;
323  };
324
325  struct PACKED(1) EndOfCentralDirectoryRecord {
326    uint32_t signature = 0x06054b50;
327    uint16_t number_of_this_disk = 0u;
328    uint16_t disk_where_central_directory_starts = 0u;
329    uint16_t number_of_central_directory_records_on_this_disk;
330    uint16_t total_number_of_central_directory_records;
331    uint32_t size_of_central_directory;
332    uint32_t offset_of_start_of_central_directory;
333    uint16_t comment_length = 0u;               // No file comment.
334  };
335
336  struct FileData {
337    CentralDirectoryFileHeader cdfh;
338    const char* location;
339  };
340
341  File* zip_file_;
342  std::vector<FileData> file_data_;
343};
344
345TEST_F(OatTest, WriteRead) {
346  TimingLogger timings("OatTest::WriteRead", false, false);
347  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
348
349  // TODO: make selectable.
350  Compiler::Kind compiler_kind = Compiler::kQuick;
351  InstructionSet insn_set = kIsTargetBuild ? kThumb2 : kX86;
352  std::string error_msg;
353  SetupCompiler(compiler_kind, insn_set, std::vector<std::string>(), /*out*/ &error_msg);
354
355  jobject class_loader = nullptr;
356  if (kCompile) {
357    TimingLogger timings2("OatTest::WriteRead", false, false);
358    compiler_driver_->SetDexFilesForOatFile(class_linker->GetBootClassPath());
359    compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings2);
360  }
361
362  ScratchFile tmp;
363  SafeMap<std::string, std::string> key_value_store;
364  key_value_store.Put(OatHeader::kImageLocationKey, "lue.art");
365  bool success = WriteElf(tmp.GetFile(), class_linker->GetBootClassPath(), key_value_store, false);
366  ASSERT_TRUE(success);
367
368  if (kCompile) {  // OatWriter strips the code, regenerate to compare
369    compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
370  }
371  std::unique_ptr<OatFile> oat_file(OatFile::Open(tmp.GetFilename(), tmp.GetFilename(), nullptr,
372                                                  nullptr, false, nullptr, &error_msg));
373  ASSERT_TRUE(oat_file.get() != nullptr) << error_msg;
374  const OatHeader& oat_header = oat_file->GetOatHeader();
375  ASSERT_TRUE(oat_header.IsValid());
376  ASSERT_EQ(class_linker->GetBootClassPath().size(), oat_header.GetDexFileCount());  // core
377  ASSERT_EQ(42U, oat_header.GetImageFileLocationOatChecksum());
378  ASSERT_EQ(4096U, oat_header.GetImageFileLocationOatDataBegin());
379  ASSERT_EQ("lue.art", std::string(oat_header.GetStoreValueByKey(OatHeader::kImageLocationKey)));
380
381  ASSERT_TRUE(java_lang_dex_file_ != nullptr);
382  const DexFile& dex_file = *java_lang_dex_file_;
383  uint32_t dex_file_checksum = dex_file.GetLocationChecksum();
384  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
385                                                                    &dex_file_checksum);
386  ASSERT_TRUE(oat_dex_file != nullptr);
387  CHECK_EQ(dex_file.GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
388  ScopedObjectAccess soa(Thread::Current());
389  auto pointer_size = class_linker->GetImagePointerSize();
390  for (size_t i = 0; i < dex_file.NumClassDefs(); i++) {
391    const DexFile::ClassDef& class_def = dex_file.GetClassDef(i);
392    const uint8_t* class_data = dex_file.GetClassData(class_def);
393
394    size_t num_virtual_methods = 0;
395    if (class_data != nullptr) {
396      ClassDataItemIterator it(dex_file, class_data);
397      num_virtual_methods = it.NumVirtualMethods();
398    }
399
400    const char* descriptor = dex_file.GetClassDescriptor(class_def);
401    mirror::Class* klass = class_linker->FindClass(soa.Self(),
402                                                   descriptor,
403                                                   ScopedNullHandle<mirror::ClassLoader>());
404
405    const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(i);
406    CHECK_EQ(mirror::Class::Status::kStatusNotReady, oat_class.GetStatus()) << descriptor;
407    CHECK_EQ(kCompile ? OatClassType::kOatClassAllCompiled : OatClassType::kOatClassNoneCompiled,
408             oat_class.GetType()) << descriptor;
409
410    size_t method_index = 0;
411    for (auto& m : klass->GetDirectMethods(pointer_size)) {
412      CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
413      ++method_index;
414    }
415    size_t visited_virtuals = 0;
416    // TODO We should also check copied methods in this test.
417    for (auto& m : klass->GetDeclaredVirtualMethods(pointer_size)) {
418      if (!klass->IsInterface()) {
419        EXPECT_FALSE(m.IsCopied());
420      }
421      CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
422      ++method_index;
423      ++visited_virtuals;
424    }
425    EXPECT_EQ(visited_virtuals, num_virtual_methods);
426  }
427}
428
429TEST_F(OatTest, OatHeaderSizeCheck) {
430  // If this test is failing and you have to update these constants,
431  // it is time to update OatHeader::kOatVersion
432  EXPECT_EQ(72U, sizeof(OatHeader));
433  EXPECT_EQ(4U, sizeof(OatMethodOffsets));
434  EXPECT_EQ(28U, sizeof(OatQuickMethodHeader));
435  EXPECT_EQ(132 * GetInstructionSetPointerSize(kRuntimeISA), sizeof(QuickEntryPoints));
436}
437
438TEST_F(OatTest, OatHeaderIsValid) {
439    InstructionSet insn_set = kX86;
440    std::string error_msg;
441    std::unique_ptr<const InstructionSetFeatures> insn_features(
442        InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
443    ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
444    std::unique_ptr<OatHeader> oat_header(OatHeader::Create(insn_set,
445                                                            insn_features.get(),
446                                                            0u,
447                                                            nullptr));
448    ASSERT_NE(oat_header.get(), nullptr);
449    ASSERT_TRUE(oat_header->IsValid());
450
451    char* magic = const_cast<char*>(oat_header->GetMagic());
452    strcpy(magic, "");  // bad magic
453    ASSERT_FALSE(oat_header->IsValid());
454    strcpy(magic, "oat\n000");  // bad version
455    ASSERT_FALSE(oat_header->IsValid());
456}
457
458TEST_F(OatTest, EmptyTextSection) {
459  TimingLogger timings("OatTest::EmptyTextSection", false, false);
460
461  // TODO: make selectable.
462  Compiler::Kind compiler_kind = Compiler::kQuick;
463  InstructionSet insn_set = kRuntimeISA;
464  if (insn_set == kArm) insn_set = kThumb2;
465  std::string error_msg;
466  std::vector<std::string> compiler_options;
467  compiler_options.push_back("--compiler-filter=verify-at-runtime");
468  SetupCompiler(compiler_kind, insn_set, compiler_options, /*out*/ &error_msg);
469
470  jobject class_loader;
471  {
472    ScopedObjectAccess soa(Thread::Current());
473    class_loader = LoadDex("Main");
474  }
475  ASSERT_TRUE(class_loader != nullptr);
476  std::vector<const DexFile*> dex_files = GetDexFiles(class_loader);
477  ASSERT_TRUE(!dex_files.empty());
478
479  ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
480  for (const DexFile* dex_file : dex_files) {
481    ScopedObjectAccess soa(Thread::Current());
482    class_linker->RegisterDexFile(
483        *dex_file,
484        class_linker->GetOrCreateAllocatorForClassLoader(
485            soa.Decode<mirror::ClassLoader*>(class_loader)));
486  }
487  compiler_driver_->SetDexFilesForOatFile(dex_files);
488  compiler_driver_->CompileAll(class_loader, dex_files, &timings);
489
490  ScratchFile tmp;
491  SafeMap<std::string, std::string> key_value_store;
492  key_value_store.Put(OatHeader::kImageLocationKey, "test.art");
493  bool success = WriteElf(tmp.GetFile(), dex_files, key_value_store, false);
494  ASSERT_TRUE(success);
495
496  std::unique_ptr<OatFile> oat_file(OatFile::Open(tmp.GetFilename(),
497                                                  tmp.GetFilename(),
498                                                  nullptr,
499                                                  nullptr,
500                                                  false,
501                                                  nullptr,
502                                                  &error_msg));
503  ASSERT_TRUE(oat_file != nullptr);
504  EXPECT_LT(static_cast<size_t>(oat_file->Size()), static_cast<size_t>(tmp.GetFile()->GetLength()));
505}
506
507static void MaybeModifyDexFileToFail(bool verify, std::unique_ptr<const DexFile>& data) {
508  // If in verify mode (= fail the verifier mode), make sure we fail early. We'll fail already
509  // because of the missing map, but that may lead to out of bounds reads.
510  if (verify) {
511    const_cast<DexFile::Header*>(&data->GetHeader())->checksum_++;
512  }
513}
514
515void OatTest::TestDexFileInput(bool verify) {
516  TimingLogger timings("OatTest::DexFileInput", false, false);
517
518  std::vector<const char*> input_filenames;
519
520  ScratchFile dex_file1;
521  TestDexFileBuilder builder1;
522  builder1.AddField("Lsome.TestClass;", "int", "someField");
523  builder1.AddMethod("Lsome.TestClass;", "()I", "foo");
524  std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
525
526  MaybeModifyDexFileToFail(verify, dex_file1_data);
527
528  bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
529                                                 dex_file1_data->GetHeader().file_size_);
530  ASSERT_TRUE(success);
531  success = dex_file1.GetFile()->Flush() == 0;
532  ASSERT_TRUE(success);
533  input_filenames.push_back(dex_file1.GetFilename().c_str());
534
535  ScratchFile dex_file2;
536  TestDexFileBuilder builder2;
537  builder2.AddField("Land.AnotherTestClass;", "boolean", "someOtherField");
538  builder2.AddMethod("Land.AnotherTestClass;", "()J", "bar");
539  std::unique_ptr<const DexFile> dex_file2_data = builder2.Build(dex_file2.GetFilename());
540
541  MaybeModifyDexFileToFail(verify, dex_file2_data);
542
543  success = dex_file2.GetFile()->WriteFully(&dex_file2_data->GetHeader(),
544                                            dex_file2_data->GetHeader().file_size_);
545  ASSERT_TRUE(success);
546  success = dex_file2.GetFile()->Flush() == 0;
547  ASSERT_TRUE(success);
548  input_filenames.push_back(dex_file2.GetFilename().c_str());
549
550  ScratchFile oat_file;
551  SafeMap<std::string, std::string> key_value_store;
552  key_value_store.Put(OatHeader::kImageLocationKey, "test.art");
553  success = WriteElf(oat_file.GetFile(), input_filenames, key_value_store, verify);
554
555  // In verify mode, we expect failure.
556  if (verify) {
557    ASSERT_FALSE(success);
558    return;
559  }
560
561  ASSERT_TRUE(success);
562
563  std::string error_msg;
564  std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(oat_file.GetFilename(),
565                                                         oat_file.GetFilename(),
566                                                         nullptr,
567                                                         nullptr,
568                                                         false,
569                                                         nullptr,
570                                                         &error_msg));
571  ASSERT_TRUE(opened_oat_file != nullptr);
572  ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
573  std::unique_ptr<const DexFile> opened_dex_file1 =
574      opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
575  std::unique_ptr<const DexFile> opened_dex_file2 =
576      opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
577
578  ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
579  ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
580                      &opened_dex_file1->GetHeader(),
581                      dex_file1_data->GetHeader().file_size_));
582  ASSERT_EQ(dex_file1_data->GetLocation(), opened_dex_file1->GetLocation());
583
584  ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
585  ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
586                      &opened_dex_file2->GetHeader(),
587                      dex_file2_data->GetHeader().file_size_));
588  ASSERT_EQ(dex_file2_data->GetLocation(), opened_dex_file2->GetLocation());
589}
590
591TEST_F(OatTest, DexFileInputCheckOutput) {
592  TestDexFileInput(false);
593}
594
595TEST_F(OatTest, DexFileInputCheckVerifier) {
596  TestDexFileInput(true);
597}
598
599void OatTest::TestZipFileInput(bool verify) {
600  TimingLogger timings("OatTest::DexFileInput", false, false);
601
602  ScratchFile zip_file;
603  ZipBuilder zip_builder(zip_file.GetFile());
604
605  ScratchFile dex_file1;
606  TestDexFileBuilder builder1;
607  builder1.AddField("Lsome.TestClass;", "long", "someField");
608  builder1.AddMethod("Lsome.TestClass;", "()D", "foo");
609  std::unique_ptr<const DexFile> dex_file1_data = builder1.Build(dex_file1.GetFilename());
610
611  MaybeModifyDexFileToFail(verify, dex_file1_data);
612
613  bool success = dex_file1.GetFile()->WriteFully(&dex_file1_data->GetHeader(),
614                                                 dex_file1_data->GetHeader().file_size_);
615  ASSERT_TRUE(success);
616  success = dex_file1.GetFile()->Flush() == 0;
617  ASSERT_TRUE(success);
618  success = zip_builder.AddFile("classes.dex",
619                                &dex_file1_data->GetHeader(),
620                                dex_file1_data->GetHeader().file_size_);
621  ASSERT_TRUE(success);
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  success = zip_builder.AddFile("classes2.dex",
637                                &dex_file2_data->GetHeader(),
638                                dex_file2_data->GetHeader().file_size_);
639  ASSERT_TRUE(success);
640
641  success = zip_builder.Finish();
642  ASSERT_TRUE(success) << strerror(errno);
643
644  SafeMap<std::string, std::string> key_value_store;
645  key_value_store.Put(OatHeader::kImageLocationKey, "test.art");
646  {
647    // Test using the AddDexFileSource() interface with the zip file.
648    std::vector<const char*> input_filenames { zip_file.GetFilename().c_str() };  // NOLINT [readability/braces] [4]
649
650    ScratchFile oat_file;
651    success = WriteElf(oat_file.GetFile(), input_filenames, key_value_store, verify);
652
653    if (verify) {
654      ASSERT_FALSE(success);
655    } else {
656      ASSERT_TRUE(success);
657
658      std::string error_msg;
659      std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(oat_file.GetFilename(),
660                                                             oat_file.GetFilename(),
661                                                             nullptr,
662                                                             nullptr,
663                                                             false,
664                                                             nullptr,
665                                                             &error_msg));
666      ASSERT_TRUE(opened_oat_file != nullptr);
667      ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
668      std::unique_ptr<const DexFile> opened_dex_file1 =
669          opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
670      std::unique_ptr<const DexFile> opened_dex_file2 =
671          opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
672
673      ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
674      ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
675                          &opened_dex_file1->GetHeader(),
676                          dex_file1_data->GetHeader().file_size_));
677      ASSERT_EQ(DexFile::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
678                opened_dex_file1->GetLocation());
679
680      ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
681      ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
682                          &opened_dex_file2->GetHeader(),
683                          dex_file2_data->GetHeader().file_size_));
684      ASSERT_EQ(DexFile::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
685                opened_dex_file2->GetLocation());
686    }
687  }
688
689  {
690    // Test using the AddZipDexFileSource() interface with the zip file handle.
691    ScopedFd zip_fd(dup(zip_file.GetFd()));
692    ASSERT_NE(-1, zip_fd.get());
693
694    ScratchFile oat_file;
695    success = WriteElf(oat_file.GetFile(),
696                       std::move(zip_fd),
697                       zip_file.GetFilename().c_str(),
698                       key_value_store,
699                       verify);
700    if (verify) {
701      ASSERT_FALSE(success);
702    } else {
703      ASSERT_TRUE(success);
704
705      std::string error_msg;
706      std::unique_ptr<OatFile> opened_oat_file(OatFile::Open(oat_file.GetFilename(),
707                                                             oat_file.GetFilename(),
708                                                             nullptr,
709                                                             nullptr,
710                                                             false,
711                                                             nullptr,
712                                                             &error_msg));
713      ASSERT_TRUE(opened_oat_file != nullptr);
714      ASSERT_EQ(2u, opened_oat_file->GetOatDexFiles().size());
715      std::unique_ptr<const DexFile> opened_dex_file1 =
716          opened_oat_file->GetOatDexFiles()[0]->OpenDexFile(&error_msg);
717      std::unique_ptr<const DexFile> opened_dex_file2 =
718          opened_oat_file->GetOatDexFiles()[1]->OpenDexFile(&error_msg);
719
720      ASSERT_EQ(dex_file1_data->GetHeader().file_size_, opened_dex_file1->GetHeader().file_size_);
721      ASSERT_EQ(0, memcmp(&dex_file1_data->GetHeader(),
722                          &opened_dex_file1->GetHeader(),
723                          dex_file1_data->GetHeader().file_size_));
724      ASSERT_EQ(DexFile::GetMultiDexLocation(0, zip_file.GetFilename().c_str()),
725                opened_dex_file1->GetLocation());
726
727      ASSERT_EQ(dex_file2_data->GetHeader().file_size_, opened_dex_file2->GetHeader().file_size_);
728      ASSERT_EQ(0, memcmp(&dex_file2_data->GetHeader(),
729                          &opened_dex_file2->GetHeader(),
730                          dex_file2_data->GetHeader().file_size_));
731      ASSERT_EQ(DexFile::GetMultiDexLocation(1, zip_file.GetFilename().c_str()),
732                opened_dex_file2->GetLocation());
733    }
734  }
735}
736
737TEST_F(OatTest, ZipFileInputCheckOutput) {
738  TestZipFileInput(false);
739}
740
741TEST_F(OatTest, ZipFileInputCheckVerifier) {
742  TestZipFileInput(true);
743}
744
745}  // namespace art
746