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