dex2oat.cc revision dcdc85bbd569f0ee66c331b4219c19304a616214
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      base_oat = base_oat.substr(0, last_oat_slash + 1);
858
859      std::string base_img = image_filenames_[0];
860      size_t last_img_slash = base_img.rfind('/');
861      if (last_img_slash == std::string::npos) {
862        Usage("--multi-image used with unusable image filename %s", base_img.c_str());
863      }
864      base_img = base_img.substr(0, last_img_slash + 1);
865
866      // Now create the other names.
867      // Note: we have some special case here for our testing. We have to inject the differentiating
868      //       parts for the different core images.
869      std::string infix;  // Empty infix by default.
870      {
871        // Check the first name.
872        std::string dex_file = oat_filenames_[0];
873        size_t last_dex_slash = dex_file.rfind('/');
874        if (last_dex_slash != std::string::npos) {
875          dex_file = dex_file.substr(last_dex_slash + 1);
876        }
877        size_t last_dex_dot = dex_file.rfind('.');
878        if (last_dex_dot != std::string::npos) {
879          dex_file = dex_file.substr(0, last_dex_dot);
880        }
881        if (StartsWith(dex_file, "core-")) {
882          infix = dex_file.substr(strlen("core"));
883        }
884      }
885      // Use a counted loop to skip the first one.
886      for (size_t i = 1; i < dex_locations_.size(); ++i) {
887        // TODO: Make everything properly std::string.
888        std::string image_name = CreateMultiImageName(dex_locations_[i], infix, ".art");
889        char_backing_storage_.push_back(base_img + image_name);
890        image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
891
892        std::string oat_name = CreateMultiImageName(dex_locations_[i], infix, ".oat");
893        char_backing_storage_.push_back(base_oat + oat_name);
894        oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
895      }
896    }
897
898    // Done with usage checks, enable watchdog if requested
899    if (parser_options->watch_dog_enabled) {
900      watchdog_.reset(new WatchDog(true));
901    }
902
903    // Fill some values into the key-value store for the oat header.
904    key_value_store_.reset(new SafeMap<std::string, std::string>());
905  }
906
907  static std::string CreateMultiImageName(std::string in,
908                                          const std::string& infix,
909                                          const char* suffix) {
910    size_t last_dex_slash = in.rfind('/');
911    if (last_dex_slash != std::string::npos) {
912      in = in.substr(last_dex_slash + 1);
913    }
914    if (!infix.empty()) {
915      // Inject infix.
916      size_t last_dot = in.rfind('.');
917      if (last_dot != std::string::npos) {
918        in.insert(last_dot, infix);
919      }
920    }
921    if (EndsWith(in, ".jar")) {
922      in = in.substr(0, in.length() - strlen(".jar")) + (suffix != nullptr ? suffix : "");
923    }
924    return in;
925  }
926
927  void InsertCompileOptions(int argc, char** argv) {
928    std::ostringstream oss;
929    for (int i = 0; i < argc; ++i) {
930      if (i > 0) {
931        oss << ' ';
932      }
933      oss << argv[i];
934    }
935    key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
936    oss.str("");  // Reset.
937    oss << kRuntimeISA;
938    key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
939    key_value_store_->Put(
940        OatHeader::kPicKey,
941        compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
942    key_value_store_->Put(
943        OatHeader::kDebuggableKey,
944        compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
945  }
946
947  // Parse the arguments from the command line. In case of an unrecognized option or impossible
948  // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
949  // returns, arguments have been successfully parsed.
950  void ParseArgs(int argc, char** argv) {
951    original_argc = argc;
952    original_argv = argv;
953
954    InitLogging(argv);
955
956    // Skip over argv[0].
957    argv++;
958    argc--;
959
960    if (argc == 0) {
961      Usage("No arguments specified");
962    }
963
964    std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
965    compiler_options_.reset(new CompilerOptions());
966
967    bool multi_image = false;
968
969    for (int i = 0; i < argc; i++) {
970      const StringPiece option(argv[i]);
971      const bool log_options = false;
972      if (log_options) {
973        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
974      }
975      if (option.starts_with("--dex-file=")) {
976        dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
977      } else if (option.starts_with("--dex-location=")) {
978        dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
979      } else if (option.starts_with("--zip-fd=")) {
980        ParseZipFd(option);
981      } else if (option.starts_with("--zip-location=")) {
982        zip_location_ = option.substr(strlen("--zip-location=")).data();
983      } else if (option.starts_with("--oat-file=")) {
984        oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
985      } else if (option.starts_with("--oat-symbols=")) {
986        parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
987      } else if (option.starts_with("--oat-fd=")) {
988        ParseOatFd(option);
989      } else if (option == "--watch-dog") {
990        parser_options->watch_dog_enabled = true;
991      } else if (option == "--no-watch-dog") {
992        parser_options->watch_dog_enabled = false;
993      } else if (option.starts_with("-j")) {
994        ParseJ(option);
995      } else if (option.starts_with("--oat-location=")) {
996        oat_location_ = option.substr(strlen("--oat-location=")).data();
997      } else if (option.starts_with("--image=")) {
998        image_filenames_.push_back(option.substr(strlen("--image=")).data());
999      } else if (option.starts_with("--image-classes=")) {
1000        image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1001      } else if (option.starts_with("--image-classes-zip=")) {
1002        image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
1003      } else if (option.starts_with("--image-format=")) {
1004        ParseImageFormat(option);
1005      } else if (option.starts_with("--compiled-classes=")) {
1006        compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1007      } else if (option.starts_with("--compiled-classes-zip=")) {
1008        compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1009      } else if (option.starts_with("--compiled-methods=")) {
1010        compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1011      } else if (option.starts_with("--compiled-methods-zip=")) {
1012        compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1013      } else if (option.starts_with("--base=")) {
1014        ParseBase(option);
1015      } else if (option.starts_with("--boot-image=")) {
1016        parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1017      } else if (option.starts_with("--android-root=")) {
1018        android_root_ = option.substr(strlen("--android-root=")).data();
1019      } else if (option.starts_with("--instruction-set=")) {
1020        ParseInstructionSet(option);
1021      } else if (option.starts_with("--instruction-set-variant=")) {
1022        ParseInstructionSetVariant(option, parser_options.get());
1023      } else if (option.starts_with("--instruction-set-features=")) {
1024        ParseInstructionSetFeatures(option, parser_options.get());
1025      } else if (option.starts_with("--compiler-backend=")) {
1026        ParseCompilerBackend(option, parser_options.get());
1027      } else if (option.starts_with("--profile-file=")) {
1028        profile_file_ = option.substr(strlen("--profile-file=")).data();
1029        VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
1030      } else if (option == "--no-profile-file") {
1031        // No profile
1032      } else if (option == "--host") {
1033        is_host_ = true;
1034      } else if (option == "--runtime-arg") {
1035        if (++i >= argc) {
1036          Usage("Missing required argument for --runtime-arg");
1037        }
1038        if (log_options) {
1039          LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1040        }
1041        runtime_args_.push_back(argv[i]);
1042      } else if (option == "--dump-timing") {
1043        dump_timing_ = true;
1044      } else if (option == "--dump-passes") {
1045        dump_passes_ = true;
1046      } else if (option.starts_with("--dump-cfg=")) {
1047        dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
1048      } else if (option.starts_with("--dump-cfg-append")) {
1049        dump_cfg_append_ = true;
1050      } else if (option == "--dump-stats") {
1051        dump_stats_ = true;
1052      } else if (option.starts_with("--swap-file=")) {
1053        swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1054      } else if (option.starts_with("--swap-fd=")) {
1055        ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1056      } else if (option.starts_with("--app-image-file=")) {
1057        app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1058      } else if (option.starts_with("--app-image-fd=")) {
1059        ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
1060      } else if (option.starts_with("--verbose-methods=")) {
1061        // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1062        //       conditional on having verbost methods.
1063        gLogVerbosity.compiler = false;
1064        Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
1065      } else if (option == "--multi-image") {
1066        multi_image = true;
1067      } else if (option.starts_with("--no-inline-from=")) {
1068        no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
1069      } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
1070        Usage("Unknown argument %s", option.data());
1071      }
1072    }
1073
1074    ProcessOptions(parser_options.get(), multi_image);
1075
1076    // Insert some compiler things.
1077    InsertCompileOptions(argc, argv);
1078  }
1079
1080  // Check whether the oat output files are writable, and open them for later. Also open a swap
1081  // file, if a name is given.
1082  bool OpenFile() {
1083    bool create_file = oat_fd_ == -1;  // as opposed to using open file descriptor
1084    if (create_file) {
1085      for (const char* oat_filename : oat_filenames_) {
1086        std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1087        if (oat_file.get() == nullptr) {
1088          PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1089          return false;
1090        }
1091        if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1092          PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1093          oat_file->Erase();
1094          return false;
1095        }
1096        oat_files_.push_back(std::move(oat_file));
1097      }
1098    } else {
1099      std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1100      oat_file->DisableAutoClose();
1101      if (oat_file->SetLength(0) != 0) {
1102        PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1103      }
1104      if (oat_file.get() == nullptr) {
1105        PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1106        return false;
1107      }
1108      if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1109        PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1110        oat_file->Erase();
1111        return false;
1112      }
1113      oat_filenames_.push_back(oat_location_.c_str());
1114      oat_files_.push_back(std::move(oat_file));
1115    }
1116
1117    // Swap file handling.
1118    //
1119    // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1120    // that we can use for swap.
1121    //
1122    // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1123    // will immediately unlink to satisfy the swap fd assumption.
1124    if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1125      std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1126      if (swap_file.get() == nullptr) {
1127        PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1128        return false;
1129      }
1130      swap_fd_ = swap_file->Fd();
1131      swap_file->MarkUnchecked();     // We don't we to track this, it will be unlinked immediately.
1132      swap_file->DisableAutoClose();  // We'll handle it ourselves, the File object will be
1133                                      // released immediately.
1134      unlink(swap_file_name_.c_str());
1135    }
1136    return true;
1137  }
1138
1139  void EraseOatFiles() {
1140    for (size_t i = 0; i < oat_files_.size(); ++i) {
1141      DCHECK(oat_files_[i].get() != nullptr);
1142      oat_files_[i]->Erase();
1143      oat_files_[i].reset();
1144    }
1145  }
1146
1147  void Shutdown() {
1148    ScopedObjectAccess soa(Thread::Current());
1149    for (jobject dex_cache : dex_caches_) {
1150      soa.Env()->DeleteLocalRef(dex_cache);
1151    }
1152    dex_caches_.clear();
1153  }
1154
1155  // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1156  // boot class path.
1157  bool Setup() {
1158    TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1159    art::MemMap::Init();  // For ZipEntry::ExtractToMemMap.
1160
1161    if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1162      return false;
1163    }
1164
1165    verification_results_.reset(new VerificationResults(compiler_options_.get()));
1166    callbacks_.reset(new QuickCompilerCallbacks(
1167        verification_results_.get(),
1168        &method_inliner_map_,
1169        IsBootImage() ?
1170            CompilerCallbacks::CallbackMode::kCompileBootImage :
1171            CompilerCallbacks::CallbackMode::kCompileApp));
1172
1173    RuntimeArgumentMap runtime_options;
1174    if (!PrepareRuntimeOptions(&runtime_options)) {
1175      return false;
1176    }
1177
1178    {
1179      TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
1180      if (!CreateRuntime(std::move(runtime_options))) {
1181        return false;
1182      }
1183    }
1184
1185    // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1186    // Runtime::Start, give it away now so that we don't starve GC.
1187    Thread* self = Thread::Current();
1188    self->TransitionFromRunnableToSuspended(kNative);
1189    // If we're doing the image, override the compiler filter to force full compilation. Must be
1190    // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
1191    // compilation of class initializers.
1192    // Whilst we're in native take the opportunity to initialize well known classes.
1193    WellKnownClasses::Init(self->GetJniEnv());
1194
1195    ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1196    if (boot_image_filename_.empty()) {
1197      dex_files_ = class_linker->GetBootClassPath();
1198    } else {
1199      TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
1200      if (dex_filenames_.empty()) {
1201        ATRACE_BEGIN("Opening zip archive from file descriptor");
1202        std::string error_msg;
1203        std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1204                                                                       zip_location_.c_str(),
1205                                                                       &error_msg));
1206        if (zip_archive.get() == nullptr) {
1207          LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1208              << error_msg;
1209          return false;
1210        }
1211        if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
1212          LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1213              << "': " << error_msg;
1214          return false;
1215        }
1216        for (auto& dex_file : opened_dex_files_) {
1217          dex_files_.push_back(dex_file.get());
1218        }
1219        ATRACE_END();
1220      } else {
1221        size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
1222        if (failure_count > 0) {
1223          LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1224          return false;
1225        }
1226        for (auto& dex_file : opened_dex_files_) {
1227          dex_files_.push_back(dex_file.get());
1228        }
1229      }
1230
1231      constexpr bool kSaveDexInput = false;
1232      if (kSaveDexInput) {
1233        SaveDexInput();
1234      }
1235    }
1236    // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1237    // the dex caches stay live since we don't want class unloading to occur during compilation.
1238    for (const auto& dex_file : dex_files_) {
1239      if (!dex_file->EnableWrite()) {
1240        PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1241      }
1242      ScopedObjectAccess soa(self);
1243      dex_caches_.push_back(soa.AddLocalReference<jobject>(
1244          class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
1245      dex_file->CreateTypeLookupTable();
1246    }
1247
1248    // If we use a swap file, ensure we are above the threshold to make it necessary.
1249    if (swap_fd_ != -1) {
1250      if (!UseSwap(IsBootImage(), dex_files_)) {
1251        close(swap_fd_);
1252        swap_fd_ = -1;
1253        VLOG(compiler) << "Decided to run without swap.";
1254      } else {
1255        LOG(INFO) << "Large app, accepted running with swap.";
1256      }
1257    }
1258    // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1259
1260    /*
1261     * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1262     * Don't bother to check if we're doing the image.
1263     */
1264    if (!IsBootImage() &&
1265        compiler_options_->IsCompilationEnabled() &&
1266        compiler_kind_ == Compiler::kQuick) {
1267      size_t num_methods = 0;
1268      for (size_t i = 0; i != dex_files_.size(); ++i) {
1269        const DexFile* dex_file = dex_files_[i];
1270        CHECK(dex_file != nullptr);
1271        num_methods += dex_file->NumMethodIds();
1272      }
1273      if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1274        compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1275        VLOG(compiler) << "Below method threshold, compiling anyways";
1276      }
1277    }
1278
1279    // Organize inputs, handling multi-dex and multiple oat file outputs.
1280    CreateDexOatMappings();
1281
1282    return true;
1283  }
1284
1285  void CreateDexOatMappings() {
1286    if (oat_files_.size() > 1) {
1287      size_t index = 0;
1288      for (size_t i = 0; i < oat_files_.size(); ++i) {
1289        std::vector<const DexFile*> dex_files = { 1, dex_files_[index] };
1290        dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
1291        index++;
1292        while (index < dex_files_.size() &&
1293            (dex_files_[index]->GetBaseLocation() == dex_files_[index - 1]->GetBaseLocation())) {
1294          dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
1295          dex_files.push_back(dex_files_[index]);
1296          index++;
1297        }
1298        dex_files_per_oat_file_.push_back(std::move(dex_files));
1299      }
1300    } else {
1301      dex_files_per_oat_file_.push_back(dex_files_);
1302      for (const DexFile* dex_file : dex_files_) {
1303        dex_file_oat_filename_map_.emplace(dex_file, oat_filenames_[0]);
1304      }
1305    }
1306  }
1307
1308  // Create and invoke the compiler driver. This will compile all the dex files.
1309  void Compile() {
1310    TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1311    compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
1312
1313    // Handle and ClassLoader creation needs to come after Runtime::Create
1314    jobject class_loader = nullptr;
1315    jobject class_path_class_loader = nullptr;
1316    Thread* self = Thread::Current();
1317
1318    if (!boot_image_filename_.empty()) {
1319      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1320      OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
1321      ScopedObjectAccess soa(self);
1322
1323      // Classpath: first the class-path given.
1324      std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1325
1326      // Store the classpath we have right now.
1327      key_value_store_->Put(OatHeader::kClassPathKey,
1328                            OatFile::EncodeDexFileDependencies(class_path_files));
1329
1330      class_path_class_loader = class_linker->CreatePathClassLoader(self,
1331                                                                    class_path_files,
1332                                                                    nullptr);
1333
1334      // Class path loader as parent so that we'll resolve there first.
1335      class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
1336    }
1337
1338    // Find the dex file we should not inline from.
1339
1340    // For now, on the host always have core-oj removed.
1341    if (!kIsTargetBuild && no_inline_from_string_.empty()) {
1342      no_inline_from_string_ = "core-oj";
1343    }
1344
1345    if (!no_inline_from_string_.empty()) {
1346      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1347      std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1348      std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1349          &class_linker->GetBootClassPath(),
1350          &class_path_files,
1351          &dex_files_
1352      };
1353      for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1354        if (dex_file_vector == nullptr) {
1355          continue;
1356        }
1357
1358        bool found = false;
1359
1360        for (const DexFile* dex_file : *dex_file_vector) {
1361          // Try the complete location first.
1362          found = no_inline_from_string_ == dex_file->GetLocation();
1363          // The try just the name.
1364          if (!found) {
1365            size_t last_slash = dex_file->GetLocation().rfind('/');
1366            if (last_slash != std::string::npos) {
1367              found = StartsWith(dex_file->GetLocation().substr(last_slash + 1),
1368                                 no_inline_from_string_.c_str());
1369            }
1370          }
1371
1372          if (found) {
1373            VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1374            compiler_options_->no_inline_from_ = dex_file;
1375            break;
1376          }
1377        }
1378
1379        if (found) {
1380          break;
1381        }
1382      }
1383    }
1384
1385    if (IsBootImage() && image_filenames_.size() > 1) {
1386      // If we're compiling the boot image, store the boot classpath into the Key-Value store. If
1387      // the image filename was adapted (e.g., for our tests), we need to change this here, too. We
1388      // need this for the multi-image case.
1389      std::ostringstream bootcp_oss;
1390      bool first_bootcp = true;
1391      for (size_t i = 0; i < dex_locations_.size(); ++i) {
1392        if (!first_bootcp) {
1393          bootcp_oss << ":";
1394        }
1395
1396        std::string dex_loc = dex_locations_[i];
1397        std::string image_filename = image_filenames_[i];
1398
1399        // Use the dex_loc path, but the image_filename name.
1400        size_t dex_last_slash = dex_loc.rfind('/');
1401        size_t image_last_slash = image_filename.rfind('/');
1402        if (dex_last_slash == std::string::npos) {
1403          dex_loc = image_filename.substr(image_last_slash + 1);
1404        } else {
1405          dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1406              image_filename.substr(image_last_slash + 1);
1407        }
1408
1409        // Image filenames already end with .art, no need to replace.
1410
1411        bootcp_oss << dex_loc;
1412        first_bootcp = false;
1413      }
1414      key_value_store_->Put(OatHeader::kBootClassPath, bootcp_oss.str());
1415    }
1416
1417    driver_.reset(new CompilerDriver(compiler_options_.get(),
1418                                     verification_results_.get(),
1419                                     &method_inliner_map_,
1420                                     compiler_kind_,
1421                                     instruction_set_,
1422                                     instruction_set_features_.get(),
1423                                     IsBootImage(),
1424                                     image_classes_.release(),
1425                                     compiled_classes_.release(),
1426                                     nullptr,
1427                                     thread_count_,
1428                                     dump_stats_,
1429                                     dump_passes_,
1430                                     dump_cfg_file_name_,
1431                                     dump_cfg_append_,
1432                                     compiler_phases_timings_.get(),
1433                                     swap_fd_,
1434                                     profile_file_,
1435                                     &dex_file_oat_filename_map_));
1436
1437    driver_->SetDexFilesForOatFile(dex_files_);
1438    driver_->CompileAll(class_loader, dex_files_, timings_);
1439  }
1440
1441  // TODO: Update comments about how this works for multi image. b/26317072
1442  // Notes on the interleaving of creating the image and oat file to
1443  // ensure the references between the two are correct.
1444  //
1445  // Currently we have a memory layout that looks something like this:
1446  //
1447  // +--------------+
1448  // | image        |
1449  // +--------------+
1450  // | boot oat     |
1451  // +--------------+
1452  // | alloc spaces |
1453  // +--------------+
1454  //
1455  // There are several constraints on the loading of the image and boot.oat.
1456  //
1457  // 1. The image is expected to be loaded at an absolute address and
1458  // contains Objects with absolute pointers within the image.
1459  //
1460  // 2. There are absolute pointers from Methods in the image to their
1461  // code in the oat.
1462  //
1463  // 3. There are absolute pointers from the code in the oat to Methods
1464  // in the image.
1465  //
1466  // 4. There are absolute pointers from code in the oat to other code
1467  // in the oat.
1468  //
1469  // To get this all correct, we go through several steps.
1470  //
1471  // 1. We prepare offsets for all data in the oat file and calculate
1472  // the oat data size and code size. During this stage, we also set
1473  // oat code offsets in methods for use by the image writer.
1474  //
1475  // 2. We prepare offsets for the objects in the image and calculate
1476  // the image size.
1477  //
1478  // 3. We create the oat file. Originally this was just our own proprietary
1479  // file but now it is contained within an ELF dynamic object (aka an .so
1480  // file). Since we know the image size and oat data size and code size we
1481  // can prepare the ELF headers and we then know the ELF memory segment
1482  // layout and we can now resolve all references. The compiler provides
1483  // LinkerPatch information in each CompiledMethod and we resolve these,
1484  // using the layout information and image object locations provided by
1485  // image writer, as we're writing the method code.
1486  //
1487  // 4. We create the image file. It needs to know where the oat file
1488  // will be loaded after itself. Originally when oat file was simply
1489  // memory mapped so we could predict where its contents were based
1490  // on the file size. Now that it is an ELF file, we need to inspect
1491  // the ELF file to understand the in memory segment layout including
1492  // where the oat header is located within.
1493  // TODO: We could just remember this information from step 3.
1494  //
1495  // 5. We fixup the ELF program headers so that dlopen will try to
1496  // load the .so at the desired location at runtime by offsetting the
1497  // Elf32_Phdr.p_vaddr values by the desired base address.
1498  // TODO: Do this in step 3. We already know the layout there.
1499  //
1500  // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1501  // are done by the CreateImageFile() below.
1502
1503  // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1504  // ImageWriter, if necessary.
1505  // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1506  //       case (when the file will be explicitly erased).
1507  bool CreateOatFiles() {
1508    CHECK(key_value_store_.get() != nullptr);
1509
1510    TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1511
1512    std::vector<std::unique_ptr<OatWriter>> oat_writers;
1513    {
1514      TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1515      std::string image_file_location;
1516      uint32_t image_file_location_oat_checksum = 0;
1517      uintptr_t image_file_location_oat_data_begin = 0;
1518      int32_t image_patch_delta = 0;
1519
1520      if (app_image_ && image_base_ == 0) {
1521        std::vector<gc::space::ImageSpace*> image_spaces =
1522            Runtime::Current()->GetHeap()->GetBootImageSpaces();
1523        for (gc::space::ImageSpace* image_space : image_spaces) {
1524          // TODO: IS THIS IN ORDER? JUST TAKE THE LAST ONE?
1525          image_base_ = std::max(image_base_, RoundUp(
1526              reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1527              kPageSize));
1528        }
1529        VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1530      }
1531
1532      if (IsImage()) {
1533        PrepareImageWriter(image_base_);
1534      }
1535
1536      if (!IsBootImage()) {
1537        TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1538        std::vector<gc::space::ImageSpace*> image_spaces =
1539            Runtime::Current()->GetHeap()->GetBootImageSpaces();
1540        image_file_location_oat_checksum = image_spaces[0]->GetImageHeader().GetOatChecksum();
1541        image_file_location_oat_data_begin =
1542            reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1543        image_patch_delta = image_spaces[0]->GetImageHeader().GetPatchDelta();
1544        std::vector<std::string> image_filenames;
1545        for (const gc::space::ImageSpace* image_space : image_spaces) {
1546          image_filenames.push_back(image_space->GetImageFilename());
1547        }
1548        image_file_location = Join(image_filenames, ':');
1549      }
1550
1551      if (!image_file_location.empty()) {
1552        key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1553      }
1554
1555      for (size_t i = 0; i < oat_files_.size(); ++i) {
1556        std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1557        std::unique_ptr<OatWriter> oat_writer(new OatWriter(dex_files,
1558                                                            image_file_location_oat_checksum,
1559                                                            image_file_location_oat_data_begin,
1560                                                            image_patch_delta,
1561                                                            driver_.get(),
1562                                                            image_writer_.get(),
1563                                                            IsBootImage(),
1564                                                            timings_,
1565                                                            key_value_store_.get()));
1566        oat_writers.push_back(std::move(oat_writer));
1567      }
1568    }
1569
1570    if (IsImage()) {
1571      // The OatWriter constructor has already updated offsets in methods and we need to
1572      // prepare method offsets in the image address space for direct method patching.
1573      TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1574      if (!image_writer_->PrepareImageAddressSpace()) {
1575        LOG(ERROR) << "Failed to prepare image address space.";
1576        return false;
1577      }
1578    }
1579
1580    {
1581      TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1582      for (size_t i = 0; i < oat_files_.size(); ++i) {
1583        std::unique_ptr<File>& oat_file = oat_files_[i];
1584        std::unique_ptr<OatWriter>& oat_writer = oat_writers[i];
1585        std::unique_ptr<ElfWriter> elf_writer =
1586            CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get());
1587
1588        elf_writer->Start();
1589
1590        OutputStream* rodata = elf_writer->StartRoData();
1591        if (!oat_writer->WriteRodata(rodata)) {
1592          LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1593          return false;
1594        }
1595        elf_writer->EndRoData(rodata);
1596
1597        OutputStream* text = elf_writer->StartText();
1598        if (!oat_writer->WriteCode(text)) {
1599          LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1600          return false;
1601        }
1602        elf_writer->EndText(text);
1603
1604        elf_writer->SetBssSize(oat_writer->GetBssSize());
1605        elf_writer->WriteDynamicSection();
1606        elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1607        elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
1608
1609        if (!elf_writer->End()) {
1610          LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1611          return false;
1612        }
1613
1614        // Flush the oat file.
1615        if (oat_files_[i] != nullptr) {
1616          if (oat_files_[i]->Flush() != 0) {
1617            PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1618            oat_files_[i]->Erase();
1619            return false;
1620          }
1621        }
1622
1623        if (IsImage()) {
1624          // Update oat estimates.
1625          UpdateImageWriter(i);
1626        }
1627
1628        VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
1629      }
1630    }
1631
1632    return true;
1633  }
1634
1635  // If we are compiling an image, invoke the image creation routine. Else just skip.
1636  bool HandleImage() {
1637    if (IsImage()) {
1638      TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1639      if (!CreateImageFile()) {
1640        return false;
1641      }
1642      VLOG(compiler) << "Images written successfully";
1643    }
1644    return true;
1645  }
1646
1647  // Create a copy from stripped to unstripped.
1648  bool CopyStrippedToUnstripped() {
1649    for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1650      // If we don't want to strip in place, copy from stripped location to unstripped location.
1651      // We need to strip after image creation because FixupElf needs to use .strtab.
1652      if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1653        // If the oat file is still open, flush it.
1654        if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1655          if (!FlushCloseOatFile(i)) {
1656            return false;
1657          }
1658        }
1659
1660        TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1661        std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1662        std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1663        size_t buffer_size = 8192;
1664        std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1665        while (true) {
1666          int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1667          if (bytes_read <= 0) {
1668            break;
1669          }
1670          bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1671          CHECK(write_ok);
1672        }
1673        if (out->FlushCloseOrErase() != 0) {
1674          PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1675          return false;
1676        }
1677        VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1678      }
1679    }
1680    return true;
1681  }
1682
1683  bool FlushOatFiles() {
1684    TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1685    for (size_t i = 0; i < oat_files_.size(); ++i) {
1686      if (oat_files_[i].get() != nullptr) {
1687        if (oat_files_[i]->Flush() != 0) {
1688          PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1689          oat_files_[i]->Erase();
1690          return false;
1691        }
1692      }
1693    }
1694    return true;
1695  }
1696
1697  bool FlushCloseOatFile(size_t i) {
1698    if (oat_files_[i].get() != nullptr) {
1699      std::unique_ptr<File> tmp(oat_files_[i].release());
1700      if (tmp->FlushCloseOrErase() != 0) {
1701        PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
1702        return false;
1703      }
1704    }
1705    return true;
1706  }
1707
1708  bool FlushCloseOatFiles() {
1709    bool result = true;
1710    for (size_t i = 0; i < oat_files_.size(); ++i) {
1711      result &= FlushCloseOatFile(i);
1712    }
1713    return result;
1714  }
1715
1716  void DumpTiming() {
1717    if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1718      LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1719    }
1720    if (dump_passes_) {
1721      LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1722    }
1723  }
1724
1725  CompilerOptions* GetCompilerOptions() const {
1726    return compiler_options_.get();
1727  }
1728
1729  bool IsImage() const {
1730    return IsAppImage() || IsBootImage();
1731  }
1732
1733  bool IsAppImage() const {
1734    return app_image_;
1735  }
1736
1737  bool IsBootImage() const {
1738    return boot_image_;
1739  }
1740
1741  bool IsHost() const {
1742    return is_host_;
1743  }
1744
1745 private:
1746  template <typename T>
1747  static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1748    std::vector<T*> result;
1749    result.reserve(src.size());
1750    for (const std::unique_ptr<T>& t : src) {
1751      result.push_back(t.get());
1752    }
1753    return result;
1754  }
1755
1756  static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1757                             const std::vector<const char*>& dex_locations,
1758                             std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1759    DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
1760    size_t failure_count = 0;
1761    for (size_t i = 0; i < dex_filenames.size(); i++) {
1762      const char* dex_filename = dex_filenames[i];
1763      const char* dex_location = dex_locations[i];
1764      ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1765      std::string error_msg;
1766      if (!OS::FileExists(dex_filename)) {
1767        LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1768        continue;
1769      }
1770      if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
1771        LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1772        ++failure_count;
1773      }
1774      ATRACE_END();
1775    }
1776    return failure_count;
1777  }
1778
1779  // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1780  // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1781  // efficient, but under normal circumstances the list is neither large nor is this part too
1782  // sensitive.
1783  static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1784                               const std::string& location) {
1785    std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
1786    for (size_t i = 0; i < dex_files.size(); ++i) {
1787      if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1788          canonical_location) {
1789        return true;
1790      }
1791    }
1792    return false;
1793  }
1794
1795  // Appends to opened_dex_files any elements of class_path that dex_files
1796  // doesn't already contain. This will open those dex files as necessary.
1797  static void OpenClassPathFiles(const std::string& class_path,
1798                                 std::vector<const DexFile*> dex_files,
1799                                 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1800    DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1801    std::vector<std::string> parsed;
1802    Split(class_path, ':', &parsed);
1803    // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1804    ScopedObjectAccess soa(Thread::Current());
1805    for (size_t i = 0; i < parsed.size(); ++i) {
1806      if (DexFilesContains(dex_files, parsed[i])) {
1807        continue;
1808      }
1809      std::string error_msg;
1810      if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
1811        LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1812      }
1813    }
1814  }
1815
1816  bool PrepareImageClasses() {
1817    // If --image-classes was specified, calculate the full list of classes to include in the image.
1818    if (image_classes_filename_ != nullptr) {
1819      image_classes_ =
1820          ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1821      if (image_classes_ == nullptr) {
1822        return false;
1823      }
1824    } else if (IsBootImage()) {
1825      image_classes_.reset(new std::unordered_set<std::string>);
1826    }
1827    return true;
1828  }
1829
1830  bool PrepareCompiledClasses() {
1831    // If --compiled-classes was specified, calculate the full list of classes to compile in the
1832    // image.
1833    if (compiled_classes_filename_ != nullptr) {
1834      compiled_classes_ =
1835          ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1836      if (compiled_classes_ == nullptr) {
1837        return false;
1838      }
1839    } else {
1840      compiled_classes_.reset(nullptr);  // By default compile everything.
1841    }
1842    return true;
1843  }
1844
1845  static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1846                                                                      const char* classes_filename,
1847                                                                      const char* tag) {
1848    std::unique_ptr<std::unordered_set<std::string>> classes;
1849    std::string error_msg;
1850    if (zip_filename != nullptr) {
1851      classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1852    } else {
1853      classes.reset(ReadImageClassesFromFile(classes_filename));
1854    }
1855    if (classes == nullptr) {
1856      LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1857                 << classes_filename << "': " << error_msg;
1858    }
1859    return classes;
1860  }
1861
1862  bool PrepareCompiledMethods() {
1863    // If --compiled-methods was specified, read the methods to compile from the given file(s).
1864    if (compiled_methods_filename_ != nullptr) {
1865      std::string error_msg;
1866      if (compiled_methods_zip_filename_ != nullptr) {
1867        compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1868                                                          compiled_methods_filename_,
1869                                                          nullptr,            // No post-processing.
1870                                                          &error_msg));
1871      } else {
1872        compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1873                                                           nullptr));         // No post-processing.
1874      }
1875      if (compiled_methods_.get() == nullptr) {
1876        LOG(ERROR) << "Failed to create list of compiled methods from '"
1877            << compiled_methods_filename_ << "': " << error_msg;
1878        return false;
1879      }
1880    } else {
1881      compiled_methods_.reset(nullptr);  // By default compile everything.
1882    }
1883    return true;
1884  }
1885
1886  void SaveDexInput() {
1887    for (size_t i = 0; i < dex_files_.size(); ++i) {
1888      const DexFile* dex_file = dex_files_[i];
1889      std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1890                                             getpid(), i));
1891      std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1892      if (tmp_file.get() == nullptr) {
1893        PLOG(ERROR) << "Failed to open file " << tmp_file_name
1894            << ". Try: adb shell chmod 777 /data/local/tmp";
1895        continue;
1896      }
1897      // This is just dumping files for debugging. Ignore errors, and leave remnants.
1898      UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1899      UNUSED(tmp_file->Flush());
1900      UNUSED(tmp_file->Close());
1901      LOG(INFO) << "Wrote input to " << tmp_file_name;
1902    }
1903  }
1904
1905  bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
1906    RuntimeOptions raw_options;
1907    if (boot_image_filename_.empty()) {
1908      std::string boot_class_path = "-Xbootclasspath:";
1909      boot_class_path += Join(dex_filenames_, ':');
1910      raw_options.push_back(std::make_pair(boot_class_path, nullptr));
1911      std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1912      boot_class_path_locations += Join(dex_locations_, ':');
1913      raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
1914    } else {
1915      std::string boot_image_option = "-Ximage:";
1916      boot_image_option += boot_image_filename_;
1917      raw_options.push_back(std::make_pair(boot_image_option, nullptr));
1918    }
1919    for (size_t i = 0; i < runtime_args_.size(); i++) {
1920      raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
1921    }
1922
1923    raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1924    raw_options.push_back(
1925        std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1926
1927    // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1928    // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1929    // have been stripped in preopting, anyways).
1930    if (!IsBootImage()) {
1931      raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1932    }
1933    // Disable libsigchain. We don't don't need it during compilation and it prevents us
1934    // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1935    raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
1936
1937    if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
1938      LOG(ERROR) << "Failed to parse runtime options";
1939      return false;
1940    }
1941    return true;
1942  }
1943
1944  // Create a runtime necessary for compilation.
1945  bool CreateRuntime(RuntimeArgumentMap&& runtime_options)
1946      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1947    if (!Runtime::Create(std::move(runtime_options))) {
1948      LOG(ERROR) << "Failed to create runtime";
1949      return false;
1950    }
1951    runtime_.reset(Runtime::Current());
1952    runtime_->SetInstructionSet(instruction_set_);
1953    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1954      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1955      if (!runtime_->HasCalleeSaveMethod(type)) {
1956        runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
1957      }
1958    }
1959    runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
1960
1961    // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1962    // set up.
1963    interpreter::UnstartedRuntime::Initialize();
1964
1965    runtime_->GetClassLinker()->RunRootClinits();
1966
1967    return true;
1968  }
1969
1970  void PrepareImageWriter(uintptr_t image_base) {
1971    DCHECK(IsImage());
1972    image_writer_.reset(new ImageWriter(*driver_,
1973                                        image_base,
1974                                        compiler_options_->GetCompilePic(),
1975                                        IsAppImage(),
1976                                        image_storage_mode_,
1977                                        oat_filenames_,
1978                                        dex_file_oat_filename_map_));
1979  }
1980
1981  // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files.
1982  bool CreateImageFile()
1983      REQUIRES(!Locks::mutator_lock_) {
1984    CHECK(image_writer_ != nullptr);
1985    if (!IsBootImage()) {
1986      image_filenames_.push_back(app_image_file_name_.c_str());
1987    }
1988    if (!image_writer_->Write(app_image_fd_, image_filenames_, oat_filenames_)) {
1989      LOG(ERROR) << "Failure during image file creation";
1990      return false;
1991    }
1992
1993    // We need the OatDataBegin entries.
1994    std::map<const char*, uintptr_t> oat_data_begins;
1995    for (const char* oat_filename : oat_filenames_) {
1996      oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
1997    }
1998    // Destroy ImageWriter before doing FixupElf.
1999    image_writer_.reset();
2000
2001    for (const char* oat_filename : oat_filenames_) {
2002      // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2003      if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2004        std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2005        if (oat_file.get() == nullptr) {
2006          PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2007          return false;
2008        }
2009
2010        uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
2011
2012        if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2013          oat_file->Erase();
2014          LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2015          return false;
2016        }
2017
2018        if (oat_file->FlushCloseOrErase()) {
2019          PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2020          return false;
2021        }
2022      }
2023    }
2024
2025    return true;
2026  }
2027
2028  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
2029  static std::unordered_set<std::string>* ReadImageClassesFromFile(
2030      const char* image_classes_filename) {
2031    std::function<std::string(const char*)> process = DotToDescriptor;
2032    return ReadCommentedInputFromFile(image_classes_filename, &process);
2033  }
2034
2035  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
2036  static std::unordered_set<std::string>* ReadImageClassesFromZip(
2037        const char* zip_filename,
2038        const char* image_classes_filename,
2039        std::string* error_msg) {
2040    std::function<std::string(const char*)> process = DotToDescriptor;
2041    return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2042  }
2043
2044  // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2045  // the given function.
2046  static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2047      const char* input_filename, std::function<std::string(const char*)>* process) {
2048    std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2049    if (input_file.get() == nullptr) {
2050      LOG(ERROR) << "Failed to open input file " << input_filename;
2051      return nullptr;
2052    }
2053    std::unique_ptr<std::unordered_set<std::string>> result(
2054        ReadCommentedInputStream(*input_file, process));
2055    input_file->close();
2056    return result.release();
2057  }
2058
2059  // Read lines from the given file from the given zip file, dropping comments and empty lines.
2060  // Post-process each line with the given function.
2061  static std::unordered_set<std::string>* ReadCommentedInputFromZip(
2062      const char* zip_filename,
2063      const char* input_filename,
2064      std::function<std::string(const char*)>* process,
2065      std::string* error_msg) {
2066    std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2067    if (zip_archive.get() == nullptr) {
2068      return nullptr;
2069    }
2070    std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
2071    if (zip_entry.get() == nullptr) {
2072      *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
2073                                zip_filename, error_msg->c_str());
2074      return nullptr;
2075    }
2076    std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2077                                                                  input_filename,
2078                                                                  error_msg));
2079    if (input_file.get() == nullptr) {
2080      *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
2081                                zip_filename, error_msg->c_str());
2082      return nullptr;
2083    }
2084    const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2085                                   input_file->Size());
2086    std::istringstream input_stream(input_string);
2087    return ReadCommentedInputStream(input_stream, process);
2088  }
2089
2090  // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2091  // with the given function.
2092  static std::unordered_set<std::string>* ReadCommentedInputStream(
2093      std::istream& in_stream,
2094      std::function<std::string(const char*)>* process) {
2095    std::unique_ptr<std::unordered_set<std::string>> image_classes(
2096        new std::unordered_set<std::string>);
2097    while (in_stream.good()) {
2098      std::string dot;
2099      std::getline(in_stream, dot);
2100      if (StartsWith(dot, "#") || dot.empty()) {
2101        continue;
2102      }
2103      if (process != nullptr) {
2104        std::string descriptor((*process)(dot.c_str()));
2105        image_classes->insert(descriptor);
2106      } else {
2107        image_classes->insert(dot);
2108      }
2109    }
2110    return image_classes.release();
2111  }
2112
2113  void LogCompletionTime() {
2114    // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2115    //       is no image, there won't be a Runtime::Current().
2116    // Note: driver creation can fail when loading an invalid dex file.
2117    LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
2118              << " (threads: " << thread_count_ << ") "
2119              << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
2120                  driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2121                  "");
2122  }
2123
2124  std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2125    std::string res(image_filename);
2126    size_t last_slash = res.rfind('/');
2127    if (last_slash == std::string::npos || last_slash == 0) {
2128      return res;
2129    }
2130    size_t penultimate_slash = res.rfind('/', last_slash - 1);
2131    if (penultimate_slash == std::string::npos) {
2132      return res;
2133    }
2134    // Check that the string in-between is the expected one.
2135    if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2136            GetInstructionSetString(isa)) {
2137      LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2138      return res;
2139    }
2140    return res.substr(0, penultimate_slash) + res.substr(last_slash);
2141  }
2142
2143  // Update the estimate for the oat file with the given index.
2144  void UpdateImageWriter(size_t index) {
2145    DCHECK(image_writer_ != nullptr);
2146    DCHECK_LT(index, oat_filenames_.size());
2147
2148    image_writer_->UpdateOatFile(oat_filenames_[index]);
2149  }
2150
2151  std::unique_ptr<CompilerOptions> compiler_options_;
2152  Compiler::Kind compiler_kind_;
2153
2154  InstructionSet instruction_set_;
2155  std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2156
2157  std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2158
2159  std::unique_ptr<VerificationResults> verification_results_;
2160
2161  DexFileToMethodInlinerMap method_inliner_map_;
2162  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2163
2164  // Ownership for the class path files.
2165  std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2166
2167  std::unique_ptr<Runtime> runtime_;
2168
2169  size_t thread_count_;
2170  uint64_t start_ns_;
2171  std::unique_ptr<WatchDog> watchdog_;
2172  std::vector<std::unique_ptr<File>> oat_files_;
2173  std::string oat_location_;
2174  std::vector<const char*> oat_filenames_;
2175  std::vector<const char*> oat_unstripped_;
2176  int oat_fd_;
2177  std::vector<const char*> dex_filenames_;
2178  std::vector<const char*> dex_locations_;
2179  int zip_fd_;
2180  std::string zip_location_;
2181  std::string boot_image_filename_;
2182  std::vector<const char*> runtime_args_;
2183  std::vector<const char*> image_filenames_;
2184  uintptr_t image_base_;
2185  const char* image_classes_zip_filename_;
2186  const char* image_classes_filename_;
2187  ImageHeader::StorageMode image_storage_mode_;
2188  const char* compiled_classes_zip_filename_;
2189  const char* compiled_classes_filename_;
2190  const char* compiled_methods_zip_filename_;
2191  const char* compiled_methods_filename_;
2192  std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2193  std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
2194  std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
2195  bool app_image_;
2196  bool boot_image_;
2197  bool is_host_;
2198  std::string android_root_;
2199  std::vector<const DexFile*> dex_files_;
2200  std::string no_inline_from_string_;
2201  std::vector<jobject> dex_caches_;
2202  std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2203
2204  std::unique_ptr<ImageWriter> image_writer_;
2205  std::unique_ptr<CompilerDriver> driver_;
2206
2207  std::vector<std::string> verbose_methods_;
2208  bool dump_stats_;
2209  bool dump_passes_;
2210  bool dump_timing_;
2211  bool dump_slow_timing_;
2212  std::string dump_cfg_file_name_;
2213  bool dump_cfg_append_;
2214  std::string swap_file_name_;
2215  int swap_fd_;
2216  std::string app_image_file_name_;
2217  int app_image_fd_;
2218  std::string profile_file_;  // Profile file to use
2219  TimingLogger* timings_;
2220  std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
2221  std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2222  std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2223
2224  // Backing storage.
2225  std::vector<std::string> char_backing_storage_;
2226
2227  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2228};
2229
2230static void b13564922() {
2231#if defined(__linux__) && defined(__arm__)
2232  int major, minor;
2233  struct utsname uts;
2234  if (uname(&uts) != -1 &&
2235      sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2236      ((major < 3) || ((major == 3) && (minor < 4)))) {
2237    // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2238    // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2239    int old_personality = personality(0xffffffff);
2240    if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2241      int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2242      if (new_personality == -1) {
2243        LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2244      }
2245    }
2246  }
2247#endif
2248}
2249
2250static int CompileImage(Dex2Oat& dex2oat) {
2251  dex2oat.Compile();
2252
2253  if (!dex2oat.CreateOatFiles()) {
2254    dex2oat.EraseOatFiles();
2255    return EXIT_FAILURE;
2256  }
2257
2258  // Close the image oat files. We always expect the output file by name, and it will be
2259  // re-opened from the unstripped name. Note: it's easier to *flush* and close...
2260  if (!dex2oat.FlushCloseOatFiles()) {
2261    return EXIT_FAILURE;
2262  }
2263
2264  // Creates the boot.art and patches the oat files.
2265  if (!dex2oat.HandleImage()) {
2266    return EXIT_FAILURE;
2267  }
2268
2269  // When given --host, finish early without stripping.
2270  if (dex2oat.IsHost()) {
2271    dex2oat.DumpTiming();
2272    return EXIT_SUCCESS;
2273  }
2274
2275  // Copy stripped to unstripped location, if necessary.
2276  if (!dex2oat.CopyStrippedToUnstripped()) {
2277    return EXIT_FAILURE;
2278  }
2279
2280  // FlushClose again, as stripping might have re-opened the oat files.
2281  if (!dex2oat.FlushCloseOatFiles()) {
2282    return EXIT_FAILURE;
2283  }
2284
2285  dex2oat.DumpTiming();
2286  return EXIT_SUCCESS;
2287}
2288
2289static int CompileApp(Dex2Oat& dex2oat) {
2290  dex2oat.Compile();
2291
2292  if (!dex2oat.CreateOatFiles()) {
2293    dex2oat.EraseOatFiles();
2294    return EXIT_FAILURE;
2295  }
2296
2297  // Do not close the oat files here. We might have gotten the output file by file descriptor,
2298  // which we would lose.
2299
2300  // When given --host, finish early without stripping.
2301  if (dex2oat.IsHost()) {
2302    if (!dex2oat.FlushCloseOatFiles()) {
2303      return EXIT_FAILURE;
2304    }
2305
2306    dex2oat.DumpTiming();
2307    return EXIT_SUCCESS;
2308  }
2309
2310  // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2311  // stripped versions. If this is given, we expect to be able to open writable files by name.
2312  if (!dex2oat.CopyStrippedToUnstripped()) {
2313    return EXIT_FAILURE;
2314  }
2315
2316  // Flush and close the files.
2317  if (!dex2oat.FlushCloseOatFiles()) {
2318    return EXIT_FAILURE;
2319  }
2320
2321  dex2oat.DumpTiming();
2322  return EXIT_SUCCESS;
2323}
2324
2325static int dex2oat(int argc, char** argv) {
2326  b13564922();
2327
2328  TimingLogger timings("compiler", false, false);
2329
2330  Dex2Oat dex2oat(&timings);
2331
2332  // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2333  dex2oat.ParseArgs(argc, argv);
2334
2335  // Check early that the result of compilation can be written
2336  if (!dex2oat.OpenFile()) {
2337    return EXIT_FAILURE;
2338  }
2339
2340  // Print the complete line when any of the following is true:
2341  //   1) Debug build
2342  //   2) Compiling an image
2343  //   3) Compiling with --host
2344  //   4) Compiling on the host (not a target build)
2345  // Otherwise, print a stripped command line.
2346  if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
2347    LOG(INFO) << CommandLine();
2348  } else {
2349    LOG(INFO) << StrippedCommandLine();
2350  }
2351
2352  if (!dex2oat.Setup()) {
2353    dex2oat.EraseOatFiles();
2354    return EXIT_FAILURE;
2355  }
2356
2357  bool result;
2358  if (dex2oat.IsImage()) {
2359    result = CompileImage(dex2oat);
2360  } else {
2361    result = CompileApp(dex2oat);
2362  }
2363
2364  dex2oat.Shutdown();
2365  return result;
2366}
2367}  // namespace art
2368
2369int main(int argc, char** argv) {
2370  int result = art::dex2oat(argc, argv);
2371  // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2372  // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2373  // should not destruct the runtime in this case.
2374  if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
2375    exit(result);
2376  }
2377  return result;
2378}
2379