dex2oat.cc revision 3029df6d212894647ba0e5c23443c40912c6ecc8
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 <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
20#include <valgrind.h>
21
22#include <fstream>
23#include <iostream>
24#include <malloc.h>  // For mallinfo
25#include <sstream>
26#include <string>
27#include <vector>
28
29#if defined(__linux__) && defined(__arm__)
30#include <sys/personality.h>
31#include <sys/utsname.h>
32#endif
33
34#include "base/stl_util.h"
35#include "base/stringpiece.h"
36#include "base/timing_logger.h"
37#include "base/unix_file/fd_file.h"
38#include "class_linker.h"
39#include "compiler.h"
40#include "compiler_callbacks.h"
41#include "dex_file-inl.h"
42#include "dex/pass_driver_me_opts.h"
43#include "dex/verification_results.h"
44#include "dex/quick_compiler_callbacks.h"
45#include "dex/quick/dex_file_to_method_inliner_map.h"
46#include "driver/compiler_driver.h"
47#include "driver/compiler_options.h"
48#include "elf_fixup.h"
49#include "elf_patcher.h"
50#include "elf_stripper.h"
51#include "gc/space/image_space.h"
52#include "gc/space/space-inl.h"
53#include "image_writer.h"
54#include "leb128.h"
55#include "mirror/art_method-inl.h"
56#include "mirror/class-inl.h"
57#include "mirror/class_loader.h"
58#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
60#include "oat_writer.h"
61#include "os.h"
62#include "runtime.h"
63#include "ScopedLocalRef.h"
64#include "scoped_thread_state_change.h"
65#include "utils.h"
66#include "vector_output_stream.h"
67#include "well_known_classes.h"
68#include "zip_archive.h"
69
70namespace art {
71
72static int original_argc;
73static char** original_argv;
74
75static std::string CommandLine() {
76  std::vector<std::string> command;
77  for (int i = 0; i < original_argc; ++i) {
78    command.push_back(original_argv[i]);
79  }
80  return Join(command, ' ');
81}
82
83static void UsageErrorV(const char* fmt, va_list ap) {
84  std::string error;
85  StringAppendV(&error, fmt, ap);
86  LOG(ERROR) << error;
87}
88
89static void UsageError(const char* fmt, ...) {
90  va_list ap;
91  va_start(ap, fmt);
92  UsageErrorV(fmt, ap);
93  va_end(ap);
94}
95
96static void Usage(const char* fmt, ...) {
97  va_list ap;
98  va_start(ap, fmt);
99  UsageErrorV(fmt, ap);
100  va_end(ap);
101
102  UsageError("Command: %s", CommandLine().c_str());
103
104  UsageError("Usage: dex2oat [options]...");
105  UsageError("");
106  UsageError("  --dex-file=<dex-file>: specifies a .dex file to compile.");
107  UsageError("      Example: --dex-file=/system/framework/core.jar");
108  UsageError("");
109  UsageError("  --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
110  UsageError("      containing a classes.dex file to compile.");
111  UsageError("      Example: --zip-fd=5");
112  UsageError("");
113  UsageError("  --zip-location=<zip-location>: specifies a symbolic name for the file");
114  UsageError("      corresponding to the file descriptor specified by --zip-fd.");
115  UsageError("      Example: --zip-location=/system/app/Calculator.apk");
116  UsageError("");
117  UsageError("  --oat-file=<file.oat>: specifies the oat output destination via a filename.");
118  UsageError("      Example: --oat-file=/system/framework/boot.oat");
119  UsageError("");
120  UsageError("  --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
121  UsageError("      Example: --oat-fd=6");
122  UsageError("");
123  UsageError("  --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
124  UsageError("      to the file descriptor specified by --oat-fd.");
125  UsageError("      Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
126  UsageError("");
127  UsageError("  --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
128  UsageError("      Example: --oat-symbols=/symbols/system/framework/boot.oat");
129  UsageError("");
130  UsageError("  --bitcode=<file.bc>: specifies the optional bitcode filename.");
131  UsageError("      Example: --bitcode=/system/framework/boot.bc");
132  UsageError("");
133  UsageError("  --image=<file.art>: specifies the output image filename.");
134  UsageError("      Example: --image=/system/framework/boot.art");
135  UsageError("");
136  UsageError("  --image-classes=<classname-file>: specifies classes to include in an image.");
137  UsageError("      Example: --image=frameworks/base/preloaded-classes");
138  UsageError("");
139  UsageError("  --base=<hex-address>: specifies the base address when creating a boot image.");
140  UsageError("      Example: --base=0x50000000");
141  UsageError("");
142  UsageError("  --boot-image=<file.art>: provide the image file for the boot class path.");
143  UsageError("      Example: --boot-image=/system/framework/boot.art");
144  UsageError("      Default: $ANDROID_ROOT/system/framework/boot.art");
145  UsageError("");
146  UsageError("  --android-root=<path>: used to locate libraries for portable linking.");
147  UsageError("      Example: --android-root=out/host/linux-x86");
148  UsageError("      Default: $ANDROID_ROOT");
149  UsageError("");
150  UsageError("  --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
151  UsageError("      instruction set.");
152  UsageError("      Example: --instruction-set=x86");
153  UsageError("      Default: arm");
154  UsageError("");
155  UsageError("  --instruction-set-features=...,: Specify instruction set features");
156  UsageError("      Example: --instruction-set-features=div");
157  UsageError("      Default: default");
158  UsageError("");
159  UsageError("  --compile-pic: Force indirect use of code, methods, and classes");
160  UsageError("      Default: disabled");
161  UsageError("");
162  UsageError("  --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
163  UsageError("      set.");
164  UsageError("      Example: --compiler-backend=Portable");
165  UsageError("      Default: Quick");
166  UsageError("");
167  UsageError("  --compiler-filter=(verify-none|interpret-only|space|balanced|speed|everything):");
168  UsageError("      select compiler filter.");
169  UsageError("      Example: --compiler-filter=everything");
170#if ART_SMALL_MODE
171  UsageError("      Default: interpret-only");
172#else
173  UsageError("      Default: speed");
174#endif
175  UsageError("");
176  UsageError("  --huge-method-max=<method-instruction-count>: the threshold size for a huge");
177  UsageError("      method for compiler filter tuning.");
178  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
179  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
180  UsageError("");
181  UsageError("  --huge-method-max=<method-instruction-count>: threshold size for a huge");
182  UsageError("      method for compiler filter tuning.");
183  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
184  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
185  UsageError("");
186  UsageError("  --large-method-max=<method-instruction-count>: threshold size for a large");
187  UsageError("      method for compiler filter tuning.");
188  UsageError("      Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
189  UsageError("      Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
190  UsageError("");
191  UsageError("  --small-method-max=<method-instruction-count>: threshold size for a small");
192  UsageError("      method for compiler filter tuning.");
193  UsageError("      Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
194  UsageError("      Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
195  UsageError("");
196  UsageError("  --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
197  UsageError("      method for compiler filter tuning.");
198  UsageError("      Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
199  UsageError("      Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
200  UsageError("");
201  UsageError("  --num-dex-methods=<method-count>: threshold size for a small dex file for");
202  UsageError("      compiler filter tuning. If the input has fewer than this many methods");
203  UsageError("      and the filter is not interpret-only or verify-none, overrides the");
204  UsageError("      filter to use speed");
205  UsageError("      Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
206  UsageError("      Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
207  UsageError("");
208  UsageError("  --host: used with Portable backend to link against host runtime libraries");
209  UsageError("");
210  UsageError("  --dump-timing: display a breakdown of where time was spent");
211  UsageError("");
212  UsageError("  --include-patch-information: Include patching information so the generated code");
213  UsageError("      can have its base address moved without full recompilation.");
214  UsageError("");
215  UsageError("  --no-include-patch-information: Do not include patching information.");
216  UsageError("");
217  UsageError("  --include-debug-symbols: Include ELF symbols in this oat file");
218  UsageError("");
219  UsageError("  --no-include-debug-symbols: Do not include ELF symbols in this oat file");
220  UsageError("");
221  UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
222  UsageError("      such as initial heap size, maximum heap size, and verbose output.");
223  UsageError("      Use a separate --runtime-arg switch for each argument.");
224  UsageError("      Example: --runtime-arg -Xms256m");
225  UsageError("");
226  UsageError("  --profile-file=<filename>: specify profiler output file to use for compilation.");
227  UsageError("");
228  UsageError("  --print-pass-names: print a list of pass names");
229  UsageError("");
230  UsageError("  --disable-passes=<pass-names>:  disable one or more passes separated by comma.");
231  UsageError("      Example: --disable-passes=UseCount,BBOptimizations");
232  UsageError("");
233  std::cerr << "See log for usage error information\n";
234  exit(EXIT_FAILURE);
235}
236
237class Dex2Oat {
238 public:
239  static bool Create(Dex2Oat** p_dex2oat,
240                     const RuntimeOptions& runtime_options,
241                     const CompilerOptions& compiler_options,
242                     Compiler::Kind compiler_kind,
243                     InstructionSet instruction_set,
244                     InstructionSetFeatures instruction_set_features,
245                     VerificationResults* verification_results,
246                     DexFileToMethodInlinerMap* method_inliner_map,
247                     size_t thread_count)
248      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
249    CHECK(verification_results != nullptr);
250    CHECK(method_inliner_map != nullptr);
251    std::unique_ptr<Dex2Oat> dex2oat(new Dex2Oat(&compiler_options,
252                                           compiler_kind,
253                                           instruction_set,
254                                           instruction_set_features,
255                                           verification_results,
256                                           method_inliner_map,
257                                           thread_count));
258    if (!dex2oat->CreateRuntime(runtime_options, instruction_set)) {
259      *p_dex2oat = nullptr;
260      return false;
261    }
262    *p_dex2oat = dex2oat.release();
263    return true;
264  }
265
266  ~Dex2Oat() {
267    delete runtime_;
268  }
269
270  void LogCompletionTime(const CompilerDriver* compiler) {
271    std::ostringstream mallinfostr;
272#ifdef HAVE_MALLOC_H
273    struct mallinfo info = mallinfo();
274    const size_t allocated_space = static_cast<size_t>(info.uordblks);
275    const size_t free_space = static_cast<size_t>(info.fordblks);
276    mallinfostr << " native alloc=" << PrettySize(allocated_space) << " free="
277        << PrettySize(free_space);
278#endif
279    const ArenaPool* arena_pool = compiler->GetArenaPool();
280    gc::Heap* heap = Runtime::Current()->GetHeap();
281    LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
282              << " (threads: " << thread_count_ << ")"
283              << " arena alloc=" << PrettySize(arena_pool->GetBytesAllocated())
284              << " java alloc=" << PrettySize(heap->GetBytesAllocated()) << mallinfostr.str();
285  }
286
287
288  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
289  std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
290    std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
291                                                                  std::ifstream::in));
292    if (image_classes_file.get() == nullptr) {
293      LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
294      return nullptr;
295    }
296    std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
297    image_classes_file->close();
298    return result.release();
299  }
300
301  std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
302    std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
303    while (image_classes_stream.good()) {
304      std::string dot;
305      std::getline(image_classes_stream, dot);
306      if (StartsWith(dot, "#") || dot.empty()) {
307        continue;
308      }
309      std::string descriptor(DotToDescriptor(dot.c_str()));
310      image_classes->insert(descriptor);
311    }
312    return image_classes.release();
313  }
314
315  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
316  std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
317                                                         const char* image_classes_filename,
318                                                         std::string* error_msg) {
319    std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
320    if (zip_archive.get() == nullptr) {
321      return nullptr;
322    }
323    std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
324    if (zip_entry.get() == nullptr) {
325      *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
326                                zip_filename, error_msg->c_str());
327      return nullptr;
328    }
329    std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
330                                                                          image_classes_filename,
331                                                                          error_msg));
332    if (image_classes_file.get() == nullptr) {
333      *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
334                                zip_filename, error_msg->c_str());
335      return nullptr;
336    }
337    const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
338                                           image_classes_file->Size());
339    std::istringstream image_classes_stream(image_classes_string);
340    return ReadImageClasses(image_classes_stream);
341  }
342
343  bool PatchOatCode(const CompilerDriver* compiler_driver, File* oat_file,
344                    const std::string& oat_location, std::string* error_msg) {
345    // We asked to include patch information but we are not making an image. We need to fix
346    // everything up manually.
347    std::unique_ptr<ElfFile> elf_file(ElfFile::Open(oat_file, PROT_READ|PROT_WRITE,
348                                                    MAP_SHARED, error_msg));
349    if (elf_file.get() == NULL) {
350      LOG(ERROR) << error_msg;
351      return false;
352    }
353    {
354      ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
355      return ElfPatcher::Patch(compiler_driver, elf_file.get(), oat_location, error_msg);
356    }
357  }
358
359  const CompilerDriver* CreateOatFile(const std::string& boot_image_option,
360                                      const std::string& android_root,
361                                      bool is_host,
362                                      const std::vector<const DexFile*>& dex_files,
363                                      File* oat_file,
364                                      const std::string& oat_location,
365                                      const std::string& bitcode_filename,
366                                      bool image,
367                                      std::unique_ptr<std::set<std::string>>& image_classes,
368                                      std::unique_ptr<std::set<std::string>>& compiled_classes,
369                                      bool dump_stats,
370                                      bool dump_passes,
371                                      TimingLogger& timings,
372                                      CumulativeLogger& compiler_phases_timings,
373                                      std::string profile_file,
374                                      SafeMap<std::string, std::string>* key_value_store) {
375    CHECK(key_value_store != nullptr);
376
377    // Handle and ClassLoader creation needs to come after Runtime::Create
378    jobject class_loader = nullptr;
379    Thread* self = Thread::Current();
380    if (!boot_image_option.empty()) {
381      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
382      std::vector<const DexFile*> class_path_files(dex_files);
383      OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
384      ScopedObjectAccess soa(self);
385      for (size_t i = 0; i < class_path_files.size(); i++) {
386        class_linker->RegisterDexFile(*class_path_files[i]);
387      }
388      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
389      ScopedLocalRef<jobject> class_loader_local(soa.Env(),
390          soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
391      class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
392      Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
393    }
394
395    std::unique_ptr<CompilerDriver> driver(new CompilerDriver(compiler_options_,
396                                                              verification_results_,
397                                                              method_inliner_map_,
398                                                              compiler_kind_,
399                                                              instruction_set_,
400                                                              instruction_set_features_,
401                                                              image,
402                                                              image_classes.release(),
403                                                              compiled_classes.release(),
404                                                              thread_count_,
405                                                              dump_stats,
406                                                              dump_passes,
407                                                              &compiler_phases_timings,
408                                                              profile_file));
409
410    driver->GetCompiler()->SetBitcodeFileName(*driver.get(), bitcode_filename);
411
412    driver->CompileAll(class_loader, dex_files, &timings);
413
414    TimingLogger::ScopedTiming t2("dex2oat OatWriter", &timings);
415    std::string image_file_location;
416    uint32_t image_file_location_oat_checksum = 0;
417    uintptr_t image_file_location_oat_data_begin = 0;
418    int32_t image_patch_delta = 0;
419    if (!driver->IsImage()) {
420      TimingLogger::ScopedTiming t3("Loading image checksum", &timings);
421      gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
422      image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
423      image_file_location_oat_data_begin =
424          reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
425      image_file_location = image_space->GetImageFilename();
426      image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
427    }
428
429    if (!image_file_location.empty()) {
430      key_value_store->Put(OatHeader::kImageLocationKey, image_file_location);
431    }
432
433    OatWriter oat_writer(dex_files, image_file_location_oat_checksum,
434                         image_file_location_oat_data_begin,
435                         image_patch_delta,
436                         driver.get(),
437                         &timings,
438                         key_value_store);
439
440    t2.NewTiming("Writing ELF");
441    if (!driver->WriteElf(android_root, is_host, dex_files, &oat_writer, oat_file)) {
442      LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
443      return nullptr;
444    }
445
446    // Flush result to disk. Patching code will re-open the file (mmap), so ensure that our view
447    // of the file already made it there and won't be re-ordered with writes from PatchOat or
448    // image patching.
449    if (oat_file->Flush() != 0) {
450      PLOG(ERROR) << "Failed flushing oat file " << oat_file->GetPath();
451      oat_file->Erase();
452      return nullptr;
453    }
454
455    if (!driver->IsImage() && driver->GetCompilerOptions().GetIncludePatchInformation()) {
456      t2.NewTiming("Patching ELF");
457      std::string error_msg;
458      if (!PatchOatCode(driver.get(), oat_file, oat_location, &error_msg)) {
459        LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath() << ": " << error_msg;
460        return nullptr;
461      }
462    }
463
464    return driver.release();
465  }
466
467  bool CreateImageFile(const std::string& image_filename,
468                       uintptr_t image_base,
469                       const std::string& oat_filename,
470                       const std::string& oat_location,
471                       const CompilerDriver& compiler)
472      LOCKS_EXCLUDED(Locks::mutator_lock_) {
473    uintptr_t oat_data_begin;
474    {
475      // ImageWriter is scoped so it can free memory before doing FixupElf
476      ImageWriter image_writer(compiler);
477      if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location,
478                              compiler_options_->GetCompilePic())) {
479        LOG(ERROR) << "Failed to create image file " << image_filename;
480        return false;
481      }
482      oat_data_begin = image_writer.GetOatDataBegin();
483    }
484
485
486    // Do not fix up the ELF file if we are --compile-pic
487    if (!compiler_options_->GetCompilePic()) {
488      std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
489      if (oat_file.get() == nullptr) {
490        PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
491        return false;
492      }
493
494      if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) {
495        LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
496        oat_file->Erase();
497        return false;
498      }
499
500      if (oat_file->FlushCloseOrErase() != 0) {
501        PLOG(ERROR) << "Failed to flush and close patched oat file " << oat_filename;
502        return false;
503      }
504    }
505
506    return true;
507  }
508
509 private:
510  explicit Dex2Oat(const CompilerOptions* compiler_options,
511                   Compiler::Kind compiler_kind,
512                   InstructionSet instruction_set,
513                   InstructionSetFeatures instruction_set_features,
514                   VerificationResults* verification_results,
515                   DexFileToMethodInlinerMap* method_inliner_map,
516                   size_t thread_count)
517      : compiler_options_(compiler_options),
518        compiler_kind_(compiler_kind),
519        instruction_set_(instruction_set),
520        instruction_set_features_(instruction_set_features),
521        verification_results_(verification_results),
522        method_inliner_map_(method_inliner_map),
523        runtime_(nullptr),
524        thread_count_(thread_count),
525        start_ns_(NanoTime()) {
526    CHECK(compiler_options != nullptr);
527    CHECK(verification_results != nullptr);
528    CHECK(method_inliner_map != nullptr);
529  }
530
531  bool CreateRuntime(const RuntimeOptions& runtime_options, InstructionSet instruction_set)
532      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
533    if (!Runtime::Create(runtime_options, false)) {
534      LOG(ERROR) << "Failed to create runtime";
535      return false;
536    }
537    Runtime* runtime = Runtime::Current();
538    runtime->SetInstructionSet(instruction_set);
539    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
540      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
541      if (!runtime->HasCalleeSaveMethod(type)) {
542        runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(type), type);
543      }
544    }
545    runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
546    runtime->GetClassLinker()->RunRootClinits();
547    runtime_ = runtime;
548    return true;
549  }
550
551  // Appends to dex_files any elements of class_path that it doesn't already
552  // contain. This will open those dex files as necessary.
553  static void OpenClassPathFiles(const std::string& class_path,
554                                 std::vector<const DexFile*>& dex_files) {
555    std::vector<std::string> parsed;
556    Split(class_path, ':', parsed);
557    // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
558    ScopedObjectAccess soa(Thread::Current());
559    for (size_t i = 0; i < parsed.size(); ++i) {
560      if (DexFilesContains(dex_files, parsed[i])) {
561        continue;
562      }
563      std::string error_msg;
564      if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
565        LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
566      }
567    }
568  }
569
570  // Returns true if dex_files has a dex with the named location.
571  static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
572                               const std::string& location) {
573    for (size_t i = 0; i < dex_files.size(); ++i) {
574      if (dex_files[i]->GetLocation() == location) {
575        return true;
576      }
577    }
578    return false;
579  }
580
581  const CompilerOptions* const compiler_options_;
582  const Compiler::Kind compiler_kind_;
583
584  const InstructionSet instruction_set_;
585  const InstructionSetFeatures instruction_set_features_;
586
587  VerificationResults* const verification_results_;
588  DexFileToMethodInlinerMap* const method_inliner_map_;
589  Runtime* runtime_;
590  size_t thread_count_;
591  uint64_t start_ns_;
592
593  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
594};
595
596static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
597                           const std::vector<const char*>& dex_locations,
598                           std::vector<const DexFile*>& dex_files) {
599  size_t failure_count = 0;
600  for (size_t i = 0; i < dex_filenames.size(); i++) {
601    const char* dex_filename = dex_filenames[i];
602    const char* dex_location = dex_locations[i];
603    ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
604    std::string error_msg;
605    if (!OS::FileExists(dex_filename)) {
606      LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
607      continue;
608    }
609    if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
610      LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
611      ++failure_count;
612    }
613    ATRACE_END();
614  }
615  return failure_count;
616}
617
618// The primary goal of the watchdog is to prevent stuck build servers
619// during development when fatal aborts lead to a cascade of failures
620// that result in a deadlock.
621class WatchDog {
622// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
623#undef CHECK_PTHREAD_CALL
624#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
625  do { \
626    int rc = call args; \
627    if (rc != 0) { \
628      errno = rc; \
629      std::string message(# call); \
630      message += " failed for "; \
631      message += reason; \
632      Fatal(message); \
633    } \
634  } while (false)
635
636 public:
637  explicit WatchDog(bool is_watch_dog_enabled) {
638    is_watch_dog_enabled_ = is_watch_dog_enabled;
639    if (!is_watch_dog_enabled_) {
640      return;
641    }
642    shutting_down_ = false;
643    const char* reason = "dex2oat watch dog thread startup";
644    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
645    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
646    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
647    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
648    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
649  }
650  ~WatchDog() {
651    if (!is_watch_dog_enabled_) {
652      return;
653    }
654    const char* reason = "dex2oat watch dog thread shutdown";
655    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
656    shutting_down_ = true;
657    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
658    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
659
660    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
661
662    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
663    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
664  }
665
666 private:
667  static void* CallBack(void* arg) {
668    WatchDog* self = reinterpret_cast<WatchDog*>(arg);
669    ::art::SetThreadName("dex2oat watch dog");
670    self->Wait();
671    return nullptr;
672  }
673
674  static void Message(char severity, const std::string& message) {
675    // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
676    //       cases.
677    fprintf(stderr, "dex2oat%s %c %d %d %s\n",
678            kIsDebugBuild ? "d" : "",
679            severity,
680            getpid(),
681            GetTid(),
682            message.c_str());
683  }
684
685  static void Warn(const std::string& message) {
686    Message('W', message);
687  }
688
689  static void Fatal(const std::string& message) {
690    Message('F', message);
691    exit(1);
692  }
693
694  void Wait() {
695    bool warning = true;
696    CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
697    // TODO: tune the multiplier for GC verification, the following is just to make the timeout
698    //       large.
699    int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
700    timespec warning_ts;
701    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
702    timespec timeout_ts;
703    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
704    const char* reason = "dex2oat watch dog thread waiting";
705    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
706    while (!shutting_down_) {
707      int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
708                                                         warning ? &warning_ts
709                                                                 : &timeout_ts));
710      if (rc == ETIMEDOUT) {
711        std::string message(StringPrintf("dex2oat did not finish after %d seconds",
712                                         warning ? kWatchDogWarningSeconds
713                                                 : kWatchDogTimeoutSeconds));
714        if (warning) {
715          Warn(message.c_str());
716          warning = false;
717        } else {
718          Fatal(message.c_str());
719        }
720      } else if (rc != 0) {
721        std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
722                                         strerror(errno)));
723        Fatal(message.c_str());
724      }
725    }
726    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
727  }
728
729  // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
730  // Debug builds are slower so they have larger timeouts.
731  static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
732#if ART_USE_PORTABLE_COMPILER
733  // 2 minutes scaled by kSlowdownFactor.
734  static const unsigned int kWatchDogWarningSeconds = kSlowdownFactor * 2 * 60;
735  // 30 minutes scaled by kSlowdownFactor.
736  static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 30 * 60;
737#else
738  // 1 minutes scaled by kSlowdownFactor.
739  static const unsigned int kWatchDogWarningSeconds = kSlowdownFactor * 1 * 60;
740  // 6 minutes scaled by kSlowdownFactor.
741  static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
742#endif
743
744  bool is_watch_dog_enabled_;
745  bool shutting_down_;
746  // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
747  pthread_mutex_t mutex_;
748  pthread_cond_t cond_;
749  pthread_attr_t attr_;
750  pthread_t pthread_;
751};
752const unsigned int WatchDog::kWatchDogWarningSeconds;
753const unsigned int WatchDog::kWatchDogTimeoutSeconds;
754
755// Given a set of instruction features from the build, parse it.  The
756// input 'str' is a comma separated list of feature names.  Parse it and
757// return the InstructionSetFeatures object.
758static InstructionSetFeatures ParseFeatureList(std::string str) {
759  InstructionSetFeatures result;
760  typedef std::vector<std::string> FeatureList;
761  FeatureList features;
762  Split(str, ',', features);
763  for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
764    std::string feature = Trim(*i);
765    if (feature == "default") {
766      // Nothing to do.
767    } else if (feature == "div") {
768      // Supports divide instruction.
769       result.SetHasDivideInstruction(true);
770    } else if (feature == "nodiv") {
771      // Turn off support for divide instruction.
772      result.SetHasDivideInstruction(false);
773    } else if (feature == "lpae") {
774      // Supports Large Physical Address Extension.
775      result.SetHasLpae(true);
776    } else if (feature == "nolpae") {
777      // Turn off support for Large Physical Address Extension.
778      result.SetHasLpae(false);
779    } else {
780      Usage("Unknown instruction set feature: '%s'", feature.c_str());
781    }
782  }
783  // others...
784  return result;
785}
786
787void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
788  std::string::size_type colon = s.find(c);
789  if (colon == std::string::npos) {
790    Usage("Missing char %c in option %s\n", c, s.c_str());
791  }
792  // Add one to remove the char we were trimming until.
793  *parsed_value = s.substr(colon + 1);
794}
795
796void ParseDouble(const std::string& option, char after_char,
797                 double min, double max, double* parsed_value) {
798  std::string substring;
799  ParseStringAfterChar(option, after_char, &substring);
800  bool sane_val = true;
801  double value;
802  if (false) {
803    // TODO: this doesn't seem to work on the emulator.  b/15114595
804    std::stringstream iss(substring);
805    iss >> value;
806    // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
807    sane_val = iss.eof() && (value >= min) && (value <= max);
808  } else {
809    char* end = nullptr;
810    value = strtod(substring.c_str(), &end);
811    sane_val = *end == '\0' && value >= min && value <= max;
812  }
813  if (!sane_val) {
814    Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
815  }
816  *parsed_value = value;
817}
818
819static void b13564922() {
820#if defined(__linux__) && defined(__arm__)
821  int major, minor;
822  struct utsname uts;
823  if (uname(&uts) != -1 &&
824      sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
825      ((major < 3) || ((major == 3) && (minor < 4)))) {
826    // Kernels before 3.4 don't handle the ASLR well and we can run out of address
827    // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
828    int old_personality = personality(0xffffffff);
829    if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
830      int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
831      if (new_personality == -1) {
832        LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
833      }
834    }
835  }
836#endif
837}
838
839static int dex2oat(int argc, char** argv) {
840  b13564922();
841
842  original_argc = argc;
843  original_argv = argv;
844
845  TimingLogger timings("compiler", false, false);
846  CumulativeLogger compiler_phases_timings("compilation times");
847
848  InitLogging(argv);
849
850  // Skip over argv[0].
851  argv++;
852  argc--;
853
854  if (argc == 0) {
855    Usage("No arguments specified");
856  }
857
858  std::vector<const char*> dex_filenames;
859  std::vector<const char*> dex_locations;
860  int zip_fd = -1;
861  std::string zip_location;
862  std::string oat_filename;
863  std::string oat_symbols;
864  std::string oat_location;
865  int oat_fd = -1;
866  std::string bitcode_filename;
867  const char* image_classes_zip_filename = nullptr;
868  const char* image_classes_filename = nullptr;
869  const char* compiled_classes_zip_filename = nullptr;
870  const char* compiled_classes_filename = nullptr;
871  std::string image_filename;
872  std::string boot_image_filename;
873  uintptr_t image_base = 0;
874  std::string android_root;
875  std::vector<const char*> runtime_args;
876  int thread_count = sysconf(_SC_NPROCESSORS_CONF);
877  Compiler::Kind compiler_kind = kUsePortableCompiler
878      ? Compiler::kPortable
879      : Compiler::kQuick;
880  const char* compiler_filter_string = nullptr;
881  bool compile_pic = false;
882  int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
883  int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
884  int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
885  int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
886  int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
887
888  // Take the default set of instruction features from the build.
889  InstructionSetFeatures instruction_set_features =
890      ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
891
892  InstructionSet instruction_set = kRuntimeISA;
893
894  // Profile file to use
895  std::string profile_file;
896  double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
897
898  bool is_host = false;
899  bool dump_stats = false;
900  bool dump_timing = false;
901  bool dump_passes = false;
902  bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
903  bool include_debug_symbols = kIsDebugBuild;
904  bool dump_slow_timing = kIsDebugBuild;
905  bool watch_dog_enabled = true;
906  bool generate_gdb_information = kIsDebugBuild;
907
908  // Checks are all explicit until we know the architecture.
909  bool implicit_null_checks = false;
910  bool implicit_so_checks = false;
911  bool implicit_suspend_checks = false;
912
913  for (int i = 0; i < argc; i++) {
914    const StringPiece option(argv[i]);
915    const bool log_options = false;
916    if (log_options) {
917      LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
918    }
919    if (option.starts_with("--dex-file=")) {
920      dex_filenames.push_back(option.substr(strlen("--dex-file=")).data());
921    } else if (option.starts_with("--dex-location=")) {
922      dex_locations.push_back(option.substr(strlen("--dex-location=")).data());
923    } else if (option.starts_with("--zip-fd=")) {
924      const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
925      if (!ParseInt(zip_fd_str, &zip_fd)) {
926        Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
927      }
928      if (zip_fd < 0) {
929        Usage("--zip-fd passed a negative value %d", zip_fd);
930      }
931    } else if (option.starts_with("--zip-location=")) {
932      zip_location = option.substr(strlen("--zip-location=")).data();
933    } else if (option.starts_with("--oat-file=")) {
934      oat_filename = option.substr(strlen("--oat-file=")).data();
935    } else if (option.starts_with("--oat-symbols=")) {
936      oat_symbols = option.substr(strlen("--oat-symbols=")).data();
937    } else if (option.starts_with("--oat-fd=")) {
938      const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
939      if (!ParseInt(oat_fd_str, &oat_fd)) {
940        Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
941      }
942      if (oat_fd < 0) {
943        Usage("--oat-fd passed a negative value %d", oat_fd);
944      }
945    } else if (option == "--watch-dog") {
946      watch_dog_enabled = true;
947    } else if (option == "--no-watch-dog") {
948      watch_dog_enabled = false;
949    } else if (option == "--gen-gdb-info") {
950      generate_gdb_information = true;
951      // Debug symbols are needed for gdb information.
952      include_debug_symbols = true;
953    } else if (option == "--no-gen-gdb-info") {
954      generate_gdb_information = false;
955    } else if (option.starts_with("-j")) {
956      const char* thread_count_str = option.substr(strlen("-j")).data();
957      if (!ParseInt(thread_count_str, &thread_count)) {
958        Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
959      }
960    } else if (option.starts_with("--oat-location=")) {
961      oat_location = option.substr(strlen("--oat-location=")).data();
962    } else if (option.starts_with("--bitcode=")) {
963      bitcode_filename = option.substr(strlen("--bitcode=")).data();
964    } else if (option.starts_with("--image=")) {
965      image_filename = option.substr(strlen("--image=")).data();
966    } else if (option.starts_with("--image-classes=")) {
967      image_classes_filename = option.substr(strlen("--image-classes=")).data();
968    } else if (option.starts_with("--image-classes-zip=")) {
969      image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data();
970    } else if (option.starts_with("--compiled-classes=")) {
971      compiled_classes_filename = option.substr(strlen("--compiled-classes=")).data();
972    } else if (option.starts_with("--compiled-classes-zip=")) {
973      compiled_classes_zip_filename = option.substr(strlen("--compiled-classes-zip=")).data();
974    } else if (option.starts_with("--base=")) {
975      const char* image_base_str = option.substr(strlen("--base=")).data();
976      char* end;
977      image_base = strtoul(image_base_str, &end, 16);
978      if (end == image_base_str || *end != '\0') {
979        Usage("Failed to parse hexadecimal value for option %s", option.data());
980      }
981    } else if (option.starts_with("--boot-image=")) {
982      boot_image_filename = option.substr(strlen("--boot-image=")).data();
983    } else if (option.starts_with("--android-root=")) {
984      android_root = option.substr(strlen("--android-root=")).data();
985    } else if (option.starts_with("--instruction-set=")) {
986      StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
987      if (instruction_set_str == "arm") {
988        instruction_set = kThumb2;
989      } else if (instruction_set_str == "arm64") {
990        instruction_set = kArm64;
991      } else if (instruction_set_str == "mips") {
992        instruction_set = kMips;
993      } else if (instruction_set_str == "x86") {
994        instruction_set = kX86;
995      } else if (instruction_set_str == "x86_64") {
996        instruction_set = kX86_64;
997      }
998    } else if (option.starts_with("--instruction-set-features=")) {
999      StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
1000      instruction_set_features = ParseFeatureList(str.as_string());
1001    } else if (option.starts_with("--compiler-backend=")) {
1002      StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
1003      if (backend_str == "Quick") {
1004        compiler_kind = Compiler::kQuick;
1005      } else if (backend_str == "Optimizing") {
1006        compiler_kind = Compiler::kOptimizing;
1007      } else if (backend_str == "Portable") {
1008        compiler_kind = Compiler::kPortable;
1009      }
1010    } else if (option.starts_with("--compiler-filter=")) {
1011      compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
1012    } else if (option == "--compile-pic") {
1013      compile_pic = true;
1014    } else if (option.starts_with("--huge-method-max=")) {
1015      const char* threshold = option.substr(strlen("--huge-method-max=")).data();
1016      if (!ParseInt(threshold, &huge_method_threshold)) {
1017        Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
1018      }
1019      if (huge_method_threshold < 0) {
1020        Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
1021      }
1022    } else if (option.starts_with("--large-method-max=")) {
1023      const char* threshold = option.substr(strlen("--large-method-max=")).data();
1024      if (!ParseInt(threshold, &large_method_threshold)) {
1025        Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
1026      }
1027      if (large_method_threshold < 0) {
1028        Usage("--large-method-max passed a negative value %s", large_method_threshold);
1029      }
1030    } else if (option.starts_with("--small-method-max=")) {
1031      const char* threshold = option.substr(strlen("--small-method-max=")).data();
1032      if (!ParseInt(threshold, &small_method_threshold)) {
1033        Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
1034      }
1035      if (small_method_threshold < 0) {
1036        Usage("--small-method-max passed a negative value %s", small_method_threshold);
1037      }
1038    } else if (option.starts_with("--tiny-method-max=")) {
1039      const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
1040      if (!ParseInt(threshold, &tiny_method_threshold)) {
1041        Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
1042      }
1043      if (tiny_method_threshold < 0) {
1044        Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
1045      }
1046    } else if (option.starts_with("--num-dex-methods=")) {
1047      const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
1048      if (!ParseInt(threshold, &num_dex_methods_threshold)) {
1049        Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
1050      }
1051      if (num_dex_methods_threshold < 0) {
1052        Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
1053      }
1054    } else if (option == "--host") {
1055      is_host = true;
1056    } else if (option == "--runtime-arg") {
1057      if (++i >= argc) {
1058        Usage("Missing required argument for --runtime-arg");
1059      }
1060      if (log_options) {
1061        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1062      }
1063      runtime_args.push_back(argv[i]);
1064    } else if (option == "--dump-timing") {
1065      dump_timing = true;
1066    } else if (option == "--dump-passes") {
1067      dump_passes = true;
1068    } else if (option == "--dump-stats") {
1069      dump_stats = true;
1070    } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
1071      include_debug_symbols = true;
1072    } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
1073      include_debug_symbols = false;
1074      generate_gdb_information = false;  // Depends on debug symbols, see above.
1075    } else if (option.starts_with("--profile-file=")) {
1076      profile_file = option.substr(strlen("--profile-file=")).data();
1077      VLOG(compiler) << "dex2oat: profile file is " << profile_file;
1078    } else if (option == "--no-profile-file") {
1079      // No profile
1080    } else if (option.starts_with("--top-k-profile-threshold=")) {
1081      ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
1082    } else if (option == "--print-pass-names") {
1083      PassDriverMEOpts::PrintPassNames();
1084    } else if (option.starts_with("--disable-passes=")) {
1085      std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
1086      PassDriverMEOpts::CreateDefaultPassList(disable_passes);
1087    } else if (option.starts_with("--print-passes=")) {
1088      std::string print_passes = option.substr(strlen("--print-passes=")).data();
1089      PassDriverMEOpts::SetPrintPassList(print_passes);
1090    } else if (option == "--print-all-passes") {
1091      PassDriverMEOpts::SetPrintAllPasses();
1092    } else if (option.starts_with("--dump-cfg-passes=")) {
1093      std::string dump_passes = option.substr(strlen("--dump-cfg-passes=")).data();
1094      PassDriverMEOpts::SetDumpPassList(dump_passes);
1095    } else if (option == "--include-patch-information") {
1096      include_patch_information = true;
1097    } else if (option == "--no-include-patch-information") {
1098      include_patch_information = false;
1099    } else {
1100      Usage("Unknown argument %s", option.data());
1101    }
1102  }
1103
1104  if (oat_filename.empty() && oat_fd == -1) {
1105    Usage("Output must be supplied with either --oat-file or --oat-fd");
1106  }
1107
1108  if (!oat_filename.empty() && oat_fd != -1) {
1109    Usage("--oat-file should not be used with --oat-fd");
1110  }
1111
1112  if (!oat_symbols.empty() && oat_fd != -1) {
1113    Usage("--oat-symbols should not be used with --oat-fd");
1114  }
1115
1116  if (!oat_symbols.empty() && is_host) {
1117    Usage("--oat-symbols should not be used with --host");
1118  }
1119
1120  if (oat_fd != -1 && !image_filename.empty()) {
1121    Usage("--oat-fd should not be used with --image");
1122  }
1123
1124  if (android_root.empty()) {
1125    const char* android_root_env_var = getenv("ANDROID_ROOT");
1126    if (android_root_env_var == nullptr) {
1127      Usage("--android-root unspecified and ANDROID_ROOT not set");
1128    }
1129    android_root += android_root_env_var;
1130  }
1131
1132  bool image = (!image_filename.empty());
1133  if (!image && boot_image_filename.empty()) {
1134    boot_image_filename += android_root;
1135    boot_image_filename += "/framework/boot.art";
1136  }
1137  std::string boot_image_option;
1138  if (!boot_image_filename.empty()) {
1139    boot_image_option += "-Ximage:";
1140    boot_image_option += boot_image_filename;
1141  }
1142
1143  if (image_classes_filename != nullptr && !image) {
1144    Usage("--image-classes should only be used with --image");
1145  }
1146
1147  if (image_classes_filename != nullptr && !boot_image_option.empty()) {
1148    Usage("--image-classes should not be used with --boot-image");
1149  }
1150
1151  if (image_classes_zip_filename != nullptr && image_classes_filename == nullptr) {
1152    Usage("--image-classes-zip should be used with --image-classes");
1153  }
1154
1155  if (compiled_classes_filename != nullptr && !image) {
1156    Usage("--compiled-classes should only be used with --image");
1157  }
1158
1159  if (compiled_classes_filename != nullptr && !boot_image_option.empty()) {
1160    Usage("--compiled-classes should not be used with --boot-image");
1161  }
1162
1163  if (compiled_classes_zip_filename != nullptr && compiled_classes_filename == nullptr) {
1164    Usage("--compiled-classes-zip should be used with --compiled-classes");
1165  }
1166
1167  if (dex_filenames.empty() && zip_fd == -1) {
1168    Usage("Input must be supplied with either --dex-file or --zip-fd");
1169  }
1170
1171  if (!dex_filenames.empty() && zip_fd != -1) {
1172    Usage("--dex-file should not be used with --zip-fd");
1173  }
1174
1175  if (!dex_filenames.empty() && !zip_location.empty()) {
1176    Usage("--dex-file should not be used with --zip-location");
1177  }
1178
1179  if (dex_locations.empty()) {
1180    for (size_t i = 0; i < dex_filenames.size(); i++) {
1181      dex_locations.push_back(dex_filenames[i]);
1182    }
1183  } else if (dex_locations.size() != dex_filenames.size()) {
1184    Usage("--dex-location arguments do not match --dex-file arguments");
1185  }
1186
1187  if (zip_fd != -1 && zip_location.empty()) {
1188    Usage("--zip-location should be supplied with --zip-fd");
1189  }
1190
1191  if (boot_image_option.empty()) {
1192    if (image_base == 0) {
1193      Usage("Non-zero --base not specified");
1194    }
1195  }
1196
1197  std::string oat_stripped(oat_filename);
1198  std::string oat_unstripped;
1199  if (!oat_symbols.empty()) {
1200    oat_unstripped += oat_symbols;
1201  } else {
1202    oat_unstripped += oat_filename;
1203  }
1204
1205  if (compiler_filter_string == nullptr) {
1206    if (instruction_set == kMips64) {
1207      // TODO: fix compiler for Mips64.
1208      compiler_filter_string = "interpret-only";
1209    } else if (image) {
1210      compiler_filter_string = "speed";
1211    } else {
1212#if ART_SMALL_MODE
1213      compiler_filter_string = "interpret-only";
1214#else
1215      compiler_filter_string = "speed";
1216#endif
1217    }
1218  }
1219  CHECK(compiler_filter_string != nullptr);
1220  CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
1221  if (strcmp(compiler_filter_string, "verify-none") == 0) {
1222    compiler_filter = CompilerOptions::kVerifyNone;
1223  } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
1224    compiler_filter = CompilerOptions::kInterpretOnly;
1225  } else if (strcmp(compiler_filter_string, "space") == 0) {
1226    compiler_filter = CompilerOptions::kSpace;
1227  } else if (strcmp(compiler_filter_string, "balanced") == 0) {
1228    compiler_filter = CompilerOptions::kBalanced;
1229  } else if (strcmp(compiler_filter_string, "speed") == 0) {
1230    compiler_filter = CompilerOptions::kSpeed;
1231  } else if (strcmp(compiler_filter_string, "everything") == 0) {
1232    compiler_filter = CompilerOptions::kEverything;
1233  } else {
1234    Usage("Unknown --compiler-filter value %s", compiler_filter_string);
1235  }
1236
1237  // Set the compilation target's implicit checks options.
1238  switch (instruction_set) {
1239    case kArm:
1240    case kThumb2:
1241    case kArm64:
1242    case kX86:
1243    case kX86_64:
1244      implicit_null_checks = true;
1245      implicit_so_checks = true;
1246      break;
1247
1248    default:
1249      // Defaults are correct.
1250      break;
1251  }
1252
1253  std::unique_ptr<CompilerOptions> compiler_options(new CompilerOptions(compiler_filter,
1254                                                                        huge_method_threshold,
1255                                                                        large_method_threshold,
1256                                                                        small_method_threshold,
1257                                                                        tiny_method_threshold,
1258                                                                        num_dex_methods_threshold,
1259                                                                        generate_gdb_information,
1260                                                                        include_patch_information,
1261                                                                        top_k_profile_threshold,
1262                                                                        include_debug_symbols,
1263                                                                        implicit_null_checks,
1264                                                                        implicit_so_checks,
1265                                                                        implicit_suspend_checks,
1266                                                                        compile_pic
1267#ifdef ART_SEA_IR_MODE
1268                                                                        , compiler_options.sea_ir_ =
1269                                                                              true;
1270#endif
1271  ));  // NOLINT(whitespace/parens)
1272
1273  // Done with usage checks, enable watchdog if requested
1274  WatchDog watch_dog(watch_dog_enabled);
1275
1276  // Check early that the result of compilation can be written
1277  std::unique_ptr<File> oat_file;
1278  bool create_file = !oat_unstripped.empty();  // as opposed to using open file descriptor
1279  if (create_file) {
1280    oat_file.reset(OS::CreateEmptyFile(oat_unstripped.c_str()));
1281    if (oat_location.empty()) {
1282      oat_location = oat_filename;
1283    }
1284  } else {
1285    oat_file.reset(new File(oat_fd, oat_location, true));
1286    oat_file->DisableAutoClose();
1287    if (oat_file->SetLength(0)) {  // Only warn for truncation error.
1288      PLOG(WARNING) << "Truncating oat file " << oat_location << " failed.";
1289    }
1290  }
1291  if (oat_file.get() == nullptr) {
1292    PLOG(ERROR) << "Failed to create oat file: " << oat_location;
1293    return EXIT_FAILURE;
1294  }
1295  if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1296    PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location;
1297    return EXIT_FAILURE;
1298  }
1299
1300  timings.StartTiming("dex2oat Setup");
1301  LOG(INFO) << CommandLine();
1302
1303  RuntimeOptions runtime_options;
1304  std::vector<const DexFile*> boot_class_path;
1305  art::MemMap::Init();  // For ZipEntry::ExtractToMemMap.
1306  if (boot_image_option.empty()) {
1307    size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path);
1308    if (failure_count > 0) {
1309      LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1310      return EXIT_FAILURE;
1311    }
1312    runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
1313  } else {
1314    runtime_options.push_back(std::make_pair(boot_image_option.c_str(), nullptr));
1315  }
1316  for (size_t i = 0; i < runtime_args.size(); i++) {
1317    runtime_options.push_back(std::make_pair(runtime_args[i], nullptr));
1318  }
1319
1320  std::unique_ptr<VerificationResults> verification_results(new VerificationResults(
1321                                                            compiler_options.get()));
1322  DexFileToMethodInlinerMap method_inliner_map;
1323  QuickCompilerCallbacks callbacks(verification_results.get(), &method_inliner_map);
1324  runtime_options.push_back(std::make_pair("compilercallbacks", &callbacks));
1325  runtime_options.push_back(
1326      std::make_pair("imageinstructionset",
1327                     reinterpret_cast<const void*>(GetInstructionSetString(instruction_set))));
1328
1329  Dex2Oat* p_dex2oat;
1330  if (!Dex2Oat::Create(&p_dex2oat,
1331                       runtime_options,
1332                       *compiler_options,
1333                       compiler_kind,
1334                       instruction_set,
1335                       instruction_set_features,
1336                       verification_results.get(),
1337                       &method_inliner_map,
1338                       thread_count)) {
1339    LOG(ERROR) << "Failed to create dex2oat";
1340    timings.EndTiming();
1341    return EXIT_FAILURE;
1342  }
1343  std::unique_ptr<Dex2Oat> dex2oat(p_dex2oat);
1344
1345  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
1346  // give it away now so that we don't starve GC.
1347  Thread* self = Thread::Current();
1348  self->TransitionFromRunnableToSuspended(kNative);
1349  // If we're doing the image, override the compiler filter to force full compilation. Must be
1350  // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
1351  // compilation of class initializers.
1352  // Whilst we're in native take the opportunity to initialize well known classes.
1353  WellKnownClasses::Init(self->GetJniEnv());
1354
1355  // If --image-classes was specified, calculate the full list of classes to include in the image
1356  std::unique_ptr<std::set<std::string>> image_classes(nullptr);
1357  if (image_classes_filename != nullptr) {
1358    std::string error_msg;
1359    if (image_classes_zip_filename != nullptr) {
1360      image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename,
1361                                                           image_classes_filename,
1362                                                           &error_msg));
1363    } else {
1364      image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename));
1365    }
1366    if (image_classes.get() == nullptr) {
1367      LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename <<
1368          "': " << error_msg;
1369      timings.EndTiming();
1370      return EXIT_FAILURE;
1371    }
1372  } else if (image) {
1373    image_classes.reset(new std::set<std::string>);
1374  }
1375  // If --compiled-classes was specified, calculate the full list of classes to compile in the
1376  // image.
1377  std::unique_ptr<std::set<std::string>> compiled_classes(nullptr);
1378  if (compiled_classes_filename != nullptr) {
1379    std::string error_msg;
1380    if (compiled_classes_zip_filename != nullptr) {
1381      compiled_classes.reset(dex2oat->ReadImageClassesFromZip(compiled_classes_zip_filename,
1382                                                              compiled_classes_filename,
1383                                                              &error_msg));
1384    } else {
1385      compiled_classes.reset(dex2oat->ReadImageClassesFromFile(compiled_classes_filename));
1386    }
1387    if (compiled_classes.get() == nullptr) {
1388      LOG(ERROR) << "Failed to create list of compiled classes from '" << compiled_classes_filename
1389                 << "': " << error_msg;
1390      timings.EndTiming();
1391      return EXIT_FAILURE;
1392    }
1393  } else if (image) {
1394    compiled_classes.reset(nullptr);  // By default compile everything.
1395  }
1396
1397  std::vector<const DexFile*> dex_files;
1398  if (boot_image_option.empty()) {
1399    dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1400  } else {
1401    if (dex_filenames.empty()) {
1402      ATRACE_BEGIN("Opening zip archive from file descriptor");
1403      std::string error_msg;
1404      std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd, zip_location.c_str(),
1405                                                               &error_msg));
1406      if (zip_archive.get() == nullptr) {
1407        LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location << "': "
1408            << error_msg;
1409        timings.EndTiming();
1410        return EXIT_FAILURE;
1411      }
1412      if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location, &error_msg, &dex_files)) {
1413        LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location
1414            << "': " << error_msg;
1415        timings.EndTiming();
1416        return EXIT_FAILURE;
1417      }
1418      ATRACE_END();
1419    } else {
1420      size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files);
1421      if (failure_count > 0) {
1422        LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1423        timings.EndTiming();
1424        return EXIT_FAILURE;
1425      }
1426    }
1427
1428    const bool kSaveDexInput = false;
1429    if (kSaveDexInput) {
1430      for (size_t i = 0; i < dex_files.size(); ++i) {
1431        const DexFile* dex_file = dex_files[i];
1432        std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1433        std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1434        if (tmp_file.get() == nullptr) {
1435            PLOG(ERROR) << "Failed to open file " << tmp_file_name
1436                        << ". Try: adb shell chmod 777 /data/local/tmp";
1437            continue;
1438        }
1439        // This is just dumping files for debugging. Ignore errors, and leave remnants.
1440        UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1441        UNUSED(tmp_file->Flush());
1442        UNUSED(tmp_file->Close());
1443        LOG(INFO) << "Wrote input to " << tmp_file_name;
1444      }
1445    }
1446  }
1447  // Ensure opened dex files are writable for dex-to-dex transformations.
1448  for (const auto& dex_file : dex_files) {
1449    if (!dex_file->EnableWrite()) {
1450      PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1451    }
1452  }
1453
1454  /*
1455   * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1456   * Don't bother to check if we're doing the image.
1457   */
1458  if (!image && compiler_options->IsCompilationEnabled()) {
1459    size_t num_methods = 0;
1460    for (size_t i = 0; i != dex_files.size(); ++i) {
1461      const DexFile* dex_file = dex_files[i];
1462      CHECK(dex_file != nullptr);
1463      num_methods += dex_file->NumMethodIds();
1464    }
1465    if (num_methods <= compiler_options->GetNumDexMethodsThreshold()) {
1466      compiler_options->SetCompilerFilter(CompilerOptions::kSpeed);
1467      VLOG(compiler) << "Below method threshold, compiling anyways";
1468    }
1469  }
1470
1471  // Fill some values into the key-value store for the oat header.
1472  std::unique_ptr<SafeMap<std::string, std::string> > key_value_store(
1473      new SafeMap<std::string, std::string>());
1474
1475  // Insert some compiler things.
1476  {
1477    std::ostringstream oss;
1478    for (int i = 0; i < argc; ++i) {
1479      if (i > 0) {
1480        oss << ' ';
1481      }
1482      oss << argv[i];
1483    }
1484    key_value_store->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1485    oss.str("");  // Reset.
1486    oss << kRuntimeISA;
1487    key_value_store->Put(OatHeader::kDex2OatHostKey, oss.str());
1488    key_value_store->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
1489  }
1490
1491  std::unique_ptr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option,
1492                                                                        android_root,
1493                                                                        is_host,
1494                                                                        dex_files,
1495                                                                        oat_file.get(),
1496                                                                        oat_location,
1497                                                                        bitcode_filename,
1498                                                                        image,
1499                                                                        image_classes,
1500                                                                        compiled_classes,
1501                                                                        dump_stats,
1502                                                                        dump_passes,
1503                                                                        timings,
1504                                                                        compiler_phases_timings,
1505                                                                        profile_file,
1506                                                                        key_value_store.get()));
1507  if (compiler.get() == nullptr) {
1508    LOG(ERROR) << "Failed to create oat file: " << oat_location;
1509    timings.EndTiming();
1510    return EXIT_FAILURE;
1511  }
1512
1513  if (!kUsePortableCompiler) {
1514    if (oat_file->FlushCloseOrErase() != 0) {
1515      PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location;
1516      timings.EndTiming();
1517      return EXIT_FAILURE;
1518    }
1519    oat_file.reset();
1520  }
1521
1522  VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location;
1523  // Notes on the interleaving of creating the image and oat file to
1524  // ensure the references between the two are correct.
1525  //
1526  // Currently we have a memory layout that looks something like this:
1527  //
1528  // +--------------+
1529  // | image        |
1530  // +--------------+
1531  // | boot oat     |
1532  // +--------------+
1533  // | alloc spaces |
1534  // +--------------+
1535  //
1536  // There are several constraints on the loading of the image and boot.oat.
1537  //
1538  // 1. The image is expected to be loaded at an absolute address and
1539  // contains Objects with absolute pointers within the image.
1540  //
1541  // 2. There are absolute pointers from Methods in the image to their
1542  // code in the oat.
1543  //
1544  // 3. There are absolute pointers from the code in the oat to Methods
1545  // in the image.
1546  //
1547  // 4. There are absolute pointers from code in the oat to other code
1548  // in the oat.
1549  //
1550  // To get this all correct, we go through several steps.
1551  //
1552  // 1. We have already created that oat file above with
1553  // CreateOatFile. Originally this was just our own proprietary file
1554  // but now it is contained within an ELF dynamic object (aka an .so
1555  // file). The Compiler returned by CreateOatFile provides
1556  // PatchInformation for references to oat code and Methods that need
1557  // to be update once we know where the oat file will be located
1558  // after the image.
1559  //
1560  // 2. We create the image file. It needs to know where the oat file
1561  // will be loaded after itself. Originally when oat file was simply
1562  // memory mapped so we could predict where its contents were based
1563  // on the file size. Now that it is an ELF file, we need to inspect
1564  // the ELF file to understand the in memory segment layout including
1565  // where the oat header is located within. ElfPatcher's Patch method
1566  // uses the PatchInformation from the Compiler to touch up absolute
1567  // references in the oat file.
1568  //
1569  // 3. We fixup the ELF program headers so that dlopen will try to
1570  // load the .so at the desired location at runtime by offsetting the
1571  // Elf32_Phdr.p_vaddr values by the desired base address.
1572  //
1573  if (image) {
1574    TimingLogger::ScopedTiming t("dex2oat ImageWriter", &timings);
1575    bool image_creation_success = dex2oat->CreateImageFile(image_filename,
1576                                                           image_base,
1577                                                           oat_unstripped,
1578                                                           oat_location,
1579                                                           *compiler.get());
1580    if (!image_creation_success) {
1581      timings.EndTiming();
1582      return EXIT_FAILURE;
1583    }
1584    VLOG(compiler) << "Image written successfully: " << image_filename;
1585  }
1586
1587  if (is_host) {
1588    timings.EndTiming();
1589    if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
1590      LOG(INFO) << Dumpable<TimingLogger>(timings);
1591    }
1592    if (dump_passes) {
1593      LOG(INFO) << Dumpable<CumulativeLogger>(*compiler.get()->GetTimingsLogger());
1594    }
1595    return EXIT_SUCCESS;
1596  }
1597
1598  // If we don't want to strip in place, copy from unstripped location to stripped location.
1599  // We need to strip after image creation because FixupElf needs to use .strtab.
1600  if (oat_unstripped != oat_stripped) {
1601    TimingLogger::ScopedTiming t("dex2oat OatFile copy", &timings);
1602    if (kUsePortableCompiler) {
1603      if (oat_file->FlushCloseOrErase() != 0) {
1604        PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location;
1605        return EXIT_FAILURE;
1606      }
1607      oat_file.reset();
1608    }
1609    std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped.c_str()));
1610    std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped.c_str()));
1611    size_t buffer_size = 8192;
1612    std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1613    while (true) {
1614      int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1615      if (bytes_read <= 0) {
1616        break;
1617      }
1618      bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1619      CHECK(write_ok);
1620    }
1621    oat_file.reset(out.release());
1622    VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped;
1623  }
1624
1625  if (kUsePortableCompiler) {
1626    if (!compiler_options->GetIncludeDebugSymbols()) {
1627      timings.NewTiming("dex2oat ElfStripper");
1628      // Strip unneeded sections for target
1629      off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET);
1630      CHECK_EQ(0, seek_actual);
1631      std::string error_msg;
1632      CHECK(ElfStripper::Strip(oat_file.get(), &error_msg)) << error_msg;
1633
1634
1635      // We wrote the oat file successfully, and want to keep it.
1636      VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location;
1637    } else {
1638      VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location;
1639    }
1640    if (oat_file->FlushCloseOrErase() != 0) {
1641      LOG(ERROR) << "Failed to flush and close oat file: " << oat_location;
1642      return EXIT_FAILURE;
1643    }
1644    oat_file.reset(nullptr);
1645  }
1646
1647  if (oat_file.get() != nullptr) {
1648    if (oat_file->FlushCloseOrErase() != 0) {
1649      PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location << "/" << oat_filename;
1650      return EXIT_FAILURE;
1651    }
1652  }
1653
1654  timings.EndTiming();
1655
1656  if (dump_timing || (dump_slow_timing && timings.GetTotalNs() > MsToNs(1000))) {
1657    LOG(INFO) << Dumpable<TimingLogger>(timings);
1658  }
1659  if (dump_passes) {
1660    LOG(INFO) << Dumpable<CumulativeLogger>(compiler_phases_timings);
1661  }
1662
1663  dex2oat->LogCompletionTime(compiler.get());
1664  // Everything was successfully written, do an explicit exit here to avoid running Runtime
1665  // destructors that take time (bug 10645725) unless we're a debug build or running on valgrind.
1666  if (!kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1667    exit(EXIT_SUCCESS);
1668  }
1669
1670  return EXIT_SUCCESS;
1671}  // NOLINT(readability/fn_size)
1672}  // namespace art
1673
1674int main(int argc, char** argv) {
1675  return art::dex2oat(argc, argv);
1676}
1677