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