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