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