dex2oat.cc revision 821dad8f384f8c520f062a317b3b66c78aa12b47
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#include "arch/instruction_set_features.h"
36#include "arch/mips/instruction_set_features_mips.h"
37#include "art_method-inl.h"
38#include "base/dumpable.h"
39#include "base/macros.h"
40#include "base/scoped_flock.h"
41#include "base/stl_util.h"
42#include "base/stringpiece.h"
43#include "base/time_utils.h"
44#include "base/timing_logger.h"
45#include "base/unix_file/fd_file.h"
46#include "class_linker.h"
47#include "compiler.h"
48#include "compiler_callbacks.h"
49#include "debug/elf_debug_writer.h"
50#include "debug/method_debug_info.h"
51#include "dex/pass_manager.h"
52#include "dex/quick/dex_file_to_method_inliner_map.h"
53#include "dex/quick_compiler_callbacks.h"
54#include "dex/verification_results.h"
55#include "dex_file-inl.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 "elf_writer_quick.h"
61#include "gc/space/image_space.h"
62#include "gc/space/space-inl.h"
63#include "image_writer.h"
64#include "interpreter/unstarted_runtime.h"
65#include "jit/offline_profiling_info.h"
66#include "leb128.h"
67#include "linker/multi_oat_relative_patcher.h"
68#include "mirror/class-inl.h"
69#include "mirror/class_loader.h"
70#include "mirror/object-inl.h"
71#include "mirror/object_array-inl.h"
72#include "oat_writer.h"
73#include "os.h"
74#include "runtime.h"
75#include "runtime_options.h"
76#include "ScopedLocalRef.h"
77#include "scoped_thread_state_change.h"
78#include "utils.h"
79#include "well_known_classes.h"
80#include "zip_archive.h"
81
82namespace art {
83
84static int original_argc;
85static char** original_argv;
86
87static std::string CommandLine() {
88  std::vector<std::string> command;
89  for (int i = 0; i < original_argc; ++i) {
90    command.push_back(original_argv[i]);
91  }
92  return Join(command, ' ');
93}
94
95// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
96// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
97// locations are all staged).
98static std::string StrippedCommandLine() {
99  std::vector<std::string> command;
100
101  // Do a pre-pass to look for zip-fd.
102  bool saw_zip_fd = false;
103  for (int i = 0; i < original_argc; ++i) {
104    if (StartsWith(original_argv[i], "--zip-fd=")) {
105      saw_zip_fd = true;
106      break;
107    }
108  }
109
110  // Now filter out things.
111  for (int i = 0; i < original_argc; ++i) {
112    // All runtime-arg parameters are dropped.
113    if (strcmp(original_argv[i], "--runtime-arg") == 0) {
114      i++;  // Drop the next part, too.
115      continue;
116    }
117
118    // Any instruction-setXXX is dropped.
119    if (StartsWith(original_argv[i], "--instruction-set")) {
120      continue;
121    }
122
123    // The boot image is dropped.
124    if (StartsWith(original_argv[i], "--boot-image=")) {
125      continue;
126    }
127
128    // The image format is dropped.
129    if (StartsWith(original_argv[i], "--image-format=")) {
130      continue;
131    }
132
133    // This should leave any dex-file and oat-file options, describing what we compiled.
134
135    // However, we prefer to drop this when we saw --zip-fd.
136    if (saw_zip_fd) {
137      // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
138      if (StartsWith(original_argv[i], "--zip-") ||
139          StartsWith(original_argv[i], "--dex-") ||
140          StartsWith(original_argv[i], "--oat-") ||
141          StartsWith(original_argv[i], "--swap-") ||
142          StartsWith(original_argv[i], "--app-image-")) {
143        continue;
144      }
145    }
146
147    command.push_back(original_argv[i]);
148  }
149
150  // Construct the final output.
151  if (command.size() <= 1U) {
152    // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
153    return "Starting dex2oat.";
154  }
155  return Join(command, ' ');
156}
157
158static void UsageErrorV(const char* fmt, va_list ap) {
159  std::string error;
160  StringAppendV(&error, fmt, ap);
161  LOG(ERROR) << error;
162}
163
164static void UsageError(const char* fmt, ...) {
165  va_list ap;
166  va_start(ap, fmt);
167  UsageErrorV(fmt, ap);
168  va_end(ap);
169}
170
171NO_RETURN static void Usage(const char* fmt, ...) {
172  va_list ap;
173  va_start(ap, fmt);
174  UsageErrorV(fmt, ap);
175  va_end(ap);
176
177  UsageError("Command: %s", CommandLine().c_str());
178
179  UsageError("Usage: dex2oat [options]...");
180  UsageError("");
181  UsageError("  -j<number>: specifies the number of threads used for compilation.");
182  UsageError("       Default is the number of detected hardware threads available on the");
183  UsageError("       host system.");
184  UsageError("      Example: -j12");
185  UsageError("");
186  UsageError("  --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
187  UsageError("      Example: --dex-file=/system/framework/core.jar");
188  UsageError("");
189  UsageError("  --dex-location=<dex-location>: specifies an alternative dex location to");
190  UsageError("      encode in the oat file for the corresponding --dex-file argument.");
191  UsageError("      Example: --dex-file=/home/build/out/system/framework/core.jar");
192  UsageError("               --dex-location=/system/framework/core.jar");
193  UsageError("");
194  UsageError("  --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
195  UsageError("      containing a classes.dex file to compile.");
196  UsageError("      Example: --zip-fd=5");
197  UsageError("");
198  UsageError("  --zip-location=<zip-location>: specifies a symbolic name for the file");
199  UsageError("      corresponding to the file descriptor specified by --zip-fd.");
200  UsageError("      Example: --zip-location=/system/app/Calculator.apk");
201  UsageError("");
202  UsageError("  --oat-file=<file.oat>: specifies an oat output destination via a filename.");
203  UsageError("      Example: --oat-file=/system/framework/boot.oat");
204  UsageError("");
205  UsageError("  --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
206  UsageError("      Example: --oat-fd=6");
207  UsageError("");
208  UsageError("  --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
209  UsageError("      to the file descriptor specified by --oat-fd.");
210  UsageError("      Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
211  UsageError("");
212  UsageError("  --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
213  UsageError("      Example: --oat-symbols=/symbols/system/framework/boot.oat");
214  UsageError("");
215  UsageError("  --image=<file.art>: specifies an output image filename.");
216  UsageError("      Example: --image=/system/framework/boot.art");
217  UsageError("");
218  UsageError("  --image-format=(uncompressed|lz4|lz4hc):");
219  UsageError("      Which format to store the image.");
220  UsageError("      Example: --image-format=lz4");
221  UsageError("      Default: uncompressed");
222  UsageError("");
223  UsageError("  --image-classes=<classname-file>: specifies classes to include in an image.");
224  UsageError("      Example: --image=frameworks/base/preloaded-classes");
225  UsageError("");
226  UsageError("  --base=<hex-address>: specifies the base address when creating a boot image.");
227  UsageError("      Example: --base=0x50000000");
228  UsageError("");
229  UsageError("  --boot-image=<file.art>: provide the image file for the boot class path.");
230  UsageError("      Do not include the arch as part of the name, it is added automatically.");
231  UsageError("      Example: --boot-image=/system/framework/boot.art");
232  UsageError("               (specifies /system/framework/<arch>/boot.art as the image file)");
233  UsageError("      Default: $ANDROID_ROOT/system/framework/boot.art");
234  UsageError("");
235  UsageError("  --android-root=<path>: used to locate libraries for portable linking.");
236  UsageError("      Example: --android-root=out/host/linux-x86");
237  UsageError("      Default: $ANDROID_ROOT");
238  UsageError("");
239  UsageError("  --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
240  UsageError("      instruction set.");
241  UsageError("      Example: --instruction-set=x86");
242  UsageError("      Default: arm");
243  UsageError("");
244  UsageError("  --instruction-set-features=...,: Specify instruction set features");
245  UsageError("      Example: --instruction-set-features=div");
246  UsageError("      Default: default");
247  UsageError("");
248  UsageError("  --compile-pic: Force indirect use of code, methods, and classes");
249  UsageError("      Default: disabled");
250  UsageError("");
251  UsageError("  --compiler-backend=(Quick|Optimizing): select compiler backend");
252  UsageError("      set.");
253  UsageError("      Example: --compiler-backend=Optimizing");
254  UsageError("      Default: Optimizing");
255  UsageError("");
256  UsageError("  --compiler-filter="
257                "(verify-none"
258                "|verify-at-runtime"
259                "|verify-profile"
260                "|interpret-only"
261                "|space"
262                "|balanced"
263                "|speed"
264                "|everything"
265                "|time):");
266  UsageError("      select compiler filter.");
267  UsageError("      verify-profile requires a --profile(-fd) to also be passed in.");
268  UsageError("      Example: --compiler-filter=everything");
269  UsageError("      Default: speed");
270  UsageError("");
271  UsageError("  --huge-method-max=<method-instruction-count>: threshold size for a huge");
272  UsageError("      method for compiler filter tuning.");
273  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
274  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
275  UsageError("");
276  UsageError("  --large-method-max=<method-instruction-count>: threshold size for a large");
277  UsageError("      method for compiler filter tuning.");
278  UsageError("      Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
279  UsageError("      Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
280  UsageError("");
281  UsageError("  --small-method-max=<method-instruction-count>: threshold size for a small");
282  UsageError("      method for compiler filter tuning.");
283  UsageError("      Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
284  UsageError("      Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
285  UsageError("");
286  UsageError("  --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
287  UsageError("      method for compiler filter tuning.");
288  UsageError("      Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
289  UsageError("      Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
290  UsageError("");
291  UsageError("  --num-dex-methods=<method-count>: threshold size for a small dex file for");
292  UsageError("      compiler filter tuning. If the input has fewer than this many methods");
293  UsageError("      and the filter is not interpret-only or verify-none or verify-at-runtime, ");
294  UsageError("      overrides the filter to use speed");
295  UsageError("      Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
296  UsageError("      Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
297  UsageError("");
298  UsageError("  --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
299  UsageError("      the compiler. A zero value will disable inlining. Honored only by Optimizing.");
300  UsageError("      Has priority over the --compiler-filter option. Intended for ");
301  UsageError("      development/experimental use.");
302  UsageError("      Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
303  UsageError("      Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
304  UsageError("");
305  UsageError("  --inline-max-code-units=<code-units-count>: the maximum code units that a method");
306  UsageError("      can have to be considered for inlining. A zero value will disable inlining.");
307  UsageError("      Honored only by Optimizing. Has priority over the --compiler-filter option.");
308  UsageError("      Intended for development/experimental use.");
309  UsageError("      Example: --inline-max-code-units=%d",
310             CompilerOptions::kDefaultInlineMaxCodeUnits);
311  UsageError("      Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
312  UsageError("");
313  UsageError("  --dump-timing: display a breakdown of where time was spent");
314  UsageError("");
315  UsageError("  --include-patch-information: Include patching information so the generated code");
316  UsageError("      can have its base address moved without full recompilation.");
317  UsageError("");
318  UsageError("  --no-include-patch-information: Do not include patching information.");
319  UsageError("");
320  UsageError("  -g");
321  UsageError("  --generate-debug-info: Generate debug information for native debugging,");
322  UsageError("      such as stack unwinding information, ELF symbols and DWARF sections.");
323  UsageError("      If used without --native-debuggable, it will be best-effort only.");
324  UsageError("      This option does not affect the generated code. (disabled by default)");
325  UsageError("");
326  UsageError("  --no-generate-debug-info: Do not generate debug information for native debugging.");
327  UsageError("");
328  UsageError("  --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
329  UsageError("      debug information necessary to print backtraces. (disabled by default)");
330  UsageError("");
331  UsageError("  --no-generate-mini-debug-info: Do do generated backtrace info.");
332  UsageError("");
333  UsageError("  --debuggable: Produce code debuggable with Java debugger.");
334  UsageError("");
335  UsageError("  --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
336  UsageError("      Implies --debuggable.");
337  UsageError("");
338  UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
339  UsageError("      such as initial heap size, maximum heap size, and verbose output.");
340  UsageError("      Use a separate --runtime-arg switch for each argument.");
341  UsageError("      Example: --runtime-arg -Xms256m");
342  UsageError("");
343  UsageError("  --profile-file=<filename>: specify profiler output file to use for compilation.");
344  UsageError("");
345  UsageError("  --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
346  UsageError("      Cannot be used together with --profile-file.");
347  UsageError("");
348  UsageError("  --print-pass-names: print a list of pass names");
349  UsageError("");
350  UsageError("  --disable-passes=<pass-names>:  disable one or more passes separated by comma.");
351  UsageError("      Example: --disable-passes=UseCount,BBOptimizations");
352  UsageError("");
353  UsageError("  --print-pass-options: print a list of passes that have configurable options along "
354             "with the setting.");
355  UsageError("      Will print default if no overridden setting exists.");
356  UsageError("");
357  UsageError("  --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
358             "Pass2Name:Pass2OptionName:Pass2Option#");
359  UsageError("      Used to specify a pass specific option. The setting itself must be integer.");
360  UsageError("      Separator used between options is a comma.");
361  UsageError("");
362  UsageError("  --swap-file=<file-name>:  specifies a file to use for swap.");
363  UsageError("      Example: --swap-file=/data/tmp/swap.001");
364  UsageError("");
365  UsageError("  --swap-fd=<file-descriptor>:  specifies a file to use for swap (by descriptor).");
366  UsageError("      Example: --swap-fd=10");
367  UsageError("");
368  UsageError("  --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
369  UsageError("      Example: --app-image-fd=10");
370  UsageError("");
371  UsageError("  --app-image-file=<file-name>: specify a file name for app image.");
372  UsageError("      Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
373  UsageError("");
374  UsageError("  --multi-image: specify that separate oat and image files be generated for each "
375             "input dex file.");
376  UsageError("");
377  UsageError("  --force-determinism: force the compiler to emit a deterministic output.");
378  UsageError("      This option is incompatible with read barriers (e.g., if dex2oat has been");
379  UsageError("      built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
380  UsageError("");
381  std::cerr << "See log for usage error information\n";
382  exit(EXIT_FAILURE);
383}
384
385// The primary goal of the watchdog is to prevent stuck build servers
386// during development when fatal aborts lead to a cascade of failures
387// that result in a deadlock.
388class WatchDog {
389// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
390#undef CHECK_PTHREAD_CALL
391#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
392  do { \
393    int rc = call args; \
394    if (rc != 0) { \
395      errno = rc; \
396      std::string message(# call); \
397      message += " failed for "; \
398      message += reason; \
399      Fatal(message); \
400    } \
401  } while (false)
402
403 public:
404  explicit WatchDog(bool is_watch_dog_enabled) {
405    is_watch_dog_enabled_ = is_watch_dog_enabled;
406    if (!is_watch_dog_enabled_) {
407      return;
408    }
409    shutting_down_ = false;
410    const char* reason = "dex2oat watch dog thread startup";
411    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
412    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
413    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
414    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
415    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
416  }
417  ~WatchDog() {
418    if (!is_watch_dog_enabled_) {
419      return;
420    }
421    const char* reason = "dex2oat watch dog thread shutdown";
422    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
423    shutting_down_ = true;
424    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
425    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
426
427    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
428
429    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
430    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
431  }
432
433 private:
434  static void* CallBack(void* arg) {
435    WatchDog* self = reinterpret_cast<WatchDog*>(arg);
436    ::art::SetThreadName("dex2oat watch dog");
437    self->Wait();
438    return nullptr;
439  }
440
441  NO_RETURN static void Fatal(const std::string& message) {
442    // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
443    //       it's rather easy to hang in unwinding.
444    //       LogLine also avoids ART logging lock issues, as it's really only a wrapper around
445    //       logcat logging or stderr output.
446    LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
447    exit(1);
448  }
449
450  void Wait() {
451    // TODO: tune the multiplier for GC verification, the following is just to make the timeout
452    //       large.
453    constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
454    timespec timeout_ts;
455    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
456    const char* reason = "dex2oat watch dog thread waiting";
457    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
458    while (!shutting_down_) {
459      int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
460      if (rc == ETIMEDOUT) {
461        Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
462                           kWatchDogTimeoutSeconds));
463      } else if (rc != 0) {
464        std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
465                                         strerror(errno)));
466        Fatal(message.c_str());
467      }
468    }
469    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
470  }
471
472  // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
473  // Debug builds are slower so they have larger timeouts.
474  static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
475
476  // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
477  // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
478  // itself before that watchdog would take down the system server.
479  static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
480
481  bool is_watch_dog_enabled_;
482  bool shutting_down_;
483  // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
484  pthread_mutex_t mutex_;
485  pthread_cond_t cond_;
486  pthread_attr_t attr_;
487  pthread_t pthread_;
488};
489
490static constexpr size_t kMinDexFilesForSwap = 2;
491static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
492
493static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
494  if (is_image) {
495    // Don't use swap, we know generation should succeed, and we don't want to slow it down.
496    return false;
497  }
498  if (dex_files.size() < kMinDexFilesForSwap) {
499    // If there are less dex files than the threshold, assume it's gonna be fine.
500    return false;
501  }
502  size_t dex_files_size = 0;
503  for (const auto* dex_file : dex_files) {
504    dex_files_size += dex_file->GetHeader().file_size_;
505  }
506  return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
507}
508
509class Dex2Oat FINAL {
510 public:
511  explicit Dex2Oat(TimingLogger* timings) :
512      compiler_kind_(Compiler::kOptimizing),
513      instruction_set_(kRuntimeISA),
514      // Take the default set of instruction features from the build.
515      image_file_location_oat_checksum_(0),
516      image_file_location_oat_data_begin_(0),
517      image_patch_delta_(0),
518      key_value_store_(nullptr),
519      verification_results_(nullptr),
520      method_inliner_map_(),
521      runtime_(nullptr),
522      thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
523      start_ns_(NanoTime()),
524      oat_fd_(-1),
525      zip_fd_(-1),
526      image_base_(0U),
527      image_classes_zip_filename_(nullptr),
528      image_classes_filename_(nullptr),
529      image_storage_mode_(ImageHeader::kStorageModeUncompressed),
530      compiled_classes_zip_filename_(nullptr),
531      compiled_classes_filename_(nullptr),
532      compiled_methods_zip_filename_(nullptr),
533      compiled_methods_filename_(nullptr),
534      app_image_(false),
535      boot_image_(false),
536      multi_image_(false),
537      is_host_(false),
538      class_loader_(nullptr),
539      elf_writers_(),
540      oat_writers_(),
541      rodata_(),
542      image_writer_(nullptr),
543      driver_(nullptr),
544      opened_dex_files_maps_(),
545      opened_dex_files_(),
546      no_inline_from_dex_files_(),
547      dump_stats_(false),
548      dump_passes_(false),
549      dump_timing_(false),
550      dump_slow_timing_(kIsDebugBuild),
551      swap_fd_(kInvalidFd),
552      app_image_fd_(kInvalidFd),
553      profile_file_fd_(kInvalidFd),
554      timings_(timings),
555      force_determinism_(false)
556      {}
557
558  ~Dex2Oat() {
559    // Log completion time before deleting the runtime_, because this accesses
560    // the runtime.
561    LogCompletionTime();
562
563    if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
564      // We want to just exit on non-debug builds, not bringing the runtime down
565      // in an orderly fashion. So release the following fields.
566      driver_.release();
567      image_writer_.release();
568      for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
569        dex_file.release();
570      }
571      for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
572        map.release();
573      }
574      for (std::unique_ptr<File>& oat_file : oat_files_) {
575        oat_file.release();
576      }
577      runtime_.release();
578      verification_results_.release();
579      key_value_store_.release();
580    }
581  }
582
583  struct ParserOptions {
584    std::vector<const char*> oat_symbols;
585    std::string boot_image_filename;
586    bool watch_dog_enabled = true;
587    bool requested_specific_compiler = false;
588    std::string error_msg;
589  };
590
591  void ParseZipFd(const StringPiece& option) {
592    ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
593  }
594
595  void ParseOatFd(const StringPiece& option) {
596    ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
597  }
598
599  void ParseFdForCollection(const StringPiece& option,
600                            const char* arg_name,
601                            std::vector<uint32_t>* fds) {
602    uint32_t fd;
603    ParseUintOption(option, arg_name, &fd, Usage);
604    fds->push_back(fd);
605  }
606
607  void ParseJ(const StringPiece& option) {
608    ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
609  }
610
611  void ParseBase(const StringPiece& option) {
612    DCHECK(option.starts_with("--base="));
613    const char* image_base_str = option.substr(strlen("--base=")).data();
614    char* end;
615    image_base_ = strtoul(image_base_str, &end, 16);
616    if (end == image_base_str || *end != '\0') {
617      Usage("Failed to parse hexadecimal value for option %s", option.data());
618    }
619  }
620
621  void ParseInstructionSet(const StringPiece& option) {
622    DCHECK(option.starts_with("--instruction-set="));
623    StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
624    // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
625    std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
626    strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
627    buf.get()[instruction_set_str.length()] = 0;
628    instruction_set_ = GetInstructionSetFromString(buf.get());
629    // arm actually means thumb2.
630    if (instruction_set_ == InstructionSet::kArm) {
631      instruction_set_ = InstructionSet::kThumb2;
632    }
633  }
634
635  void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
636    DCHECK(option.starts_with("--instruction-set-variant="));
637    StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
638    instruction_set_features_.reset(
639        InstructionSetFeatures::FromVariant(
640            instruction_set_, str.as_string(), &parser_options->error_msg));
641    if (instruction_set_features_.get() == nullptr) {
642      Usage("%s", parser_options->error_msg.c_str());
643    }
644  }
645
646  void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
647    DCHECK(option.starts_with("--instruction-set-features="));
648    StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
649    if (instruction_set_features_.get() == nullptr) {
650      instruction_set_features_.reset(
651          InstructionSetFeatures::FromVariant(
652              instruction_set_, "default", &parser_options->error_msg));
653      if (instruction_set_features_.get() == nullptr) {
654        Usage("Problem initializing default instruction set features variant: %s",
655              parser_options->error_msg.c_str());
656      }
657    }
658    instruction_set_features_.reset(
659        instruction_set_features_->AddFeaturesFromString(str.as_string(),
660                                                         &parser_options->error_msg));
661    if (instruction_set_features_.get() == nullptr) {
662      Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
663    }
664  }
665
666  void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
667    DCHECK(option.starts_with("--compiler-backend="));
668    parser_options->requested_specific_compiler = true;
669    StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
670    if (backend_str == "Quick") {
671      compiler_kind_ = Compiler::kQuick;
672    } else if (backend_str == "Optimizing") {
673      compiler_kind_ = Compiler::kOptimizing;
674    } else {
675      Usage("Unknown compiler backend: %s", backend_str.data());
676    }
677  }
678
679  void ParseImageFormat(const StringPiece& option) {
680    const StringPiece substr("--image-format=");
681    DCHECK(option.starts_with(substr));
682    const StringPiece format_str = option.substr(substr.length());
683    if (format_str == "lz4") {
684      image_storage_mode_ = ImageHeader::kStorageModeLZ4;
685    } else if (format_str == "lz4hc") {
686      image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
687    } else if (format_str == "uncompressed") {
688      image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
689    } else {
690      Usage("Unknown image format: %s", format_str.data());
691    }
692  }
693
694  void ProcessOptions(ParserOptions* parser_options) {
695    boot_image_ = !image_filenames_.empty();
696    app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
697
698    if (IsAppImage() && IsBootImage()) {
699      Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
700    }
701
702    if (IsBootImage()) {
703      // We need the boot image to always be debuggable.
704      // TODO: Remove this once we better deal with full frame deoptimization.
705      compiler_options_->debuggable_ = true;
706    }
707
708    if (oat_filenames_.empty() && oat_fd_ == -1) {
709      Usage("Output must be supplied with either --oat-file or --oat-fd");
710    }
711
712    if (!oat_filenames_.empty() && oat_fd_ != -1) {
713      Usage("--oat-file should not be used with --oat-fd");
714    }
715
716    if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
717      Usage("--oat-symbols should not be used with --oat-fd");
718    }
719
720    if (!parser_options->oat_symbols.empty() && is_host_) {
721      Usage("--oat-symbols should not be used with --host");
722    }
723
724    if (oat_fd_ != -1 && !image_filenames_.empty()) {
725      Usage("--oat-fd should not be used with --image");
726    }
727
728    if (!parser_options->oat_symbols.empty() &&
729        parser_options->oat_symbols.size() != oat_filenames_.size()) {
730      Usage("--oat-file arguments do not match --oat-symbols arguments");
731    }
732
733    if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
734      Usage("--oat-file arguments do not match --image arguments");
735    }
736
737    if (android_root_.empty()) {
738      const char* android_root_env_var = getenv("ANDROID_ROOT");
739      if (android_root_env_var == nullptr) {
740        Usage("--android-root unspecified and ANDROID_ROOT not set");
741      }
742      android_root_ += android_root_env_var;
743    }
744
745    if (!boot_image_ && parser_options->boot_image_filename.empty()) {
746      parser_options->boot_image_filename += android_root_;
747      parser_options->boot_image_filename += "/framework/boot.art";
748    }
749    if (!parser_options->boot_image_filename.empty()) {
750      boot_image_filename_ = parser_options->boot_image_filename;
751    }
752
753    if (image_classes_filename_ != nullptr && !IsBootImage()) {
754      Usage("--image-classes should only be used with --image");
755    }
756
757    if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
758      Usage("--image-classes should not be used with --boot-image");
759    }
760
761    if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
762      Usage("--image-classes-zip should be used with --image-classes");
763    }
764
765    if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
766      Usage("--compiled-classes should only be used with --image");
767    }
768
769    if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
770      Usage("--compiled-classes should not be used with --boot-image");
771    }
772
773    if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
774      Usage("--compiled-classes-zip should be used with --compiled-classes");
775    }
776
777    if (dex_filenames_.empty() && zip_fd_ == -1) {
778      Usage("Input must be supplied with either --dex-file or --zip-fd");
779    }
780
781    if (!dex_filenames_.empty() && zip_fd_ != -1) {
782      Usage("--dex-file should not be used with --zip-fd");
783    }
784
785    if (!dex_filenames_.empty() && !zip_location_.empty()) {
786      Usage("--dex-file should not be used with --zip-location");
787    }
788
789    if (dex_locations_.empty()) {
790      for (const char* dex_file_name : dex_filenames_) {
791        dex_locations_.push_back(dex_file_name);
792      }
793    } else if (dex_locations_.size() != dex_filenames_.size()) {
794      Usage("--dex-location arguments do not match --dex-file arguments");
795    }
796
797    if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
798      if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
799        Usage("--oat-file arguments must be singular or match --dex-file arguments");
800      }
801    }
802
803    if (zip_fd_ != -1 && zip_location_.empty()) {
804      Usage("--zip-location should be supplied with --zip-fd");
805    }
806
807    if (boot_image_filename_.empty()) {
808      if (image_base_ == 0) {
809        Usage("Non-zero --base not specified");
810      }
811    }
812
813    const bool have_profile_file = !profile_file_.empty();
814    const bool have_profile_fd = profile_file_fd_ != kInvalidFd;
815    if (have_profile_file && have_profile_fd) {
816      Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
817    }
818
819    if (compiler_options_->VerifyOnlyProfile() && !have_profile_file && !have_profile_fd) {
820      Usage("verify-profile compiler filter must be used with a profile file or fd");
821    }
822
823    if (!parser_options->oat_symbols.empty()) {
824      oat_unstripped_ = std::move(parser_options->oat_symbols);
825    }
826
827    // If no instruction set feature was given, use the default one for the target
828    // instruction set.
829    if (instruction_set_features_.get() == nullptr) {
830      instruction_set_features_.reset(
831          InstructionSetFeatures::FromVariant(
832              instruction_set_, "default", &parser_options->error_msg));
833      if (instruction_set_features_.get() == nullptr) {
834        Usage("Problem initializing default instruction set features variant: %s",
835              parser_options->error_msg.c_str());
836      }
837    }
838
839    if (instruction_set_ == kRuntimeISA) {
840      std::unique_ptr<const InstructionSetFeatures> runtime_features(
841          InstructionSetFeatures::FromCppDefines());
842      if (!instruction_set_features_->Equals(runtime_features.get())) {
843        LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
844            << *instruction_set_features_ << ") and those of dex2oat executable ("
845            << *runtime_features <<") for the command line:\n"
846            << CommandLine();
847      }
848    }
849
850    // It they are not set, use default values for inlining settings.
851    // TODO: We should rethink the compiler filter. We mostly save
852    // time here, which is orthogonal to space.
853    if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
854      compiler_options_->inline_depth_limit_ =
855          (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
856          // Implementation of the space filter: limit inlining depth.
857          ? CompilerOptions::kSpaceFilterInlineDepthLimit
858          : CompilerOptions::kDefaultInlineDepthLimit;
859    }
860    if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
861      compiler_options_->inline_max_code_units_ =
862          (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
863          // Implementation of the space filter: limit inlining max code units.
864          ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
865          : CompilerOptions::kDefaultInlineMaxCodeUnits;
866    }
867
868    // Checks are all explicit until we know the architecture.
869    // Set the compilation target's implicit checks options.
870    switch (instruction_set_) {
871      case kArm:
872      case kThumb2:
873      case kArm64:
874      case kX86:
875      case kX86_64:
876      case kMips:
877      case kMips64:
878        compiler_options_->implicit_null_checks_ = true;
879        compiler_options_->implicit_so_checks_ = true;
880        break;
881
882      default:
883        // Defaults are correct.
884        break;
885    }
886
887    compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
888
889    if (!IsBootImage() && multi_image_) {
890      Usage("--multi-image can only be used when creating boot images");
891    }
892    if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
893      Usage("--multi-image cannot be used with multiple image names");
894    }
895
896    // For now, if we're on the host and compile the boot image, *always* use multiple image files.
897    if (!kIsTargetBuild && IsBootImage()) {
898      if (image_filenames_.size() == 1) {
899        multi_image_ = true;
900      }
901    }
902
903    // Done with usage checks, enable watchdog if requested
904    if (parser_options->watch_dog_enabled) {
905      watchdog_.reset(new WatchDog(true));
906    }
907
908    // Fill some values into the key-value store for the oat header.
909    key_value_store_.reset(new SafeMap<std::string, std::string>());
910
911    // Automatically force determinism for the boot image in a host build if the default GC is CMS
912    // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
913    // one by passing the option `-Xgc:nonconcurrent` (see below).
914    if (!kIsTargetBuild && IsBootImage()) {
915      if (SupportsDeterministicCompilation()) {
916        force_determinism_ = true;
917      } else {
918        LOG(WARNING) << "Deterministic compilation is disabled.";
919      }
920    }
921    compiler_options_->force_determinism_ = force_determinism_;
922  }
923
924  static bool SupportsDeterministicCompilation() {
925    return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
926            gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
927        !kEmitCompilerReadBarrier;
928  }
929
930  void ExpandOatAndImageFilenames() {
931    std::string base_oat = oat_filenames_[0];
932    size_t last_oat_slash = base_oat.rfind('/');
933    if (last_oat_slash == std::string::npos) {
934      Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
935    }
936    // We also need to honor path components that were encoded through '@'. Otherwise the loading
937    // code won't be able to find the images.
938    if (base_oat.find('@', last_oat_slash) != std::string::npos) {
939      last_oat_slash = base_oat.rfind('@');
940    }
941    base_oat = base_oat.substr(0, last_oat_slash + 1);
942
943    std::string base_img = image_filenames_[0];
944    size_t last_img_slash = base_img.rfind('/');
945    if (last_img_slash == std::string::npos) {
946      Usage("--multi-image used with unusable image filename %s", base_img.c_str());
947    }
948    // We also need to honor path components that were encoded through '@'. Otherwise the loading
949    // code won't be able to find the images.
950    if (base_img.find('@', last_img_slash) != std::string::npos) {
951      last_img_slash = base_img.rfind('@');
952    }
953
954    // Get the prefix, which is the primary image name (without path components). Strip the
955    // extension.
956    std::string prefix = base_img.substr(last_img_slash + 1);
957    if (prefix.rfind('.') != std::string::npos) {
958      prefix = prefix.substr(0, prefix.rfind('.'));
959    }
960    if (!prefix.empty()) {
961      prefix = prefix + "-";
962    }
963
964    base_img = base_img.substr(0, last_img_slash + 1);
965
966    // Note: we have some special case here for our testing. We have to inject the differentiating
967    //       parts for the different core images.
968    std::string infix;  // Empty infix by default.
969    {
970      // Check the first name.
971      std::string dex_file = oat_filenames_[0];
972      size_t last_dex_slash = dex_file.rfind('/');
973      if (last_dex_slash != std::string::npos) {
974        dex_file = dex_file.substr(last_dex_slash + 1);
975      }
976      size_t last_dex_dot = dex_file.rfind('.');
977      if (last_dex_dot != std::string::npos) {
978        dex_file = dex_file.substr(0, last_dex_dot);
979      }
980      if (StartsWith(dex_file, "core-")) {
981        infix = dex_file.substr(strlen("core"));
982      }
983    }
984
985    // Now create the other names. Use a counted loop to skip the first one.
986    for (size_t i = 1; i < dex_locations_.size(); ++i) {
987      // TODO: Make everything properly std::string.
988      std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
989      char_backing_storage_.push_back(base_img + image_name);
990      image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
991
992      std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
993      char_backing_storage_.push_back(base_oat + oat_name);
994      oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
995    }
996  }
997
998  // Modify the input string in the following way:
999  //   0) Assume input is /a/b/c.d
1000  //   1) Strip the path  -> c.d
1001  //   2) Inject prefix p -> pc.d
1002  //   3) Inject infix i  -> pci.d
1003  //   4) Replace suffix with s if it's "jar"  -> d == "jar" -> pci.s
1004  static std::string CreateMultiImageName(std::string in,
1005                                          const std::string& prefix,
1006                                          const std::string& infix,
1007                                          const char* replace_suffix) {
1008    size_t last_dex_slash = in.rfind('/');
1009    if (last_dex_slash != std::string::npos) {
1010      in = in.substr(last_dex_slash + 1);
1011    }
1012    if (!prefix.empty()) {
1013      in = prefix + in;
1014    }
1015    if (!infix.empty()) {
1016      // Inject infix.
1017      size_t last_dot = in.rfind('.');
1018      if (last_dot != std::string::npos) {
1019        in.insert(last_dot, infix);
1020      }
1021    }
1022    if (EndsWith(in, ".jar")) {
1023      in = in.substr(0, in.length() - strlen(".jar")) +
1024          (replace_suffix != nullptr ? replace_suffix : "");
1025    }
1026    return in;
1027  }
1028
1029  void InsertCompileOptions(int argc, char** argv) {
1030    std::ostringstream oss;
1031    for (int i = 0; i < argc; ++i) {
1032      if (i > 0) {
1033        oss << ' ';
1034      }
1035      oss << argv[i];
1036    }
1037    key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1038    oss.str("");  // Reset.
1039    oss << kRuntimeISA;
1040    key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1041    key_value_store_->Put(
1042        OatHeader::kPicKey,
1043        compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
1044    key_value_store_->Put(
1045        OatHeader::kDebuggableKey,
1046        compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
1047    key_value_store_->Put(
1048        OatHeader::kNativeDebuggableKey,
1049        compiler_options_->native_debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
1050    if (compiler_options_->IsExtractOnly()) {
1051      key_value_store_->Put(OatHeader::kCompilationType, OatHeader::kExtractOnlyValue);
1052    } else if (UseProfileGuidedCompilation()) {
1053      key_value_store_->Put(OatHeader::kCompilationType, OatHeader::kProfileGuideCompiledValue);
1054    }
1055  }
1056
1057  // Parse the arguments from the command line. In case of an unrecognized option or impossible
1058  // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1059  // returns, arguments have been successfully parsed.
1060  void ParseArgs(int argc, char** argv) {
1061    original_argc = argc;
1062    original_argv = argv;
1063
1064    InitLogging(argv);
1065
1066    // Skip over argv[0].
1067    argv++;
1068    argc--;
1069
1070    if (argc == 0) {
1071      Usage("No arguments specified");
1072    }
1073
1074    std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
1075    compiler_options_.reset(new CompilerOptions());
1076
1077    for (int i = 0; i < argc; i++) {
1078      const StringPiece option(argv[i]);
1079      const bool log_options = false;
1080      if (log_options) {
1081        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1082      }
1083      if (option.starts_with("--dex-file=")) {
1084        dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1085      } else if (option.starts_with("--dex-location=")) {
1086        dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1087      } else if (option.starts_with("--zip-fd=")) {
1088        ParseZipFd(option);
1089      } else if (option.starts_with("--zip-location=")) {
1090        zip_location_ = option.substr(strlen("--zip-location=")).data();
1091      } else if (option.starts_with("--oat-file=")) {
1092        oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
1093      } else if (option.starts_with("--oat-symbols=")) {
1094        parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
1095      } else if (option.starts_with("--oat-fd=")) {
1096        ParseOatFd(option);
1097      } else if (option == "--watch-dog") {
1098        parser_options->watch_dog_enabled = true;
1099      } else if (option == "--no-watch-dog") {
1100        parser_options->watch_dog_enabled = false;
1101      } else if (option.starts_with("-j")) {
1102        ParseJ(option);
1103      } else if (option.starts_with("--oat-location=")) {
1104        oat_location_ = option.substr(strlen("--oat-location=")).data();
1105      } else if (option.starts_with("--image=")) {
1106        image_filenames_.push_back(option.substr(strlen("--image=")).data());
1107      } else if (option.starts_with("--image-classes=")) {
1108        image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1109      } else if (option.starts_with("--image-classes-zip=")) {
1110        image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
1111      } else if (option.starts_with("--image-format=")) {
1112        ParseImageFormat(option);
1113      } else if (option.starts_with("--compiled-classes=")) {
1114        compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1115      } else if (option.starts_with("--compiled-classes-zip=")) {
1116        compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1117      } else if (option.starts_with("--compiled-methods=")) {
1118        compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1119      } else if (option.starts_with("--compiled-methods-zip=")) {
1120        compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1121      } else if (option.starts_with("--base=")) {
1122        ParseBase(option);
1123      } else if (option.starts_with("--boot-image=")) {
1124        parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1125      } else if (option.starts_with("--android-root=")) {
1126        android_root_ = option.substr(strlen("--android-root=")).data();
1127      } else if (option.starts_with("--instruction-set=")) {
1128        ParseInstructionSet(option);
1129      } else if (option.starts_with("--instruction-set-variant=")) {
1130        ParseInstructionSetVariant(option, parser_options.get());
1131      } else if (option.starts_with("--instruction-set-features=")) {
1132        ParseInstructionSetFeatures(option, parser_options.get());
1133      } else if (option.starts_with("--compiler-backend=")) {
1134        ParseCompilerBackend(option, parser_options.get());
1135      } else if (option.starts_with("--profile-file=")) {
1136        profile_file_ = option.substr(strlen("--profile-file=")).ToString();
1137      } else if (option.starts_with("--profile-file-fd=")) {
1138        ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
1139      } else if (option == "--host") {
1140        is_host_ = true;
1141      } else if (option == "--runtime-arg") {
1142        if (++i >= argc) {
1143          Usage("Missing required argument for --runtime-arg");
1144        }
1145        if (log_options) {
1146          LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1147        }
1148        runtime_args_.push_back(argv[i]);
1149      } else if (option == "--dump-timing") {
1150        dump_timing_ = true;
1151      } else if (option == "--dump-passes") {
1152        dump_passes_ = true;
1153      } else if (option == "--dump-stats") {
1154        dump_stats_ = true;
1155      } else if (option.starts_with("--swap-file=")) {
1156        swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1157      } else if (option.starts_with("--swap-fd=")) {
1158        ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1159      } else if (option.starts_with("--app-image-file=")) {
1160        app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1161      } else if (option.starts_with("--app-image-fd=")) {
1162        ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
1163      } else if (option.starts_with("--verbose-methods=")) {
1164        // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1165        //       conditional on having verbost methods.
1166        gLogVerbosity.compiler = false;
1167        Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
1168      } else if (option == "--multi-image") {
1169        multi_image_ = true;
1170      } else if (option.starts_with("--no-inline-from=")) {
1171        no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
1172      } else if (option == "--force-determinism") {
1173        if (!SupportsDeterministicCompilation()) {
1174          Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
1175        }
1176        force_determinism_ = true;
1177      } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
1178        Usage("Unknown argument %s", option.data());
1179      }
1180    }
1181
1182    ProcessOptions(parser_options.get());
1183
1184    // Insert some compiler things.
1185    InsertCompileOptions(argc, argv);
1186  }
1187
1188  // Check whether the oat output files are writable, and open them for later. Also open a swap
1189  // file, if a name is given.
1190  bool OpenFile() {
1191    // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1192    PruneNonExistentDexFiles();
1193
1194    // Expand oat and image filenames for multi image.
1195    if (IsBootImage() && multi_image_) {
1196      ExpandOatAndImageFilenames();
1197    }
1198
1199    bool create_file = oat_fd_ == -1;  // as opposed to using open file descriptor
1200    if (create_file) {
1201      for (const char* oat_filename : oat_filenames_) {
1202        std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1203        if (oat_file.get() == nullptr) {
1204          PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1205          return false;
1206        }
1207        if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1208          PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1209          oat_file->Erase();
1210          return false;
1211        }
1212        oat_files_.push_back(std::move(oat_file));
1213      }
1214    } else {
1215      std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1216      oat_file->DisableAutoClose();
1217      if (oat_file->SetLength(0) != 0) {
1218        PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1219      }
1220      if (oat_file.get() == nullptr) {
1221        PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1222        return false;
1223      }
1224      if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1225        PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1226        oat_file->Erase();
1227        return false;
1228      }
1229      oat_filenames_.push_back(oat_location_.c_str());
1230      oat_files_.push_back(std::move(oat_file));
1231    }
1232
1233    // Swap file handling.
1234    //
1235    // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1236    // that we can use for swap.
1237    //
1238    // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1239    // will immediately unlink to satisfy the swap fd assumption.
1240    if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1241      std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1242      if (swap_file.get() == nullptr) {
1243        PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1244        return false;
1245      }
1246      swap_fd_ = swap_file->Fd();
1247      swap_file->MarkUnchecked();     // We don't we to track this, it will be unlinked immediately.
1248      swap_file->DisableAutoClose();  // We'll handle it ourselves, the File object will be
1249                                      // released immediately.
1250      unlink(swap_file_name_.c_str());
1251    }
1252
1253    // If we use a swap file, ensure we are above the threshold to make it necessary.
1254    if (swap_fd_ != -1) {
1255      if (!UseSwap(IsBootImage(), dex_files_)) {
1256        close(swap_fd_);
1257        swap_fd_ = -1;
1258        VLOG(compiler) << "Decided to run without swap.";
1259      } else {
1260        LOG(INFO) << "Large app, accepted running with swap.";
1261      }
1262    }
1263    // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1264
1265    return true;
1266  }
1267
1268  void EraseOatFiles() {
1269    for (size_t i = 0; i < oat_files_.size(); ++i) {
1270      DCHECK(oat_files_[i].get() != nullptr);
1271      oat_files_[i]->Erase();
1272      oat_files_[i].reset();
1273    }
1274  }
1275
1276  void Shutdown() {
1277    ScopedObjectAccess soa(Thread::Current());
1278    for (jobject dex_cache : dex_caches_) {
1279      soa.Env()->DeleteLocalRef(dex_cache);
1280    }
1281    dex_caches_.clear();
1282  }
1283
1284  void LoadClassProfileDescriptors() {
1285    if (profile_compilation_info_ != nullptr && app_image_) {
1286      Runtime* runtime = Runtime::Current();
1287      CHECK(runtime != nullptr);
1288      std::set<DexCacheResolvedClasses> resolved_classes(
1289          profile_compilation_info_->GetResolvedClasses());
1290      image_classes_.reset(new std::unordered_set<std::string>(
1291          runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes)));
1292      VLOG(compiler) << "Loaded " << image_classes_->size()
1293                     << " image class descriptors from profile";
1294      if (VLOG_IS_ON(compiler)) {
1295        for (const std::string& s : *image_classes_) {
1296          LOG(INFO) << "Image class " << s;
1297        }
1298      }
1299    }
1300  }
1301
1302  // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1303  // boot class path.
1304  bool Setup() {
1305    TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1306    art::MemMap::Init();  // For ZipEntry::ExtractToMemMap.
1307
1308    if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1309      return false;
1310    }
1311
1312    verification_results_.reset(new VerificationResults(compiler_options_.get()));
1313    callbacks_.reset(new QuickCompilerCallbacks(
1314        verification_results_.get(),
1315        &method_inliner_map_,
1316        IsBootImage() ?
1317            CompilerCallbacks::CallbackMode::kCompileBootImage :
1318            CompilerCallbacks::CallbackMode::kCompileApp));
1319
1320    RuntimeArgumentMap runtime_options;
1321    if (!PrepareRuntimeOptions(&runtime_options)) {
1322      return false;
1323    }
1324
1325    CreateOatWriters();
1326    if (!AddDexFileSources()) {
1327      return false;
1328    }
1329
1330    if (IsBootImage() && image_filenames_.size() > 1) {
1331      // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1332      // We need this for the multi-image case.
1333      key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1334    }
1335
1336    if (!IsBootImage()) {
1337      // When compiling an app, create the runtime early to retrieve
1338      // the image location key needed for the oat header.
1339      if (!CreateRuntime(std::move(runtime_options))) {
1340        return false;
1341      }
1342
1343      if (compiler_options_->IsExtractOnly()) {
1344        // ExtractOnly oat files only contain non-quickened DEX code and are
1345        // therefore independent of the image file.
1346        image_file_location_oat_checksum_ = 0u;
1347        image_file_location_oat_data_begin_ = 0u;
1348        image_patch_delta_ = 0;
1349      } else {
1350        TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1351        std::vector<gc::space::ImageSpace*> image_spaces =
1352            Runtime::Current()->GetHeap()->GetBootImageSpaces();
1353        image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1354        image_file_location_oat_data_begin_ =
1355            reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1356        image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1357        // Store the boot image filename(s).
1358        std::vector<std::string> image_filenames;
1359        for (const gc::space::ImageSpace* image_space : image_spaces) {
1360          image_filenames.push_back(image_space->GetImageFilename());
1361        }
1362        std::string image_file_location = Join(image_filenames, ':');
1363        if (!image_file_location.empty()) {
1364          key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1365        }
1366      }
1367
1368      // Open dex files for class path.
1369      const std::vector<std::string> class_path_locations =
1370          GetClassPathLocations(runtime_->GetClassPathString());
1371      OpenClassPathFiles(class_path_locations, &class_path_files_);
1372
1373      // Store the classpath we have right now.
1374      std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1375      key_value_store_->Put(OatHeader::kClassPathKey,
1376                            OatFile::EncodeDexFileDependencies(class_path_files));
1377    }
1378
1379    // Now that we have finalized key_value_store_, start writing the oat file.
1380    {
1381      TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1382      rodata_.reserve(oat_writers_.size());
1383      for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1384        rodata_.push_back(elf_writers_[i]->StartRoData());
1385        // Unzip or copy dex files straight to the oat file.
1386        std::unique_ptr<MemMap> opened_dex_files_map;
1387        std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1388        if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1389                                                   oat_files_[i].get(),
1390                                                   instruction_set_,
1391                                                   instruction_set_features_.get(),
1392                                                   key_value_store_.get(),
1393                                                   /* verify */ true,
1394                                                   &opened_dex_files_map,
1395                                                   &opened_dex_files)) {
1396          return false;
1397        }
1398        dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1399        if (opened_dex_files_map != nullptr) {
1400          opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1401          for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
1402            dex_file_oat_index_map_.emplace(dex_file.get(), i);
1403            opened_dex_files_.push_back(std::move(dex_file));
1404          }
1405        } else {
1406          DCHECK(opened_dex_files.empty());
1407        }
1408      }
1409    }
1410
1411    dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1412    if (IsBootImage()) {
1413      // For boot image, pass opened dex files to the Runtime::Create().
1414      // Note: Runtime acquires ownership of these dex files.
1415      runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
1416      if (!CreateRuntime(std::move(runtime_options))) {
1417        return false;
1418      }
1419    }
1420
1421    // If we're doing the image, override the compiler filter to force full compilation. Must be
1422    // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
1423    // compilation of class initializers.
1424    // Whilst we're in native take the opportunity to initialize well known classes.
1425    Thread* self = Thread::Current();
1426    WellKnownClasses::Init(self->GetJniEnv());
1427
1428    ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1429    if (!IsBootImage()) {
1430      constexpr bool kSaveDexInput = false;
1431      if (kSaveDexInput) {
1432        SaveDexInput();
1433      }
1434
1435      // Handle and ClassLoader creation needs to come after Runtime::Create.
1436      ScopedObjectAccess soa(self);
1437
1438      // Classpath: first the class-path given.
1439      std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(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    // Ensure opened dex files are writable for dex-to-dex transformations.
1448    for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1449      if (!map->Protect(PROT_READ | PROT_WRITE)) {
1450        PLOG(ERROR) << "Failed to make .dex files writeable.";
1451        return false;
1452      }
1453    }
1454
1455    // Ensure that the dex caches stay live since we don't want class unloading
1456    // to occur during compilation.
1457    for (const auto& dex_file : dex_files_) {
1458      ScopedObjectAccess soa(self);
1459      dex_caches_.push_back(soa.AddLocalReference<jobject>(
1460          class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
1461    }
1462
1463    /*
1464     * If we're not in interpret-only or verify-none or verify-at-runtime or verify-profile mode,
1465     * go ahead and compile small applications.  Don't bother to check if we're doing the image.
1466     */
1467    if (!IsBootImage() &&
1468        compiler_options_->IsCompilationEnabled() &&
1469        compiler_kind_ == Compiler::kQuick) {
1470      size_t num_methods = 0;
1471      for (size_t i = 0; i != dex_files_.size(); ++i) {
1472        const DexFile* dex_file = dex_files_[i];
1473        CHECK(dex_file != nullptr);
1474        num_methods += dex_file->NumMethodIds();
1475      }
1476      if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1477        compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1478        VLOG(compiler) << "Below method threshold, compiling anyways";
1479      }
1480    }
1481
1482    return true;
1483  }
1484
1485  // If we need to keep the oat file open for the image writer.
1486  bool ShouldKeepOatFileOpen() const {
1487    return IsImage() && oat_fd_ != kInvalidFd;
1488  }
1489
1490  // Create and invoke the compiler driver. This will compile all the dex files.
1491  void Compile() {
1492    TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1493    compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
1494
1495    // Find the dex files we should not inline from.
1496
1497    std::vector<std::string> no_inline_filters;
1498    Split(no_inline_from_string_, ',', &no_inline_filters);
1499
1500    // For now, on the host always have core-oj removed.
1501    const std::string core_oj = "core-oj";
1502    if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1503      no_inline_filters.push_back(core_oj);
1504    }
1505
1506    if (!no_inline_filters.empty()) {
1507      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1508      std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1509      std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1510          &class_linker->GetBootClassPath(),
1511          &class_path_files,
1512          &dex_files_
1513      };
1514      for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1515        for (const DexFile* dex_file : *dex_file_vector) {
1516          for (const std::string& filter : no_inline_filters) {
1517            // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1518            // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1519            // base location passes the StartsWith() test, so do all extra locations.
1520            std::string dex_location = dex_file->GetLocation();
1521            if (filter.find('/') == std::string::npos) {
1522              // The filter does not contain the path. Remove the path from dex_location as well.
1523              size_t last_slash = dex_file->GetLocation().rfind('/');
1524              if (last_slash != std::string::npos) {
1525                dex_location = dex_location.substr(last_slash + 1);
1526              }
1527            }
1528
1529            if (StartsWith(dex_location, filter.c_str())) {
1530              VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1531              no_inline_from_dex_files_.push_back(dex_file);
1532              break;
1533            }
1534          }
1535        }
1536      }
1537      if (!no_inline_from_dex_files_.empty()) {
1538        compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
1539      }
1540    }
1541
1542    driver_.reset(new CompilerDriver(compiler_options_.get(),
1543                                     verification_results_.get(),
1544                                     &method_inliner_map_,
1545                                     compiler_kind_,
1546                                     instruction_set_,
1547                                     instruction_set_features_.get(),
1548                                     IsBootImage(),
1549                                     image_classes_.release(),
1550                                     compiled_classes_.release(),
1551                                     /* compiled_methods */ nullptr,
1552                                     thread_count_,
1553                                     dump_stats_,
1554                                     dump_passes_,
1555                                     compiler_phases_timings_.get(),
1556                                     swap_fd_,
1557                                     profile_compilation_info_.get()));
1558    driver_->SetDexFilesForOatFile(dex_files_);
1559    driver_->CompileAll(class_loader_, dex_files_, timings_);
1560  }
1561
1562  // Notes on the interleaving of creating the images and oat files to
1563  // ensure the references between the two are correct.
1564  //
1565  // Currently we have a memory layout that looks something like this:
1566  //
1567  // +--------------+
1568  // | images       |
1569  // +--------------+
1570  // | oat files    |
1571  // +--------------+
1572  // | alloc spaces |
1573  // +--------------+
1574  //
1575  // There are several constraints on the loading of the images and oat files.
1576  //
1577  // 1. The images are expected to be loaded at an absolute address and
1578  // contain Objects with absolute pointers within the images.
1579  //
1580  // 2. There are absolute pointers from Methods in the images to their
1581  // code in the oat files.
1582  //
1583  // 3. There are absolute pointers from the code in the oat files to Methods
1584  // in the images.
1585  //
1586  // 4. There are absolute pointers from code in the oat files to other code
1587  // in the oat files.
1588  //
1589  // To get this all correct, we go through several steps.
1590  //
1591  // 1. We prepare offsets for all data in the oat files and calculate
1592  // the oat data size and code size. During this stage, we also set
1593  // oat code offsets in methods for use by the image writer.
1594  //
1595  // 2. We prepare offsets for the objects in the images and calculate
1596  // the image sizes.
1597  //
1598  // 3. We create the oat files. Originally this was just our own proprietary
1599  // file but now it is contained within an ELF dynamic object (aka an .so
1600  // file). Since we know the image sizes and oat data sizes and code sizes we
1601  // can prepare the ELF headers and we then know the ELF memory segment
1602  // layout and we can now resolve all references. The compiler provides
1603  // LinkerPatch information in each CompiledMethod and we resolve these,
1604  // using the layout information and image object locations provided by
1605  // image writer, as we're writing the method code.
1606  //
1607  // 4. We create the image files. They need to know where the oat files
1608  // will be loaded after itself. Originally oat files were simply
1609  // memory mapped so we could predict where their contents were based
1610  // on the file size. Now that they are ELF files, we need to inspect
1611  // the ELF files to understand the in memory segment layout including
1612  // where the oat header is located within.
1613  // TODO: We could just remember this information from step 3.
1614  //
1615  // 5. We fixup the ELF program headers so that dlopen will try to
1616  // load the .so at the desired location at runtime by offsetting the
1617  // Elf32_Phdr.p_vaddr values by the desired base address.
1618  // TODO: Do this in step 3. We already know the layout there.
1619  //
1620  // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1621  // are done by the CreateImageFile() below.
1622
1623  // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1624  // ImageWriter, if necessary.
1625  // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1626  //       case (when the file will be explicitly erased).
1627  bool WriteOatFiles() {
1628    TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1629
1630    // Sync the data to the file, in case we did dex2dex transformations.
1631    for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1632      if (!map->Sync()) {
1633        PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1634        return false;
1635      }
1636    }
1637
1638    if (IsImage()) {
1639      if (app_image_ && image_base_ == 0) {
1640        gc::Heap* const heap = Runtime::Current()->GetHeap();
1641        for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
1642          image_base_ = std::max(image_base_, RoundUp(
1643              reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1644              kPageSize));
1645        }
1646        // The non moving space is right after the oat file. Put the preferred app image location
1647        // right after the non moving space so that we ideally get a continuous immune region for
1648        // the GC.
1649        // Use the default non moving space capacity since dex2oat does not have a separate non-
1650        // moving space. This means the runtime's non moving space space size will be as large
1651        // as the growth limit for dex2oat, but smaller in the zygote.
1652        const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
1653        image_base_ += non_moving_space_capacity;
1654        VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1655      }
1656
1657      image_writer_.reset(new ImageWriter(*driver_,
1658                                          image_base_,
1659                                          compiler_options_->GetCompilePic(),
1660                                          IsAppImage(),
1661                                          image_storage_mode_,
1662                                          oat_filenames_,
1663                                          dex_file_oat_index_map_));
1664
1665      // We need to prepare method offsets in the image address space for direct method patching.
1666      TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1667      if (!image_writer_->PrepareImageAddressSpace()) {
1668        LOG(ERROR) << "Failed to prepare image address space.";
1669        return false;
1670      }
1671    }
1672
1673    linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
1674    {
1675      TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1676      for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
1677        std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1678        std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1679
1680        std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1681        oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1682
1683        size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1684        size_t text_size = oat_writer->GetSize() - rodata_size;
1685        elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1686
1687        if (IsImage()) {
1688          // Update oat layout.
1689          DCHECK(image_writer_ != nullptr);
1690          DCHECK_LT(i, oat_filenames_.size());
1691          image_writer_->UpdateOatFileLayout(i,
1692                                             elf_writer->GetLoadedSize(),
1693                                             oat_writer->GetOatDataOffset(),
1694                                             oat_writer->GetSize());
1695        }
1696      }
1697
1698      for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
1699        std::unique_ptr<File>& oat_file = oat_files_[i];
1700        std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1701        std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1702
1703        oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader()));
1704
1705        // We need to mirror the layout of the ELF file in the compressed debug-info.
1706        // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1707        elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
1708
1709        OutputStream*& rodata = rodata_[i];
1710        DCHECK(rodata != nullptr);
1711        if (!oat_writer->WriteRodata(rodata)) {
1712          LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1713          return false;
1714        }
1715        elf_writer->EndRoData(rodata);
1716        rodata = nullptr;
1717
1718        OutputStream* text = elf_writer->StartText();
1719        if (!oat_writer->WriteCode(text)) {
1720          LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1721          return false;
1722        }
1723        elf_writer->EndText(text);
1724
1725        if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1726                                     image_file_location_oat_checksum_,
1727                                     image_file_location_oat_data_begin_,
1728                                     image_patch_delta_)) {
1729          LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1730          return false;
1731        }
1732
1733        if (IsImage()) {
1734          // Update oat header information.
1735          DCHECK(image_writer_ != nullptr);
1736          DCHECK_LT(i, oat_filenames_.size());
1737          image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1738        }
1739
1740        elf_writer->WriteDynamicSection();
1741        elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1742        elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
1743
1744        if (!elf_writer->End()) {
1745          LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1746          return false;
1747        }
1748
1749        // Flush the oat file.
1750        if (oat_files_[i] != nullptr) {
1751          if (oat_files_[i]->Flush() != 0) {
1752            PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1753            return false;
1754          }
1755        }
1756
1757        VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
1758
1759        oat_writer.reset();
1760        elf_writer.reset();
1761      }
1762    }
1763
1764    return true;
1765  }
1766
1767  // If we are compiling an image, invoke the image creation routine. Else just skip.
1768  bool HandleImage() {
1769    if (IsImage()) {
1770      TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1771      if (!CreateImageFile()) {
1772        return false;
1773      }
1774      VLOG(compiler) << "Images written successfully";
1775    }
1776    return true;
1777  }
1778
1779  // Create a copy from stripped to unstripped.
1780  bool CopyStrippedToUnstripped() {
1781    for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1782      // If we don't want to strip in place, copy from stripped location to unstripped location.
1783      // We need to strip after image creation because FixupElf needs to use .strtab.
1784      if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1785        // If the oat file is still open, flush it.
1786        if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1787          if (!FlushCloseOatFile(i)) {
1788            return false;
1789          }
1790        }
1791
1792        TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1793        std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1794        std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1795        size_t buffer_size = 8192;
1796        std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1797        while (true) {
1798          int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1799          if (bytes_read <= 0) {
1800            break;
1801          }
1802          bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1803          CHECK(write_ok);
1804        }
1805        if (out->FlushCloseOrErase() != 0) {
1806          PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1807          return false;
1808        }
1809        VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1810      }
1811    }
1812    return true;
1813  }
1814
1815  bool FlushOatFiles() {
1816    TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1817    for (size_t i = 0; i < oat_files_.size(); ++i) {
1818      if (oat_files_[i].get() != nullptr) {
1819        if (oat_files_[i]->Flush() != 0) {
1820          PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1821          oat_files_[i]->Erase();
1822          return false;
1823        }
1824      }
1825    }
1826    return true;
1827  }
1828
1829  bool FlushCloseOatFile(size_t i) {
1830    if (oat_files_[i].get() != nullptr) {
1831      std::unique_ptr<File> tmp(oat_files_[i].release());
1832      if (tmp->FlushCloseOrErase() != 0) {
1833        PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
1834        return false;
1835      }
1836    }
1837    return true;
1838  }
1839
1840  bool FlushCloseOatFiles() {
1841    bool result = true;
1842    for (size_t i = 0; i < oat_files_.size(); ++i) {
1843      result &= FlushCloseOatFile(i);
1844    }
1845    return result;
1846  }
1847
1848  void DumpTiming() {
1849    if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1850      LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1851    }
1852    if (dump_passes_) {
1853      LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1854    }
1855  }
1856
1857  CompilerOptions* GetCompilerOptions() const {
1858    return compiler_options_.get();
1859  }
1860
1861  bool IsImage() const {
1862    return IsAppImage() || IsBootImage();
1863  }
1864
1865  bool IsAppImage() const {
1866    return app_image_;
1867  }
1868
1869  bool IsBootImage() const {
1870    return boot_image_;
1871  }
1872
1873  bool IsHost() const {
1874    return is_host_;
1875  }
1876
1877  bool UseProfileGuidedCompilation() const {
1878    return !profile_file_.empty() || (profile_file_fd_ != kInvalidFd);
1879  }
1880
1881  bool LoadProfile() {
1882    DCHECK(UseProfileGuidedCompilation());
1883
1884    profile_compilation_info_.reset(new ProfileCompilationInfo());
1885    ScopedFlock flock;
1886    bool success = false;
1887    std::string error;
1888    if (profile_file_fd_ != -1) {
1889      // The file doesn't need to be flushed so don't check the usage.
1890      // Pass a bogus path so that we can easily attribute any reported error.
1891      File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1892      if (flock.Init(&file, &error)) {
1893        success = profile_compilation_info_->Load(profile_file_fd_);
1894      }
1895    } else {
1896      if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1897        success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1898      }
1899    }
1900    if (!error.empty()) {
1901      LOG(WARNING) << "Cannot lock profiles: " << error;
1902    }
1903
1904    if (!success) {
1905      profile_compilation_info_.reset(nullptr);
1906    }
1907
1908    return success;
1909  }
1910
1911 private:
1912  template <typename T>
1913  static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1914    std::vector<T*> result;
1915    result.reserve(src.size());
1916    for (const std::unique_ptr<T>& t : src) {
1917      result.push_back(t.get());
1918    }
1919    return result;
1920  }
1921
1922  std::string GetMultiImageBootClassPath() {
1923    DCHECK(IsBootImage());
1924    DCHECK_GT(oat_filenames_.size(), 1u);
1925    // If the image filename was adapted (e.g., for our tests), we need to change this here,
1926    // too, but need to strip all path components (they will be re-established when loading).
1927    std::ostringstream bootcp_oss;
1928    bool first_bootcp = true;
1929    for (size_t i = 0; i < dex_locations_.size(); ++i) {
1930      if (!first_bootcp) {
1931        bootcp_oss << ":";
1932      }
1933
1934      std::string dex_loc = dex_locations_[i];
1935      std::string image_filename = image_filenames_[i];
1936
1937      // Use the dex_loc path, but the image_filename name (without path elements).
1938      size_t dex_last_slash = dex_loc.rfind('/');
1939
1940      // npos is max(size_t). That makes this a bit ugly.
1941      size_t image_last_slash = image_filename.rfind('/');
1942      size_t image_last_at = image_filename.rfind('@');
1943      size_t image_last_sep = (image_last_slash == std::string::npos)
1944                                  ? image_last_at
1945                                  : (image_last_at == std::string::npos)
1946                                        ? std::string::npos
1947                                        : std::max(image_last_slash, image_last_at);
1948      // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1949
1950      if (dex_last_slash == std::string::npos) {
1951        dex_loc = image_filename.substr(image_last_sep + 1);
1952      } else {
1953        dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1954            image_filename.substr(image_last_sep + 1);
1955      }
1956
1957      // Image filenames already end with .art, no need to replace.
1958
1959      bootcp_oss << dex_loc;
1960      first_bootcp = false;
1961    }
1962    return bootcp_oss.str();
1963  }
1964
1965  std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1966    // This function is used only for apps and for an app we have exactly one oat file.
1967    DCHECK(!IsBootImage());
1968    DCHECK_EQ(oat_writers_.size(), 1u);
1969    std::vector<std::string> dex_files_canonical_locations;
1970    for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1971      dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
1972    }
1973
1974    std::vector<std::string> parsed;
1975    Split(class_path, ':', &parsed);
1976    auto kept_it = std::remove_if(parsed.begin(),
1977                                  parsed.end(),
1978                                  [dex_files_canonical_locations](const std::string& location) {
1979      return ContainsElement(dex_files_canonical_locations,
1980                             DexFile::GetDexCanonicalLocation(location.c_str()));
1981    });
1982    parsed.erase(kept_it, parsed.end());
1983    return parsed;
1984  }
1985
1986  // Opens requested class path files and appends them to opened_dex_files.
1987  static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1988                                 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1989    DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1990    for (const std::string& location : class_path_locations) {
1991      std::string error_msg;
1992      if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1993        LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
1994      }
1995    }
1996  }
1997
1998  bool PrepareImageClasses() {
1999    // If --image-classes was specified, calculate the full list of classes to include in the image.
2000    if (image_classes_filename_ != nullptr) {
2001      image_classes_ =
2002          ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
2003      if (image_classes_ == nullptr) {
2004        return false;
2005      }
2006    } else if (IsBootImage()) {
2007      image_classes_.reset(new std::unordered_set<std::string>);
2008    }
2009    return true;
2010  }
2011
2012  bool PrepareCompiledClasses() {
2013    // If --compiled-classes was specified, calculate the full list of classes to compile in the
2014    // image.
2015    if (compiled_classes_filename_ != nullptr) {
2016      compiled_classes_ =
2017          ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2018      if (compiled_classes_ == nullptr) {
2019        return false;
2020      }
2021    } else {
2022      compiled_classes_.reset(nullptr);  // By default compile everything.
2023    }
2024    return true;
2025  }
2026
2027  static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2028                                                                      const char* classes_filename,
2029                                                                      const char* tag) {
2030    std::unique_ptr<std::unordered_set<std::string>> classes;
2031    std::string error_msg;
2032    if (zip_filename != nullptr) {
2033      classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2034    } else {
2035      classes.reset(ReadImageClassesFromFile(classes_filename));
2036    }
2037    if (classes == nullptr) {
2038      LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2039                 << classes_filename << "': " << error_msg;
2040    }
2041    return classes;
2042  }
2043
2044  bool PrepareCompiledMethods() {
2045    // If --compiled-methods was specified, read the methods to compile from the given file(s).
2046    if (compiled_methods_filename_ != nullptr) {
2047      std::string error_msg;
2048      if (compiled_methods_zip_filename_ != nullptr) {
2049        compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2050                                                          compiled_methods_filename_,
2051                                                          nullptr,            // No post-processing.
2052                                                          &error_msg));
2053      } else {
2054        compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2055                                                           nullptr));         // No post-processing.
2056      }
2057      if (compiled_methods_.get() == nullptr) {
2058        LOG(ERROR) << "Failed to create list of compiled methods from '"
2059            << compiled_methods_filename_ << "': " << error_msg;
2060        return false;
2061      }
2062    } else {
2063      compiled_methods_.reset(nullptr);  // By default compile everything.
2064    }
2065    return true;
2066  }
2067
2068  void PruneNonExistentDexFiles() {
2069    DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2070    size_t kept = 0u;
2071    for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2072      if (!OS::FileExists(dex_filenames_[i])) {
2073        LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2074      } else {
2075        dex_filenames_[kept] = dex_filenames_[i];
2076        dex_locations_[kept] = dex_locations_[i];
2077        ++kept;
2078      }
2079    }
2080    dex_filenames_.resize(kept);
2081    dex_locations_.resize(kept);
2082  }
2083
2084  bool AddDexFileSources() {
2085    TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2086    if (zip_fd_ != -1) {
2087      DCHECK_EQ(oat_writers_.size(), 1u);
2088      if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2089        return false;
2090      }
2091    } else if (oat_writers_.size() > 1u) {
2092      // Multi-image.
2093      DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2094      DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2095      for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2096        if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2097          return false;
2098        }
2099      }
2100    } else {
2101      DCHECK_EQ(oat_writers_.size(), 1u);
2102      DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2103      DCHECK_NE(dex_filenames_.size(), 0u);
2104      for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2105        if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2106          return false;
2107        }
2108      }
2109    }
2110    return true;
2111  }
2112
2113  void CreateOatWriters() {
2114    TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2115    elf_writers_.reserve(oat_files_.size());
2116    oat_writers_.reserve(oat_files_.size());
2117    for (const std::unique_ptr<File>& oat_file : oat_files_) {
2118      elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2119                                                     instruction_set_features_.get(),
2120                                                     compiler_options_.get(),
2121                                                     oat_file.get()));
2122      elf_writers_.back()->Start();
2123      oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2124    }
2125  }
2126
2127  void SaveDexInput() {
2128    for (size_t i = 0; i < dex_files_.size(); ++i) {
2129      const DexFile* dex_file = dex_files_[i];
2130      std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2131                                             getpid(), i));
2132      std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2133      if (tmp_file.get() == nullptr) {
2134        PLOG(ERROR) << "Failed to open file " << tmp_file_name
2135            << ". Try: adb shell chmod 777 /data/local/tmp";
2136        continue;
2137      }
2138      // This is just dumping files for debugging. Ignore errors, and leave remnants.
2139      UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2140      UNUSED(tmp_file->Flush());
2141      UNUSED(tmp_file->Close());
2142      LOG(INFO) << "Wrote input to " << tmp_file_name;
2143    }
2144  }
2145
2146  bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2147    RuntimeOptions raw_options;
2148    if (boot_image_filename_.empty()) {
2149      std::string boot_class_path = "-Xbootclasspath:";
2150      boot_class_path += Join(dex_filenames_, ':');
2151      raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2152      std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2153      boot_class_path_locations += Join(dex_locations_, ':');
2154      raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2155    } else {
2156      std::string boot_image_option = "-Ximage:";
2157      boot_image_option += boot_image_filename_;
2158      raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2159    }
2160    for (size_t i = 0; i < runtime_args_.size(); i++) {
2161      raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2162    }
2163
2164    raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2165    raw_options.push_back(
2166        std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2167
2168    // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2169    // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2170    // have been stripped in preopting, anyways).
2171    if (!IsBootImage()) {
2172      raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2173    }
2174    // Disable libsigchain. We don't don't need it during compilation and it prevents us
2175    // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2176    raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
2177    // Disable Hspace compaction to save heap size virtual space.
2178    // Only need disable Hspace for OOM becasue background collector is equal to
2179    // foreground collector by default for dex2oat.
2180    raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
2181
2182    // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2183    // force the free-list implementation for large objects.
2184    if (compiler_options_->IsForceDeterminism()) {
2185      raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2186      raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2187
2188      // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2189      // compaction (done above) and ensure that neither foreground nor background collectors
2190      // are concurrent.
2191      raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2192
2193      // To make identity hashcode deterministic, set a known seed.
2194      mirror::Object::SetHashCodeSeed(987654321U);
2195    }
2196
2197    if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2198      LOG(ERROR) << "Failed to parse runtime options";
2199      return false;
2200    }
2201    return true;
2202  }
2203
2204  // Create a runtime necessary for compilation.
2205  bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2206    TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
2207    if (!Runtime::Create(std::move(runtime_options))) {
2208      LOG(ERROR) << "Failed to create runtime";
2209      return false;
2210    }
2211    runtime_.reset(Runtime::Current());
2212    runtime_->SetInstructionSet(instruction_set_);
2213    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2214      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
2215      if (!runtime_->HasCalleeSaveMethod(type)) {
2216        runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
2217      }
2218    }
2219    runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
2220
2221    // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2222    // set up.
2223    interpreter::UnstartedRuntime::Initialize();
2224
2225    runtime_->GetClassLinker()->RunRootClinits();
2226
2227    // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2228    // Runtime::Start, give it away now so that we don't starve GC.
2229    Thread* self = Thread::Current();
2230    self->TransitionFromRunnableToSuspended(kNative);
2231
2232    return true;
2233  }
2234
2235  // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files.
2236  bool CreateImageFile()
2237      REQUIRES(!Locks::mutator_lock_) {
2238    CHECK(image_writer_ != nullptr);
2239    if (!IsBootImage()) {
2240      CHECK(image_filenames_.empty());
2241      image_filenames_.push_back(app_image_file_name_.c_str());
2242    }
2243    if (!image_writer_->Write(app_image_fd_,
2244                              image_filenames_,
2245                              oat_filenames_)) {
2246      LOG(ERROR) << "Failure during image file creation";
2247      return false;
2248    }
2249
2250    // We need the OatDataBegin entries.
2251    dchecked_vector<uintptr_t> oat_data_begins;
2252    for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2253      oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
2254    }
2255    // Destroy ImageWriter before doing FixupElf.
2256    image_writer_.reset();
2257
2258    for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2259      const char* oat_filename = oat_filenames_[i];
2260      // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2261      if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2262        std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2263        if (oat_file.get() == nullptr) {
2264          PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2265          return false;
2266        }
2267
2268        if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
2269          oat_file->Erase();
2270          LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2271          return false;
2272        }
2273
2274        if (oat_file->FlushCloseOrErase()) {
2275          PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2276          return false;
2277        }
2278      }
2279    }
2280
2281    return true;
2282  }
2283
2284  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
2285  static std::unordered_set<std::string>* ReadImageClassesFromFile(
2286      const char* image_classes_filename) {
2287    std::function<std::string(const char*)> process = DotToDescriptor;
2288    return ReadCommentedInputFromFile(image_classes_filename, &process);
2289  }
2290
2291  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
2292  static std::unordered_set<std::string>* ReadImageClassesFromZip(
2293        const char* zip_filename,
2294        const char* image_classes_filename,
2295        std::string* error_msg) {
2296    std::function<std::string(const char*)> process = DotToDescriptor;
2297    return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2298  }
2299
2300  // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2301  // the given function.
2302  static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2303      const char* input_filename, std::function<std::string(const char*)>* process) {
2304    std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2305    if (input_file.get() == nullptr) {
2306      LOG(ERROR) << "Failed to open input file " << input_filename;
2307      return nullptr;
2308    }
2309    std::unique_ptr<std::unordered_set<std::string>> result(
2310        ReadCommentedInputStream(*input_file, process));
2311    input_file->close();
2312    return result.release();
2313  }
2314
2315  // Read lines from the given file from the given zip file, dropping comments and empty lines.
2316  // Post-process each line with the given function.
2317  static std::unordered_set<std::string>* ReadCommentedInputFromZip(
2318      const char* zip_filename,
2319      const char* input_filename,
2320      std::function<std::string(const char*)>* process,
2321      std::string* error_msg) {
2322    std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2323    if (zip_archive.get() == nullptr) {
2324      return nullptr;
2325    }
2326    std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
2327    if (zip_entry.get() == nullptr) {
2328      *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
2329                                zip_filename, error_msg->c_str());
2330      return nullptr;
2331    }
2332    std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2333                                                                  input_filename,
2334                                                                  error_msg));
2335    if (input_file.get() == nullptr) {
2336      *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
2337                                zip_filename, error_msg->c_str());
2338      return nullptr;
2339    }
2340    const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2341                                   input_file->Size());
2342    std::istringstream input_stream(input_string);
2343    return ReadCommentedInputStream(input_stream, process);
2344  }
2345
2346  // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2347  // with the given function.
2348  static std::unordered_set<std::string>* ReadCommentedInputStream(
2349      std::istream& in_stream,
2350      std::function<std::string(const char*)>* process) {
2351    std::unique_ptr<std::unordered_set<std::string>> image_classes(
2352        new std::unordered_set<std::string>);
2353    while (in_stream.good()) {
2354      std::string dot;
2355      std::getline(in_stream, dot);
2356      if (StartsWith(dot, "#") || dot.empty()) {
2357        continue;
2358      }
2359      if (process != nullptr) {
2360        std::string descriptor((*process)(dot.c_str()));
2361        image_classes->insert(descriptor);
2362      } else {
2363        image_classes->insert(dot);
2364      }
2365    }
2366    return image_classes.release();
2367  }
2368
2369  void LogCompletionTime() {
2370    // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2371    //       is no image, there won't be a Runtime::Current().
2372    // Note: driver creation can fail when loading an invalid dex file.
2373    LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
2374              << " (threads: " << thread_count_ << ") "
2375              << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
2376                  driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2377                  "");
2378  }
2379
2380  std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2381    std::string res(image_filename);
2382    size_t last_slash = res.rfind('/');
2383    if (last_slash == std::string::npos || last_slash == 0) {
2384      return res;
2385    }
2386    size_t penultimate_slash = res.rfind('/', last_slash - 1);
2387    if (penultimate_slash == std::string::npos) {
2388      return res;
2389    }
2390    // Check that the string in-between is the expected one.
2391    if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2392            GetInstructionSetString(isa)) {
2393      LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2394      return res;
2395    }
2396    return res.substr(0, penultimate_slash) + res.substr(last_slash);
2397  }
2398
2399  std::unique_ptr<CompilerOptions> compiler_options_;
2400  Compiler::Kind compiler_kind_;
2401
2402  InstructionSet instruction_set_;
2403  std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2404
2405  uint32_t image_file_location_oat_checksum_;
2406  uintptr_t image_file_location_oat_data_begin_;
2407  int32_t image_patch_delta_;
2408  std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2409
2410  std::unique_ptr<VerificationResults> verification_results_;
2411
2412  DexFileToMethodInlinerMap method_inliner_map_;
2413  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2414
2415  std::unique_ptr<Runtime> runtime_;
2416
2417  // Ownership for the class path files.
2418  std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2419
2420  size_t thread_count_;
2421  uint64_t start_ns_;
2422  std::unique_ptr<WatchDog> watchdog_;
2423  std::vector<std::unique_ptr<File>> oat_files_;
2424  std::string oat_location_;
2425  std::vector<const char*> oat_filenames_;
2426  std::vector<const char*> oat_unstripped_;
2427  int oat_fd_;
2428  std::vector<const char*> dex_filenames_;
2429  std::vector<const char*> dex_locations_;
2430  int zip_fd_;
2431  std::string zip_location_;
2432  std::string boot_image_filename_;
2433  std::vector<const char*> runtime_args_;
2434  std::vector<const char*> image_filenames_;
2435  uintptr_t image_base_;
2436  const char* image_classes_zip_filename_;
2437  const char* image_classes_filename_;
2438  ImageHeader::StorageMode image_storage_mode_;
2439  const char* compiled_classes_zip_filename_;
2440  const char* compiled_classes_filename_;
2441  const char* compiled_methods_zip_filename_;
2442  const char* compiled_methods_filename_;
2443  std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2444  std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
2445  std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
2446  bool app_image_;
2447  bool boot_image_;
2448  bool multi_image_;
2449  bool is_host_;
2450  std::string android_root_;
2451  std::vector<const DexFile*> dex_files_;
2452  std::string no_inline_from_string_;
2453  std::vector<jobject> dex_caches_;
2454  jobject class_loader_;
2455
2456  std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2457  std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2458  std::vector<OutputStream*> rodata_;
2459  std::unique_ptr<ImageWriter> image_writer_;
2460  std::unique_ptr<CompilerDriver> driver_;
2461
2462  std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2463  std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2464
2465  std::vector<const DexFile*> no_inline_from_dex_files_;
2466
2467  std::vector<std::string> verbose_methods_;
2468  bool dump_stats_;
2469  bool dump_passes_;
2470  bool dump_timing_;
2471  bool dump_slow_timing_;
2472  std::string swap_file_name_;
2473  int swap_fd_;
2474  std::string app_image_file_name_;
2475  int app_image_fd_;
2476  std::string profile_file_;
2477  int profile_file_fd_;
2478  std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
2479  TimingLogger* timings_;
2480  std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
2481  std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2482  std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
2483
2484  // Backing storage.
2485  std::vector<std::string> char_backing_storage_;
2486
2487  // See CompilerOptions.force_determinism_.
2488  bool force_determinism_;
2489
2490  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2491};
2492
2493static void b13564922() {
2494#if defined(__linux__) && defined(__arm__)
2495  int major, minor;
2496  struct utsname uts;
2497  if (uname(&uts) != -1 &&
2498      sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2499      ((major < 3) || ((major == 3) && (minor < 4)))) {
2500    // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2501    // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2502    int old_personality = personality(0xffffffff);
2503    if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2504      int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2505      if (new_personality == -1) {
2506        LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2507      }
2508    }
2509  }
2510#endif
2511}
2512
2513static int CompileImage(Dex2Oat& dex2oat) {
2514  dex2oat.LoadClassProfileDescriptors();
2515  dex2oat.Compile();
2516
2517  if (!dex2oat.WriteOatFiles()) {
2518    dex2oat.EraseOatFiles();
2519    return EXIT_FAILURE;
2520  }
2521
2522  // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2523  // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2524  // image writer will require this fd to generate the image.
2525  if (dex2oat.ShouldKeepOatFileOpen()) {
2526    if (!dex2oat.FlushOatFiles()) {
2527      return EXIT_FAILURE;
2528    }
2529  } else if (!dex2oat.FlushCloseOatFiles()) {
2530    return EXIT_FAILURE;
2531  }
2532
2533  // Creates the boot.art and patches the oat files.
2534  if (!dex2oat.HandleImage()) {
2535    return EXIT_FAILURE;
2536  }
2537
2538  // When given --host, finish early without stripping.
2539  if (dex2oat.IsHost()) {
2540    dex2oat.DumpTiming();
2541    return EXIT_SUCCESS;
2542  }
2543
2544  // Copy stripped to unstripped location, if necessary.
2545  if (!dex2oat.CopyStrippedToUnstripped()) {
2546    return EXIT_FAILURE;
2547  }
2548
2549  // FlushClose again, as stripping might have re-opened the oat files.
2550  if (!dex2oat.FlushCloseOatFiles()) {
2551    return EXIT_FAILURE;
2552  }
2553
2554  dex2oat.DumpTiming();
2555  return EXIT_SUCCESS;
2556}
2557
2558static int CompileApp(Dex2Oat& dex2oat) {
2559  dex2oat.Compile();
2560
2561  if (!dex2oat.WriteOatFiles()) {
2562    dex2oat.EraseOatFiles();
2563    return EXIT_FAILURE;
2564  }
2565
2566  // Do not close the oat files here. We might have gotten the output file by file descriptor,
2567  // which we would lose.
2568
2569  // When given --host, finish early without stripping.
2570  if (dex2oat.IsHost()) {
2571    if (!dex2oat.FlushCloseOatFiles()) {
2572      return EXIT_FAILURE;
2573    }
2574
2575    dex2oat.DumpTiming();
2576    return EXIT_SUCCESS;
2577  }
2578
2579  // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2580  // stripped versions. If this is given, we expect to be able to open writable files by name.
2581  if (!dex2oat.CopyStrippedToUnstripped()) {
2582    return EXIT_FAILURE;
2583  }
2584
2585  // Flush and close the files.
2586  if (!dex2oat.FlushCloseOatFiles()) {
2587    return EXIT_FAILURE;
2588  }
2589
2590  dex2oat.DumpTiming();
2591  return EXIT_SUCCESS;
2592}
2593
2594static int dex2oat(int argc, char** argv) {
2595  b13564922();
2596
2597  TimingLogger timings("compiler", false, false);
2598
2599  // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2600  // might produce a stack frame too large for this function or for
2601  // functions inlining it (such as main), that would not fit the
2602  // requirements of the `-Wframe-larger-than` option.
2603  std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
2604
2605  // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2606  dex2oat->ParseArgs(argc, argv);
2607
2608  // If needed, process profile information for profile guided compilation.
2609  // This operation involves I/O.
2610  if (dex2oat->UseProfileGuidedCompilation()) {
2611    if (!dex2oat->LoadProfile()) {
2612      LOG(ERROR) << "Failed to process profile file";
2613      return EXIT_FAILURE;
2614    }
2615  }
2616
2617  // Check early that the result of compilation can be written
2618  if (!dex2oat->OpenFile()) {
2619    return EXIT_FAILURE;
2620  }
2621
2622  // Print the complete line when any of the following is true:
2623  //   1) Debug build
2624  //   2) Compiling an image
2625  //   3) Compiling with --host
2626  //   4) Compiling on the host (not a target build)
2627  // Otherwise, print a stripped command line.
2628  if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
2629    LOG(INFO) << CommandLine();
2630  } else {
2631    LOG(INFO) << StrippedCommandLine();
2632  }
2633
2634  if (!dex2oat->Setup()) {
2635    dex2oat->EraseOatFiles();
2636    return EXIT_FAILURE;
2637  }
2638
2639  bool result;
2640  if (dex2oat->IsImage()) {
2641    result = CompileImage(*dex2oat);
2642  } else {
2643    result = CompileApp(*dex2oat);
2644  }
2645
2646  dex2oat->Shutdown();
2647  return result;
2648}
2649}  // namespace art
2650
2651int main(int argc, char** argv) {
2652  int result = art::dex2oat(argc, argv);
2653  // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2654  // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2655  // should not destruct the runtime in this case.
2656  if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
2657    exit(result);
2658  }
2659  return result;
2660}
2661