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