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