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