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