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