oat_test.cc revision 6286a97bea0f584342803a215550038852b24776
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 "dex/pass_manager.h"
25#include "dex/quick/dex_file_to_method_inliner_map.h"
26#include "dex/quick_compiler_callbacks.h"
27#include "dex/verification_results.h"
28#include "driver/compiler_driver.h"
29#include "driver/compiler_options.h"
30#include "dwarf/method_debug_info.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_array-inl.h"
37#include "mirror/object-inl.h"
38#include "oat_file-inl.h"
39#include "oat_writer.h"
40#include "scoped_thread_state_change.h"
41
42namespace art {
43
44NO_RETURN static void Usage(const char* fmt, ...) {
45  va_list ap;
46  va_start(ap, fmt);
47  std::string error;
48  StringAppendV(&error, fmt, ap);
49  LOG(FATAL) << error;
50  va_end(ap);
51  UNREACHABLE();
52}
53
54class OatTest : public CommonCompilerTest {
55 protected:
56  static const bool kCompile = false;  // DISABLED_ due to the time to compile libcore
57
58  void CheckMethod(ArtMethod* method,
59                   const OatFile::OatMethod& oat_method,
60                   const DexFile& dex_file)
61      SHARED_REQUIRES(Locks::mutator_lock_) {
62    const CompiledMethod* compiled_method =
63        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
64                                                            method->GetDexMethodIndex()));
65
66    if (compiled_method == nullptr) {
67      EXPECT_TRUE(oat_method.GetQuickCode() == nullptr) << PrettyMethod(method) << " "
68                                                        << oat_method.GetQuickCode();
69      EXPECT_EQ(oat_method.GetFrameSizeInBytes(), 0U);
70      EXPECT_EQ(oat_method.GetCoreSpillMask(), 0U);
71      EXPECT_EQ(oat_method.GetFpSpillMask(), 0U);
72    } else {
73      const void* quick_oat_code = oat_method.GetQuickCode();
74      EXPECT_TRUE(quick_oat_code != nullptr) << PrettyMethod(method);
75      EXPECT_EQ(oat_method.GetFrameSizeInBytes(), compiled_method->GetFrameSizeInBytes());
76      EXPECT_EQ(oat_method.GetCoreSpillMask(), compiled_method->GetCoreSpillMask());
77      EXPECT_EQ(oat_method.GetFpSpillMask(), compiled_method->GetFpSpillMask());
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          << PrettyMethod(method) << " " << code_size;
85      CHECK_EQ(0, memcmp(quick_oat_code, &quick_code[0], code_size));
86    }
87  }
88
89  void SetupCompiler(Compiler::Kind compiler_kind,
90                     InstructionSet insn_set,
91                     const std::vector<std::string>& compiler_options,
92                     /*out*/std::string* error_msg) {
93    ASSERT_TRUE(error_msg != nullptr);
94    insn_features_.reset(InstructionSetFeatures::FromVariant(insn_set, "default", error_msg));
95    ASSERT_TRUE(insn_features_ != nullptr) << error_msg;
96    compiler_options_.reset(new CompilerOptions);
97    for (const std::string& option : compiler_options) {
98      compiler_options_->ParseCompilerOption(option, Usage);
99    }
100    verification_results_.reset(new VerificationResults(compiler_options_.get()));
101    method_inliner_map_.reset(new DexFileToMethodInlinerMap);
102    callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
103                                                method_inliner_map_.get(),
104                                                CompilerCallbacks::CallbackMode::kCompileApp));
105    Runtime::Current()->SetCompilerCallbacks(callbacks_.get());
106    timer_.reset(new CumulativeLogger("Compilation times"));
107    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
108                                              verification_results_.get(),
109                                              method_inliner_map_.get(),
110                                              compiler_kind,
111                                              insn_set,
112                                              insn_features_.get(),
113                                              false,
114                                              nullptr,
115                                              nullptr,
116                                              nullptr,
117                                              2,
118                                              true,
119                                              true,
120                                              "",
121                                              false,
122                                              timer_.get(),
123                                              -1,
124                                              ""));
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    TimingLogger timings("WriteElf", false, false);
131    OatWriter oat_writer(dex_files,
132                         42U,
133                         4096U,
134                         0,
135                         compiler_driver_.get(),
136                         nullptr,
137                         /*compiling_boot_image*/false,
138                         &timings,
139                         &key_value_store);
140    std::unique_ptr<ElfWriter> elf_writer = CreateElfWriterQuick(
141        compiler_driver_->GetInstructionSet(),
142        &compiler_driver_->GetCompilerOptions(),
143        file);
144
145    elf_writer->Start();
146
147    OutputStream* rodata = elf_writer->StartRoData();
148    if (!oat_writer.WriteRodata(rodata)) {
149      return false;
150    }
151    elf_writer->EndRoData(rodata);
152
153    OutputStream* text = elf_writer->StartText();
154    if (!oat_writer.WriteCode(text)) {
155      return false;
156    }
157    elf_writer->EndText(text);
158
159    elf_writer->SetBssSize(oat_writer.GetBssSize());
160    elf_writer->WriteDynamicSection();
161    elf_writer->WriteDebugInfo(oat_writer.GetMethodDebugInfo());
162    elf_writer->WritePatchLocations(oat_writer.GetAbsolutePatchLocations());
163
164    return elf_writer->End();
165  }
166
167  std::unique_ptr<const InstructionSetFeatures> insn_features_;
168  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
169};
170
171TEST_F(OatTest, WriteRead) {
172  TimingLogger timings("OatTest::WriteRead", false, false);
173  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
174
175  // TODO: make selectable.
176  Compiler::Kind compiler_kind = Compiler::kQuick;
177  InstructionSet insn_set = kIsTargetBuild ? kThumb2 : kX86;
178  std::string error_msg;
179  SetupCompiler(compiler_kind, insn_set, std::vector<std::string>(), /*out*/ &error_msg);
180
181  jobject class_loader = nullptr;
182  if (kCompile) {
183    TimingLogger timings2("OatTest::WriteRead", false, false);
184    compiler_driver_->SetDexFilesForOatFile(class_linker->GetBootClassPath());
185    compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings2);
186  }
187
188  ScratchFile tmp;
189  SafeMap<std::string, std::string> key_value_store;
190  key_value_store.Put(OatHeader::kImageLocationKey, "lue.art");
191  bool success = WriteElf(tmp.GetFile(), class_linker->GetBootClassPath(), key_value_store);
192  ASSERT_TRUE(success);
193
194  if (kCompile) {  // OatWriter strips the code, regenerate to compare
195    compiler_driver_->CompileAll(class_loader, class_linker->GetBootClassPath(), &timings);
196  }
197  std::unique_ptr<OatFile> oat_file(OatFile::Open(tmp.GetFilename(), tmp.GetFilename(), nullptr,
198                                                  nullptr, false, nullptr, &error_msg));
199  ASSERT_TRUE(oat_file.get() != nullptr) << error_msg;
200  const OatHeader& oat_header = oat_file->GetOatHeader();
201  ASSERT_TRUE(oat_header.IsValid());
202  ASSERT_EQ(1U, oat_header.GetDexFileCount());  // core
203  ASSERT_EQ(42U, oat_header.GetImageFileLocationOatChecksum());
204  ASSERT_EQ(4096U, oat_header.GetImageFileLocationOatDataBegin());
205  ASSERT_EQ("lue.art", std::string(oat_header.GetStoreValueByKey(OatHeader::kImageLocationKey)));
206
207  ASSERT_TRUE(java_lang_dex_file_ != nullptr);
208  const DexFile& dex_file = *java_lang_dex_file_;
209  uint32_t dex_file_checksum = dex_file.GetLocationChecksum();
210  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
211                                                                    &dex_file_checksum);
212  ASSERT_TRUE(oat_dex_file != nullptr);
213  CHECK_EQ(dex_file.GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
214  ScopedObjectAccess soa(Thread::Current());
215  auto pointer_size = class_linker->GetImagePointerSize();
216  for (size_t i = 0; i < dex_file.NumClassDefs(); i++) {
217    const DexFile::ClassDef& class_def = dex_file.GetClassDef(i);
218    const uint8_t* class_data = dex_file.GetClassData(class_def);
219
220    size_t num_virtual_methods = 0;
221    if (class_data != nullptr) {
222      ClassDataItemIterator it(dex_file, class_data);
223      num_virtual_methods = it.NumVirtualMethods();
224    }
225
226    const char* descriptor = dex_file.GetClassDescriptor(class_def);
227    mirror::Class* klass = class_linker->FindClass(soa.Self(), descriptor,
228                                                   NullHandle<mirror::ClassLoader>());
229
230    const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(i);
231    CHECK_EQ(mirror::Class::Status::kStatusNotReady, oat_class.GetStatus()) << descriptor;
232    CHECK_EQ(kCompile ? OatClassType::kOatClassAllCompiled : OatClassType::kOatClassNoneCompiled,
233             oat_class.GetType()) << descriptor;
234
235    size_t method_index = 0;
236    for (auto& m : klass->GetDirectMethods(pointer_size)) {
237      CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
238      ++method_index;
239    }
240    size_t visited_virtuals = 0;
241    // TODO We should also check copied methods in this test.
242    for (auto& m : klass->GetDeclaredVirtualMethods(pointer_size)) {
243      EXPECT_FALSE(m.IsMiranda());
244      CheckMethod(&m, oat_class.GetOatMethod(method_index), dex_file);
245      ++method_index;
246      ++visited_virtuals;
247    }
248    EXPECT_EQ(visited_virtuals, num_virtual_methods);
249  }
250}
251
252TEST_F(OatTest, OatHeaderSizeCheck) {
253  // If this test is failing and you have to update these constants,
254  // it is time to update OatHeader::kOatVersion
255  EXPECT_EQ(72U, sizeof(OatHeader));
256  EXPECT_EQ(4U, sizeof(OatMethodOffsets));
257  EXPECT_EQ(28U, sizeof(OatQuickMethodHeader));
258  EXPECT_EQ(131 * GetInstructionSetPointerSize(kRuntimeISA), sizeof(QuickEntryPoints));
259}
260
261TEST_F(OatTest, OatHeaderIsValid) {
262    InstructionSet insn_set = kX86;
263    std::string error_msg;
264    std::unique_ptr<const InstructionSetFeatures> insn_features(
265        InstructionSetFeatures::FromVariant(insn_set, "default", &error_msg));
266    ASSERT_TRUE(insn_features.get() != nullptr) << error_msg;
267    std::unique_ptr<OatHeader> oat_header(OatHeader::Create(insn_set,
268                                                            insn_features.get(),
269                                                            0u,
270                                                            nullptr));
271    ASSERT_NE(oat_header.get(), nullptr);
272    ASSERT_TRUE(oat_header->IsValid());
273
274    char* magic = const_cast<char*>(oat_header->GetMagic());
275    strcpy(magic, "");  // bad magic
276    ASSERT_FALSE(oat_header->IsValid());
277    strcpy(magic, "oat\n000");  // bad version
278    ASSERT_FALSE(oat_header->IsValid());
279}
280
281TEST_F(OatTest, EmptyTextSection) {
282  TimingLogger timings("OatTest::EmptyTextSection", false, false);
283
284  // TODO: make selectable.
285  Compiler::Kind compiler_kind = Compiler::kQuick;
286  InstructionSet insn_set = kRuntimeISA;
287  if (insn_set == kArm) insn_set = kThumb2;
288  std::string error_msg;
289  std::vector<std::string> compiler_options;
290  compiler_options.push_back("--compiler-filter=verify-at-runtime");
291  SetupCompiler(compiler_kind, insn_set, compiler_options, /*out*/ &error_msg);
292
293  jobject class_loader;
294  {
295    ScopedObjectAccess soa(Thread::Current());
296    class_loader = LoadDex("Main");
297  }
298  ASSERT_TRUE(class_loader != nullptr);
299  std::vector<const DexFile*> dex_files = GetDexFiles(class_loader);
300  ASSERT_TRUE(!dex_files.empty());
301
302  ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
303  for (const DexFile* dex_file : dex_files) {
304    ScopedObjectAccess soa(Thread::Current());
305    class_linker->RegisterDexFile(
306        *dex_file,
307        class_linker->GetOrCreateAllocatorForClassLoader(
308            soa.Decode<mirror::ClassLoader*>(class_loader)));
309  }
310  compiler_driver_->SetDexFilesForOatFile(dex_files);
311  compiler_driver_->CompileAll(class_loader, dex_files, &timings);
312
313  ScratchFile tmp;
314  SafeMap<std::string, std::string> key_value_store;
315  key_value_store.Put(OatHeader::kImageLocationKey, "test.art");
316  bool success = WriteElf(tmp.GetFile(), dex_files, key_value_store);
317  ASSERT_TRUE(success);
318
319  std::unique_ptr<OatFile> oat_file(OatFile::Open(tmp.GetFilename(),
320                                                  tmp.GetFilename(),
321                                                  nullptr,
322                                                  nullptr,
323                                                  false,
324                                                  nullptr,
325                                                  &error_msg));
326  ASSERT_TRUE(oat_file != nullptr);
327  EXPECT_LT(static_cast<size_t>(oat_file->Size()), static_cast<size_t>(tmp.GetFile()->GetLength()));
328}
329
330}  // namespace art
331