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