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