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