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