dex2oat.cc revision dbfe254f5ca96f6c5b2284478597d6140c01a394
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 <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
20#include <valgrind.h>
21
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
28#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
33#define ATRACE_TAG ATRACE_TAG_DALVIK
34#include <cutils/trace.h>
35
36#include "arch/instruction_set_features.h"
37#include "base/dumpable.h"
38#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
43#include "compiler.h"
44#include "compiler_callbacks.h"
45#include "dex_file-inl.h"
46#include "dex/pass_driver_me_opts.h"
47#include "dex/verification_results.h"
48#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
50#include "driver/compiler_driver.h"
51#include "driver/compiler_options.h"
52#include "elf_file.h"
53#include "elf_writer.h"
54#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
58#include "mirror/art_method-inl.h"
59#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
64#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
68#include "utils.h"
69#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
75static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79  std::vector<std::string> command;
80  for (int i = 0; i < original_argc; ++i) {
81    command.push_back(original_argv[i]);
82  }
83  return Join(command, ' ');
84}
85
86static void UsageErrorV(const char* fmt, va_list ap) {
87  std::string error;
88  StringAppendV(&error, fmt, ap);
89  LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93  va_list ap;
94  va_start(ap, fmt);
95  UsageErrorV(fmt, ap);
96  va_end(ap);
97}
98
99[[noreturn]] static void Usage(const char* fmt, ...) {
100  va_list ap;
101  va_start(ap, fmt);
102  UsageErrorV(fmt, ap);
103  va_end(ap);
104
105  UsageError("Command: %s", CommandLine().c_str());
106
107  UsageError("Usage: dex2oat [options]...");
108  UsageError("");
109  UsageError("  --dex-file=<dex-file>: specifies a .dex file to compile.");
110  UsageError("      Example: --dex-file=/system/framework/core.jar");
111  UsageError("");
112  UsageError("  --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113  UsageError("      containing a classes.dex file to compile.");
114  UsageError("      Example: --zip-fd=5");
115  UsageError("");
116  UsageError("  --zip-location=<zip-location>: specifies a symbolic name for the file");
117  UsageError("      corresponding to the file descriptor specified by --zip-fd.");
118  UsageError("      Example: --zip-location=/system/app/Calculator.apk");
119  UsageError("");
120  UsageError("  --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121  UsageError("      Example: --oat-file=/system/framework/boot.oat");
122  UsageError("");
123  UsageError("  --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
124  UsageError("      Example: --oat-fd=6");
125  UsageError("");
126  UsageError("  --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127  UsageError("      to the file descriptor specified by --oat-fd.");
128  UsageError("      Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129  UsageError("");
130  UsageError("  --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131  UsageError("      Example: --oat-symbols=/symbols/system/framework/boot.oat");
132  UsageError("");
133  UsageError("  --bitcode=<file.bc>: specifies the optional bitcode filename.");
134  UsageError("      Example: --bitcode=/system/framework/boot.bc");
135  UsageError("");
136  UsageError("  --image=<file.art>: specifies the output image filename.");
137  UsageError("      Example: --image=/system/framework/boot.art");
138  UsageError("");
139  UsageError("  --image-classes=<classname-file>: specifies classes to include in an image.");
140  UsageError("      Example: --image=frameworks/base/preloaded-classes");
141  UsageError("");
142  UsageError("  --base=<hex-address>: specifies the base address when creating a boot image.");
143  UsageError("      Example: --base=0x50000000");
144  UsageError("");
145  UsageError("  --boot-image=<file.art>: provide the image file for the boot class path.");
146  UsageError("      Example: --boot-image=/system/framework/boot.art");
147  UsageError("      Default: $ANDROID_ROOT/system/framework/boot.art");
148  UsageError("");
149  UsageError("  --android-root=<path>: used to locate libraries for portable linking.");
150  UsageError("      Example: --android-root=out/host/linux-x86");
151  UsageError("      Default: $ANDROID_ROOT");
152  UsageError("");
153  UsageError("  --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
154  UsageError("      instruction set.");
155  UsageError("      Example: --instruction-set=x86");
156  UsageError("      Default: arm");
157  UsageError("");
158  UsageError("  --instruction-set-features=...,: Specify instruction set features");
159  UsageError("      Example: --instruction-set-features=div");
160  UsageError("      Default: default");
161  UsageError("");
162  UsageError("  --compile-pic: Force indirect use of code, methods, and classes");
163  UsageError("      Default: disabled");
164  UsageError("");
165  UsageError("  --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
166  UsageError("      set.");
167  UsageError("      Example: --compiler-backend=Portable");
168  UsageError("      Default: Quick");
169  UsageError("");
170  UsageError("  --compiler-filter="
171                "(verify-none"
172                "|interpret-only"
173                "|space"
174                "|balanced"
175                "|speed"
176                "|everything"
177                "|time):");
178  UsageError("      select compiler filter.");
179  UsageError("      Example: --compiler-filter=everything");
180#if ART_SMALL_MODE
181  UsageError("      Default: interpret-only");
182#else
183  UsageError("      Default: speed");
184#endif
185  UsageError("");
186  UsageError("  --huge-method-max=<method-instruction-count>: the threshold size for a huge");
187  UsageError("      method for compiler filter tuning.");
188  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
189  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
190  UsageError("");
191  UsageError("  --huge-method-max=<method-instruction-count>: threshold size for a huge");
192  UsageError("      method for compiler filter tuning.");
193  UsageError("      Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
194  UsageError("      Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
195  UsageError("");
196  UsageError("  --large-method-max=<method-instruction-count>: threshold size for a large");
197  UsageError("      method for compiler filter tuning.");
198  UsageError("      Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
199  UsageError("      Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
200  UsageError("");
201  UsageError("  --small-method-max=<method-instruction-count>: threshold size for a small");
202  UsageError("      method for compiler filter tuning.");
203  UsageError("      Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
204  UsageError("      Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
205  UsageError("");
206  UsageError("  --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
207  UsageError("      method for compiler filter tuning.");
208  UsageError("      Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
209  UsageError("      Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
210  UsageError("");
211  UsageError("  --num-dex-methods=<method-count>: threshold size for a small dex file for");
212  UsageError("      compiler filter tuning. If the input has fewer than this many methods");
213  UsageError("      and the filter is not interpret-only or verify-none, overrides the");
214  UsageError("      filter to use speed");
215  UsageError("      Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216  UsageError("      Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217  UsageError("");
218  UsageError("  --host: used with Portable backend to link against host runtime libraries");
219  UsageError("");
220  UsageError("  --dump-timing: display a breakdown of where time was spent");
221  UsageError("");
222  UsageError("  --include-patch-information: Include patching information so the generated code");
223  UsageError("      can have its base address moved without full recompilation.");
224  UsageError("");
225  UsageError("  --no-include-patch-information: Do not include patching information.");
226  UsageError("");
227  UsageError("  --include-debug-symbols: Include ELF symbols in this oat file");
228  UsageError("");
229  UsageError("  --no-include-debug-symbols: Do not include ELF symbols in this oat file");
230  UsageError("");
231  UsageError("  --runtime-arg <argument>: used to specify various arguments for the runtime,");
232  UsageError("      such as initial heap size, maximum heap size, and verbose output.");
233  UsageError("      Use a separate --runtime-arg switch for each argument.");
234  UsageError("      Example: --runtime-arg -Xms256m");
235  UsageError("");
236  UsageError("  --profile-file=<filename>: specify profiler output file to use for compilation.");
237  UsageError("");
238  UsageError("  --print-pass-names: print a list of pass names");
239  UsageError("");
240  UsageError("  --disable-passes=<pass-names>:  disable one or more passes separated by comma.");
241  UsageError("      Example: --disable-passes=UseCount,BBOptimizations");
242  UsageError("");
243  UsageError("  --print-pass-options: print a list of passes that have configurable options along "
244             "with the setting.");
245  UsageError("      Will print default if no overridden setting exists.");
246  UsageError("");
247  UsageError("  --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
248             "Pass2Name:Pass2OptionName:Pass2Option#");
249  UsageError("      Used to specify a pass specific option. The setting itself must be integer.");
250  UsageError("      Separator used between options is a comma.");
251  UsageError("");
252  std::cerr << "See log for usage error information\n";
253  exit(EXIT_FAILURE);
254}
255
256// The primary goal of the watchdog is to prevent stuck build servers
257// during development when fatal aborts lead to a cascade of failures
258// that result in a deadlock.
259class WatchDog {
260// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
261#undef CHECK_PTHREAD_CALL
262#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
263  do { \
264    int rc = call args; \
265    if (rc != 0) { \
266      errno = rc; \
267      std::string message(# call); \
268      message += " failed for "; \
269      message += reason; \
270      Fatal(message); \
271    } \
272  } while (false)
273
274 public:
275  explicit WatchDog(bool is_watch_dog_enabled) {
276    is_watch_dog_enabled_ = is_watch_dog_enabled;
277    if (!is_watch_dog_enabled_) {
278      return;
279    }
280    shutting_down_ = false;
281    const char* reason = "dex2oat watch dog thread startup";
282    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
283    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
284    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
285    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
286    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
287  }
288  ~WatchDog() {
289    if (!is_watch_dog_enabled_) {
290      return;
291    }
292    const char* reason = "dex2oat watch dog thread shutdown";
293    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
294    shutting_down_ = true;
295    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
296    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
297
298    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
299
300    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
301    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
302  }
303
304 private:
305  static void* CallBack(void* arg) {
306    WatchDog* self = reinterpret_cast<WatchDog*>(arg);
307    ::art::SetThreadName("dex2oat watch dog");
308    self->Wait();
309    return nullptr;
310  }
311
312  static void Message(char severity, const std::string& message) {
313    // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
314    //       cases.
315    fprintf(stderr, "dex2oat%s %c %d %d %s\n",
316            kIsDebugBuild ? "d" : "",
317            severity,
318            getpid(),
319            GetTid(),
320            message.c_str());
321  }
322
323  static void Warn(const std::string& message) {
324    Message('W', message);
325  }
326
327  [[noreturn]] static void Fatal(const std::string& message) {
328    Message('F', message);
329    exit(1);
330  }
331
332  void Wait() {
333    bool warning = true;
334    CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
335    // TODO: tune the multiplier for GC verification, the following is just to make the timeout
336    //       large.
337    int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
338    timespec warning_ts;
339    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
340    timespec timeout_ts;
341    InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
342    const char* reason = "dex2oat watch dog thread waiting";
343    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
344    while (!shutting_down_) {
345      int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
346                                                         warning ? &warning_ts
347                                                                 : &timeout_ts));
348      if (rc == ETIMEDOUT) {
349        std::string message(StringPrintf("dex2oat did not finish after %d seconds",
350                                         warning ? kWatchDogWarningSeconds
351                                                 : kWatchDogTimeoutSeconds));
352        if (warning) {
353          Warn(message.c_str());
354          warning = false;
355        } else {
356          Fatal(message.c_str());
357        }
358      } else if (rc != 0) {
359        std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
360                                         strerror(errno)));
361        Fatal(message.c_str());
362      }
363    }
364    CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
365  }
366
367  // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
368  // Debug builds are slower so they have larger timeouts.
369  static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
370
371  static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
372      kSlowdownFactor * 2 * 60 :   // 2 minutes scaled by kSlowdownFactor (portable).
373      kSlowdownFactor * 1 * 60;    // 1 minute scaled by kSlowdownFactor  (not-portable).
374  static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
375      kSlowdownFactor * 30 * 60 :  // 30 minutes scaled by kSlowdownFactor (portable).
376      kSlowdownFactor * 6 * 60;    // 6 minutes scaled by kSlowdownFactor  (not-portable).
377
378  bool is_watch_dog_enabled_;
379  bool shutting_down_;
380  // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
381  pthread_mutex_t mutex_;
382  pthread_cond_t cond_;
383  pthread_attr_t attr_;
384  pthread_t pthread_;
385};
386
387static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
388  std::string::size_type colon = s.find(c);
389  if (colon == std::string::npos) {
390    Usage("Missing char %c in option %s\n", c, s.c_str());
391  }
392  // Add one to remove the char we were trimming until.
393  *parsed_value = s.substr(colon + 1);
394}
395
396static void ParseDouble(const std::string& option, char after_char, double min, double max,
397                        double* parsed_value) {
398  std::string substring;
399  ParseStringAfterChar(option, after_char, &substring);
400  bool sane_val = true;
401  double value;
402  if (false) {
403    // TODO: this doesn't seem to work on the emulator.  b/15114595
404    std::stringstream iss(substring);
405    iss >> value;
406    // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
407    sane_val = iss.eof() && (value >= min) && (value <= max);
408  } else {
409    char* end = nullptr;
410    value = strtod(substring.c_str(), &end);
411    sane_val = *end == '\0' && value >= min && value <= max;
412  }
413  if (!sane_val) {
414    Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
415  }
416  *parsed_value = value;
417}
418
419class Dex2Oat FINAL {
420 public:
421  explicit Dex2Oat(TimingLogger* timings) :
422      compiler_kind_(kUsePortableCompiler ? Compiler::kPortable : Compiler::kQuick),
423      instruction_set_(kRuntimeISA),
424      // Take the default set of instruction features from the build.
425      method_inliner_map_(),
426      runtime_(nullptr),
427      thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
428      start_ns_(NanoTime()),
429      oat_fd_(-1),
430      zip_fd_(-1),
431      image_base_(0U),
432      image_classes_zip_filename_(nullptr),
433      image_classes_filename_(nullptr),
434      compiled_classes_zip_filename_(nullptr),
435      compiled_classes_filename_(nullptr),
436      image_(false),
437      is_host_(false),
438      dump_stats_(false),
439      dump_passes_(false),
440      dump_timing_(false),
441      dump_slow_timing_(kIsDebugBuild),
442      timings_(timings) {}
443
444  ~Dex2Oat() {
445    if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
446      delete runtime_;  // See field declaration for why this is manual.
447    }
448    LogCompletionTime();
449  }
450
451  // Parse the arguments from the command line. In case of an unrecognized option or impossible
452  // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
453  // returns, arguments have been successfully parsed.
454  void ParseArgs(int argc, char** argv) {
455    original_argc = argc;
456    original_argv = argv;
457
458    InitLogging(argv);
459
460    // Skip over argv[0].
461    argv++;
462    argc--;
463
464    if (argc == 0) {
465      Usage("No arguments specified");
466    }
467
468    std::string oat_symbols;
469    std::string boot_image_filename;
470    const char* compiler_filter_string = nullptr;
471    bool compile_pic = false;
472    int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
473    int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
474    int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
475    int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
476    int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
477
478    // Profile file to use
479    double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
480
481    bool print_pass_options = false;
482    bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
483    bool include_debug_symbols = kIsDebugBuild;
484    bool watch_dog_enabled = true;
485    bool generate_gdb_information = kIsDebugBuild;
486
487    std::string error_msg;
488
489    for (int i = 0; i < argc; i++) {
490      const StringPiece option(argv[i]);
491      const bool log_options = false;
492      if (log_options) {
493        LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
494      }
495      if (option.starts_with("--dex-file=")) {
496        dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
497      } else if (option.starts_with("--dex-location=")) {
498        dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
499      } else if (option.starts_with("--zip-fd=")) {
500        const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
501        if (!ParseInt(zip_fd_str, &zip_fd_)) {
502          Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
503        }
504        if (zip_fd_ < 0) {
505          Usage("--zip-fd passed a negative value %d", zip_fd_);
506        }
507      } else if (option.starts_with("--zip-location=")) {
508        zip_location_ = option.substr(strlen("--zip-location=")).data();
509      } else if (option.starts_with("--oat-file=")) {
510        oat_filename_ = option.substr(strlen("--oat-file=")).data();
511      } else if (option.starts_with("--oat-symbols=")) {
512        oat_symbols = option.substr(strlen("--oat-symbols=")).data();
513      } else if (option.starts_with("--oat-fd=")) {
514        const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
515        if (!ParseInt(oat_fd_str, &oat_fd_)) {
516          Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
517        }
518        if (oat_fd_ < 0) {
519          Usage("--oat-fd passed a negative value %d", oat_fd_);
520        }
521      } else if (option == "--watch-dog") {
522        watch_dog_enabled = true;
523      } else if (option == "--no-watch-dog") {
524        watch_dog_enabled = false;
525      } else if (option == "--gen-gdb-info") {
526        generate_gdb_information = true;
527        // Debug symbols are needed for gdb information.
528        include_debug_symbols = true;
529      } else if (option == "--no-gen-gdb-info") {
530        generate_gdb_information = false;
531      } else if (option.starts_with("-j")) {
532        const char* thread_count_str = option.substr(strlen("-j")).data();
533        if (!ParseUint(thread_count_str, &thread_count_)) {
534          Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
535        }
536      } else if (option.starts_with("--oat-location=")) {
537        oat_location_ = option.substr(strlen("--oat-location=")).data();
538      } else if (option.starts_with("--bitcode=")) {
539        bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
540      } else if (option.starts_with("--image=")) {
541        image_filename_ = option.substr(strlen("--image=")).data();
542      } else if (option.starts_with("--image-classes=")) {
543        image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
544      } else if (option.starts_with("--image-classes-zip=")) {
545        image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
546      } else if (option.starts_with("--compiled-classes=")) {
547        compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
548      } else if (option.starts_with("--compiled-classes-zip=")) {
549        compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
550      } else if (option.starts_with("--base=")) {
551        const char* image_base_str = option.substr(strlen("--base=")).data();
552        char* end;
553        image_base_ = strtoul(image_base_str, &end, 16);
554        if (end == image_base_str || *end != '\0') {
555          Usage("Failed to parse hexadecimal value for option %s", option.data());
556        }
557      } else if (option.starts_with("--boot-image=")) {
558        boot_image_filename = option.substr(strlen("--boot-image=")).data();
559      } else if (option.starts_with("--android-root=")) {
560        android_root_ = option.substr(strlen("--android-root=")).data();
561      } else if (option.starts_with("--instruction-set=")) {
562        StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
563        // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
564        std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
565        strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
566        buf.get()[instruction_set_str.length()] = 0;
567        instruction_set_ = GetInstructionSetFromString(buf.get());
568        // arm actually means thumb2.
569        if (instruction_set_ == InstructionSet::kArm) {
570          instruction_set_ = InstructionSet::kThumb2;
571        }
572      } else if (option.starts_with("--instruction-set-variant=")) {
573        StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
574        instruction_set_features_.reset(
575            InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
576        if (instruction_set_features_.get() == nullptr) {
577          Usage("%s", error_msg.c_str());
578        }
579      } else if (option.starts_with("--instruction-set-features=")) {
580        StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
581        if (instruction_set_features_.get() == nullptr) {
582          instruction_set_features_.reset(
583              InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
584          if (instruction_set_features_.get() == nullptr) {
585            Usage("Problem initializing default instruction set features variant: %s",
586                  error_msg.c_str());
587          }
588        }
589        instruction_set_features_.reset(
590            instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
591        if (instruction_set_features_.get() == nullptr) {
592          Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
593        }
594      } else if (option.starts_with("--compiler-backend=")) {
595        StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
596        if (backend_str == "Quick") {
597          compiler_kind_ = Compiler::kQuick;
598        } else if (backend_str == "Optimizing") {
599          compiler_kind_ = Compiler::kOptimizing;
600          compile_pic = true;
601        } else if (backend_str == "Portable") {
602          compiler_kind_ = Compiler::kPortable;
603        } else {
604          Usage("Unknown compiler backend: %s", backend_str.data());
605        }
606      } else if (option.starts_with("--compiler-filter=")) {
607        compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
608      } else if (option == "--compile-pic") {
609        compile_pic = true;
610      } else if (option.starts_with("--huge-method-max=")) {
611        const char* threshold = option.substr(strlen("--huge-method-max=")).data();
612        if (!ParseInt(threshold, &huge_method_threshold)) {
613          Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
614        }
615        if (huge_method_threshold < 0) {
616          Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
617        }
618      } else if (option.starts_with("--large-method-max=")) {
619        const char* threshold = option.substr(strlen("--large-method-max=")).data();
620        if (!ParseInt(threshold, &large_method_threshold)) {
621          Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
622        }
623        if (large_method_threshold < 0) {
624          Usage("--large-method-max passed a negative value %s", large_method_threshold);
625        }
626      } else if (option.starts_with("--small-method-max=")) {
627        const char* threshold = option.substr(strlen("--small-method-max=")).data();
628        if (!ParseInt(threshold, &small_method_threshold)) {
629          Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
630        }
631        if (small_method_threshold < 0) {
632          Usage("--small-method-max passed a negative value %s", small_method_threshold);
633        }
634      } else if (option.starts_with("--tiny-method-max=")) {
635        const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
636        if (!ParseInt(threshold, &tiny_method_threshold)) {
637          Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
638        }
639        if (tiny_method_threshold < 0) {
640          Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
641        }
642      } else if (option.starts_with("--num-dex-methods=")) {
643        const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
644        if (!ParseInt(threshold, &num_dex_methods_threshold)) {
645          Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
646        }
647        if (num_dex_methods_threshold < 0) {
648          Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
649        }
650      } else if (option == "--host") {
651        is_host_ = true;
652      } else if (option == "--runtime-arg") {
653        if (++i >= argc) {
654          Usage("Missing required argument for --runtime-arg");
655        }
656        if (log_options) {
657          LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
658        }
659        runtime_args_.push_back(argv[i]);
660      } else if (option == "--dump-timing") {
661        dump_timing_ = true;
662      } else if (option == "--dump-passes") {
663        dump_passes_ = true;
664      } else if (option == "--dump-stats") {
665        dump_stats_ = true;
666      } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
667        include_debug_symbols = true;
668      } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
669        include_debug_symbols = false;
670        generate_gdb_information = false;  // Depends on debug symbols, see above.
671      } else if (option.starts_with("--profile-file=")) {
672        profile_file_ = option.substr(strlen("--profile-file=")).data();
673        VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
674      } else if (option == "--no-profile-file") {
675        // No profile
676      } else if (option.starts_with("--top-k-profile-threshold=")) {
677        ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
678      } else if (option == "--print-pass-names") {
679        PassDriverMEOpts::PrintPassNames();
680      } else if (option.starts_with("--disable-passes=")) {
681        std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
682        PassDriverMEOpts::CreateDefaultPassList(disable_passes);
683      } else if (option.starts_with("--print-passes=")) {
684        std::string print_passes = option.substr(strlen("--print-passes=")).data();
685        PassDriverMEOpts::SetPrintPassList(print_passes);
686      } else if (option == "--print-all-passes") {
687        PassDriverMEOpts::SetPrintAllPasses();
688      } else if (option.starts_with("--dump-cfg-passes=")) {
689        std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
690        PassDriverMEOpts::SetDumpPassList(dump_passes_string);
691      } else if (option == "--print-pass-options") {
692        print_pass_options = true;
693      } else if (option.starts_with("--pass-options=")) {
694        std::string options = option.substr(strlen("--pass-options=")).data();
695        PassDriverMEOpts::SetOverriddenPassOptions(options);
696      } else if (option == "--include-patch-information") {
697        include_patch_information = true;
698      } else if (option == "--no-include-patch-information") {
699        include_patch_information = false;
700      } else if (option.starts_with("--verbose-methods=")) {
701        // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
702        //       on having verbost methods.
703        gLogVerbosity.compiler = false;
704        Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
705      } else if (option.starts_with("--dump-init-failures=")) {
706        std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
707        init_failure_output_.reset(new std::ofstream(file_name));
708        if (init_failure_output_.get() == nullptr) {
709          LOG(ERROR) << "Failed to allocate ofstream";
710        } else if (init_failure_output_->fail()) {
711          LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
712                     << "failures.";
713          init_failure_output_.reset();
714        }
715      } else {
716        Usage("Unknown argument %s", option.data());
717      }
718    }
719
720    if (oat_filename_.empty() && oat_fd_ == -1) {
721      Usage("Output must be supplied with either --oat-file or --oat-fd");
722    }
723
724    if (!oat_filename_.empty() && oat_fd_ != -1) {
725      Usage("--oat-file should not be used with --oat-fd");
726    }
727
728    if (!oat_symbols.empty() && oat_fd_ != -1) {
729      Usage("--oat-symbols should not be used with --oat-fd");
730    }
731
732    if (!oat_symbols.empty() && is_host_) {
733      Usage("--oat-symbols should not be used with --host");
734    }
735
736    if (oat_fd_ != -1 && !image_filename_.empty()) {
737      Usage("--oat-fd should not be used with --image");
738    }
739
740    if (android_root_.empty()) {
741      const char* android_root_env_var = getenv("ANDROID_ROOT");
742      if (android_root_env_var == nullptr) {
743        Usage("--android-root unspecified and ANDROID_ROOT not set");
744      }
745      android_root_ += android_root_env_var;
746    }
747
748    image_ = (!image_filename_.empty());
749    if (!image_ && boot_image_filename.empty()) {
750      boot_image_filename += android_root_;
751      boot_image_filename += "/framework/boot.art";
752    }
753    if (!boot_image_filename.empty()) {
754      boot_image_option_ += "-Ximage:";
755      boot_image_option_ += boot_image_filename;
756    }
757
758    if (image_classes_filename_ != nullptr && !image_) {
759      Usage("--image-classes should only be used with --image");
760    }
761
762    if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
763      Usage("--image-classes should not be used with --boot-image");
764    }
765
766    if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
767      Usage("--image-classes-zip should be used with --image-classes");
768    }
769
770    if (compiled_classes_filename_ != nullptr && !image_) {
771      Usage("--compiled-classes should only be used with --image");
772    }
773
774    if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
775      Usage("--compiled-classes should not be used with --boot-image");
776    }
777
778    if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
779      Usage("--compiled-classes-zip should be used with --compiled-classes");
780    }
781
782    if (dex_filenames_.empty() && zip_fd_ == -1) {
783      Usage("Input must be supplied with either --dex-file or --zip-fd");
784    }
785
786    if (!dex_filenames_.empty() && zip_fd_ != -1) {
787      Usage("--dex-file should not be used with --zip-fd");
788    }
789
790    if (!dex_filenames_.empty() && !zip_location_.empty()) {
791      Usage("--dex-file should not be used with --zip-location");
792    }
793
794    if (dex_locations_.empty()) {
795      for (const char* dex_file_name : dex_filenames_) {
796        dex_locations_.push_back(dex_file_name);
797      }
798    } else if (dex_locations_.size() != dex_filenames_.size()) {
799      Usage("--dex-location arguments do not match --dex-file arguments");
800    }
801
802    if (zip_fd_ != -1 && zip_location_.empty()) {
803      Usage("--zip-location should be supplied with --zip-fd");
804    }
805
806    if (boot_image_option_.empty()) {
807      if (image_base_ == 0) {
808        Usage("Non-zero --base not specified");
809      }
810    }
811
812    oat_stripped_ = oat_filename_;
813    if (!oat_symbols.empty()) {
814      oat_unstripped_ = oat_symbols;
815    } else {
816      oat_unstripped_ = oat_filename_;
817    }
818
819    // If no instruction set feature was given, use the default one for the target
820    // instruction set.
821    if (instruction_set_features_.get() == nullptr) {
822      instruction_set_features_.reset(
823          InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
824      if (instruction_set_features_.get() == nullptr) {
825        Usage("Problem initializing default instruction set features variant: %s",
826              error_msg.c_str());
827      }
828    }
829
830    if (instruction_set_ == kRuntimeISA) {
831      std::unique_ptr<const InstructionSetFeatures> runtime_features(
832          InstructionSetFeatures::FromCppDefines());
833      if (!instruction_set_features_->Equals(runtime_features.get())) {
834        LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
835            << *instruction_set_features_ << ") and those of dex2oat executable ("
836            << *runtime_features <<") for the command line:\n"
837            << CommandLine();
838      }
839    }
840
841    if (compiler_filter_string == nullptr) {
842      if (instruction_set_ == kMips64) {
843        // TODO: fix compiler for Mips64.
844        compiler_filter_string = "interpret-only";
845      } else if (image_) {
846        compiler_filter_string = "speed";
847      } else {
848        // TODO: Migrate SMALL mode to command line option.
849  #if ART_SMALL_MODE
850        compiler_filter_string = "interpret-only";
851  #else
852        compiler_filter_string = "speed";
853  #endif
854      }
855    }
856    CHECK(compiler_filter_string != nullptr);
857    CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
858    if (strcmp(compiler_filter_string, "verify-none") == 0) {
859      compiler_filter = CompilerOptions::kVerifyNone;
860    } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
861      compiler_filter = CompilerOptions::kInterpretOnly;
862    } else if (strcmp(compiler_filter_string, "space") == 0) {
863      compiler_filter = CompilerOptions::kSpace;
864    } else if (strcmp(compiler_filter_string, "balanced") == 0) {
865      compiler_filter = CompilerOptions::kBalanced;
866    } else if (strcmp(compiler_filter_string, "speed") == 0) {
867      compiler_filter = CompilerOptions::kSpeed;
868    } else if (strcmp(compiler_filter_string, "everything") == 0) {
869      compiler_filter = CompilerOptions::kEverything;
870    } else if (strcmp(compiler_filter_string, "time") == 0) {
871      compiler_filter = CompilerOptions::kTime;
872    } else {
873      Usage("Unknown --compiler-filter value %s", compiler_filter_string);
874    }
875
876    // Checks are all explicit until we know the architecture.
877    bool implicit_null_checks = false;
878    bool implicit_so_checks = false;
879    bool implicit_suspend_checks = false;
880    // Set the compilation target's implicit checks options.
881    switch (instruction_set_) {
882      case kArm:
883      case kThumb2:
884      case kArm64:
885      case kX86:
886      case kX86_64:
887        implicit_null_checks = true;
888        implicit_so_checks = true;
889        break;
890
891      default:
892        // Defaults are correct.
893        break;
894    }
895
896    if (print_pass_options) {
897      PassDriverMEOpts::PrintPassOptions();
898    }
899
900    compiler_options_.reset(new CompilerOptions(compiler_filter,
901                                                huge_method_threshold,
902                                                large_method_threshold,
903                                                small_method_threshold,
904                                                tiny_method_threshold,
905                                                num_dex_methods_threshold,
906                                                generate_gdb_information,
907                                                include_patch_information,
908                                                top_k_profile_threshold,
909                                                include_debug_symbols,
910                                                implicit_null_checks,
911                                                implicit_so_checks,
912                                                implicit_suspend_checks,
913                                                compile_pic,
914  #ifdef ART_SEA_IR_MODE
915                                                true,
916  #endif
917                                                verbose_methods_.empty() ?
918                                                    nullptr :
919                                                    &verbose_methods_,
920                                                init_failure_output_.get()));
921
922    // Done with usage checks, enable watchdog if requested
923    if (watch_dog_enabled) {
924      watchdog_.reset(new WatchDog(true));
925    }
926
927    // Fill some values into the key-value store for the oat header.
928    key_value_store_.reset(new SafeMap<std::string, std::string>());
929
930    // Insert some compiler things.
931    {
932      std::ostringstream oss;
933      for (int i = 0; i < argc; ++i) {
934        if (i > 0) {
935          oss << ' ';
936        }
937        oss << argv[i];
938      }
939      key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
940      oss.str("");  // Reset.
941      oss << kRuntimeISA;
942      key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
943      key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
944    }
945  }
946
947  // Check whether the oat output file is writable, and open it for later.
948  bool OpenFile() {
949    bool create_file = !oat_unstripped_.empty();  // as opposed to using open file descriptor
950    if (create_file) {
951      oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
952      if (oat_location_.empty()) {
953        oat_location_ = oat_filename_;
954      }
955    } else {
956      oat_file_.reset(new File(oat_fd_, oat_location_, true));
957      oat_file_->DisableAutoClose();
958      if (oat_file_->SetLength(0) != 0) {
959        PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
960      }
961    }
962    if (oat_file_.get() == nullptr) {
963      PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
964      return false;
965    }
966    if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
967      PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
968      oat_file_->Erase();
969      return false;
970    }
971    return true;
972  }
973
974  // Set up the environment for compilation. Includes starting the runtime and loading/opening the
975  // boot class path.
976  bool Setup() {
977    TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
978    RuntimeOptions runtime_options;
979    std::vector<const DexFile*> boot_class_path;
980    art::MemMap::Init();  // For ZipEntry::ExtractToMemMap.
981    if (boot_image_option_.empty()) {
982      size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
983      if (failure_count > 0) {
984        LOG(ERROR) << "Failed to open some dex files: " << failure_count;
985        return false;
986      }
987      runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
988    } else {
989      runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
990    }
991    for (size_t i = 0; i < runtime_args_.size(); i++) {
992      runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
993    }
994
995    verification_results_.reset(new VerificationResults(compiler_options_.get()));
996    callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
997    runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
998    runtime_options.push_back(
999        std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1000
1001    if (!CreateRuntime(runtime_options)) {
1002      return false;
1003    }
1004
1005    // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1006    // Runtime::Start, give it away now so that we don't starve GC.
1007    Thread* self = Thread::Current();
1008    self->TransitionFromRunnableToSuspended(kNative);
1009    // If we're doing the image, override the compiler filter to force full compilation. Must be
1010    // done ahead of WellKnownClasses::Init that causes verification.  Note: doesn't force
1011    // compilation of class initializers.
1012    // Whilst we're in native take the opportunity to initialize well known classes.
1013    WellKnownClasses::Init(self->GetJniEnv());
1014
1015    // If --image-classes was specified, calculate the full list of classes to include in the image
1016    if (image_classes_filename_ != nullptr) {
1017      std::string error_msg;
1018      if (image_classes_zip_filename_ != nullptr) {
1019        image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1020                                                    image_classes_filename_,
1021                                                    &error_msg));
1022      } else {
1023        image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1024      }
1025      if (image_classes_.get() == nullptr) {
1026        LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1027            "': " << error_msg;
1028        return false;
1029      }
1030    } else if (image_) {
1031      image_classes_.reset(new std::set<std::string>);
1032    }
1033    // If --compiled-classes was specified, calculate the full list of classes to compile in the
1034    // image.
1035    if (compiled_classes_filename_ != nullptr) {
1036      std::string error_msg;
1037      if (compiled_classes_zip_filename_ != nullptr) {
1038        compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1039                                                        compiled_classes_filename_,
1040                                                        &error_msg));
1041      } else {
1042        compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1043      }
1044      if (compiled_classes_.get() == nullptr) {
1045        LOG(ERROR) << "Failed to create list of compiled classes from '"
1046                   << compiled_classes_filename_ << "': " << error_msg;
1047        return false;
1048      }
1049    } else if (image_) {
1050      compiled_classes_.reset(nullptr);  // By default compile everything.
1051    }
1052
1053    if (boot_image_option_.empty()) {
1054      dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1055    } else {
1056      if (dex_filenames_.empty()) {
1057        ATRACE_BEGIN("Opening zip archive from file descriptor");
1058        std::string error_msg;
1059        std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1060                                                                       zip_location_.c_str(),
1061                                                                       &error_msg));
1062        if (zip_archive.get() == nullptr) {
1063          LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1064              << error_msg;
1065          return false;
1066        }
1067        if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1068          LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1069              << "': " << error_msg;
1070          return false;
1071        }
1072        ATRACE_END();
1073      } else {
1074        size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1075        if (failure_count > 0) {
1076          LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1077          return false;
1078        }
1079      }
1080
1081      constexpr bool kSaveDexInput = false;
1082      if (kSaveDexInput) {
1083        for (size_t i = 0; i < dex_files_.size(); ++i) {
1084          const DexFile* dex_file = dex_files_[i];
1085          std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1086          std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1087          if (tmp_file.get() == nullptr) {
1088            PLOG(ERROR) << "Failed to open file " << tmp_file_name
1089                << ". Try: adb shell chmod 777 /data/local/tmp";
1090            continue;
1091          }
1092          // This is just dumping files for debugging. Ignore errors, and leave remnants.
1093          UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1094          UNUSED(tmp_file->Flush());
1095          UNUSED(tmp_file->Close());
1096          LOG(INFO) << "Wrote input to " << tmp_file_name;
1097        }
1098      }
1099    }
1100    // Ensure opened dex files are writable for dex-to-dex transformations.
1101    for (const auto& dex_file : dex_files_) {
1102      if (!dex_file->EnableWrite()) {
1103        PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
1104      }
1105    }
1106
1107    /*
1108     * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1109     * Don't bother to check if we're doing the image.
1110     */
1111    if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1112      size_t num_methods = 0;
1113      for (size_t i = 0; i != dex_files_.size(); ++i) {
1114        const DexFile* dex_file = dex_files_[i];
1115        CHECK(dex_file != nullptr);
1116        num_methods += dex_file->NumMethodIds();
1117      }
1118      if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1119        compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1120        VLOG(compiler) << "Below method threshold, compiling anyways";
1121      }
1122    }
1123
1124    return true;
1125  }
1126
1127  // Create and invoke the compiler driver. This will compile all the dex files.
1128  void Compile() {
1129    TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1130    compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
1131
1132    // Handle and ClassLoader creation needs to come after Runtime::Create
1133    jobject class_loader = nullptr;
1134    Thread* self = Thread::Current();
1135    if (!boot_image_option_.empty()) {
1136      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1137      std::vector<const DexFile*> class_path_files(dex_files_);
1138      OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1139      ScopedObjectAccess soa(self);
1140      for (size_t i = 0; i < class_path_files.size(); i++) {
1141        class_linker->RegisterDexFile(*class_path_files[i]);
1142      }
1143      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1144      ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1145          soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1146      class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1147      Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1148    }
1149
1150    driver_.reset(new CompilerDriver(compiler_options_.get(),
1151                                     verification_results_.get(),
1152                                     &method_inliner_map_,
1153                                     compiler_kind_,
1154                                     instruction_set_,
1155                                     instruction_set_features_.get(),
1156                                     image_,
1157                                     image_classes_.release(),
1158                                     compiled_classes_.release(),
1159                                     thread_count_,
1160                                     dump_stats_,
1161                                     dump_passes_,
1162                                     compiler_phases_timings_.get(),
1163                                     profile_file_));
1164
1165    driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1166
1167    driver_->CompileAll(class_loader, dex_files_, timings_);
1168  }
1169
1170  // Notes on the interleaving of creating the image and oat file to
1171  // ensure the references between the two are correct.
1172  //
1173  // Currently we have a memory layout that looks something like this:
1174  //
1175  // +--------------+
1176  // | image        |
1177  // +--------------+
1178  // | boot oat     |
1179  // +--------------+
1180  // | alloc spaces |
1181  // +--------------+
1182  //
1183  // There are several constraints on the loading of the image and boot.oat.
1184  //
1185  // 1. The image is expected to be loaded at an absolute address and
1186  // contains Objects with absolute pointers within the image.
1187  //
1188  // 2. There are absolute pointers from Methods in the image to their
1189  // code in the oat.
1190  //
1191  // 3. There are absolute pointers from the code in the oat to Methods
1192  // in the image.
1193  //
1194  // 4. There are absolute pointers from code in the oat to other code
1195  // in the oat.
1196  //
1197  // To get this all correct, we go through several steps.
1198  //
1199  // 1. We prepare offsets for all data in the oat file and calculate
1200  // the oat data size and code size. During this stage, we also set
1201  // oat code offsets in methods for use by the image writer.
1202  //
1203  // 2. We prepare offsets for the objects in the image and calculate
1204  // the image size.
1205  //
1206  // 3. We create the oat file. Originally this was just our own proprietary
1207  // file but now it is contained within an ELF dynamic object (aka an .so
1208  // file). Since we know the image size and oat data size and code size we
1209  // can prepare the ELF headers and we then know the ELF memory segment
1210  // layout and we can now resolve all references. The compiler provides
1211  // LinkerPatch information in each CompiledMethod and we resolve these,
1212  // using the layout information and image object locations provided by
1213  // image writer, as we're writing the method code.
1214  //
1215  // 4. We create the image file. It needs to know where the oat file
1216  // will be loaded after itself. Originally when oat file was simply
1217  // memory mapped so we could predict where its contents were based
1218  // on the file size. Now that it is an ELF file, we need to inspect
1219  // the ELF file to understand the in memory segment layout including
1220  // where the oat header is located within.
1221  // TODO: We could just remember this information from step 3.
1222  //
1223  // 5. We fixup the ELF program headers so that dlopen will try to
1224  // load the .so at the desired location at runtime by offsetting the
1225  // Elf32_Phdr.p_vaddr values by the desired base address.
1226  // TODO: Do this in step 3. We already know the layout there.
1227  //
1228  // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1229  // are done by the CreateImageFile() below.
1230
1231
1232  // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1233  // ImageWriter, if necessary.
1234  // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1235  //       case (when the file will be explicitly erased).
1236  bool CreateOatFile() {
1237    CHECK(key_value_store_.get() != nullptr);
1238
1239    TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1240
1241    std::unique_ptr<OatWriter> oat_writer;
1242    {
1243      TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1244      std::string image_file_location;
1245      uint32_t image_file_location_oat_checksum = 0;
1246      uintptr_t image_file_location_oat_data_begin = 0;
1247      int32_t image_patch_delta = 0;
1248      if (image_) {
1249        PrepareImageWriter(image_base_);
1250      } else {
1251        TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1252        gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1253        image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1254        image_file_location_oat_data_begin =
1255            reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1256        image_file_location = image_space->GetImageFilename();
1257        image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1258      }
1259
1260      if (!image_file_location.empty()) {
1261        key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1262      }
1263
1264      oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1265                                     image_file_location_oat_data_begin,
1266                                     image_patch_delta,
1267                                     driver_.get(),
1268                                     image_writer_.get(),
1269                                     timings_,
1270                                     key_value_store_.get()));
1271    }
1272
1273    if (image_) {
1274      // The OatWriter constructor has already updated offsets in methods and we need to
1275      // prepare method offsets in the image address space for direct method patching.
1276      TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1277      if (!image_writer_->PrepareImageAddressSpace()) {
1278        LOG(ERROR) << "Failed to prepare image address space.";
1279        return false;
1280      }
1281    }
1282
1283    {
1284      TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1285      if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1286                             oat_file_.get())) {
1287        LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1288        oat_file_->Erase();
1289        return false;
1290      }
1291    }
1292
1293    VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1294    return true;
1295  }
1296
1297  // If we are compiling an image, invoke the image creation routine. Else just skip.
1298  bool HandleImage() {
1299    if (image_) {
1300      TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1301      if (!CreateImageFile()) {
1302        return false;
1303      }
1304      VLOG(compiler) << "Image written successfully: " << image_filename_;
1305    }
1306    return true;
1307  }
1308
1309  // Create a copy from unstripped to stripped.
1310  bool CopyUnstrippedToStripped() {
1311    // If we don't want to strip in place, copy from unstripped location to stripped location.
1312    // We need to strip after image creation because FixupElf needs to use .strtab.
1313    if (oat_unstripped_ != oat_stripped_) {
1314      // If the oat file is still open, flush it.
1315      if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1316        if (!FlushCloseOatFile()) {
1317          return false;
1318        }
1319      }
1320
1321      TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1322      std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1323      std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1324      size_t buffer_size = 8192;
1325      std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1326      while (true) {
1327        int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1328        if (bytes_read <= 0) {
1329          break;
1330        }
1331        bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1332        CHECK(write_ok);
1333      }
1334      if (kUsePortableCompiler) {
1335        oat_file_.reset(out.release());
1336      } else {
1337        if (out->FlushCloseOrErase() != 0) {
1338          PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1339          return false;
1340        }
1341      }
1342      VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
1343    }
1344    return true;
1345  }
1346
1347  // Run the ElfStripper. Currently only relevant for the portable compiler.
1348  bool Strip() {
1349    if (kUsePortableCompiler) {
1350      // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1351      // strip them now. Quick generates debug symbols only when the flag(s) are set.
1352      if (!compiler_options_->GetIncludeDebugSymbols()) {
1353        CHECK(oat_file_.get() != nullptr && oat_file_->IsOpened());
1354
1355        TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1356        // Strip unneeded sections for target
1357        off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1358        CHECK_EQ(0, seek_actual);
1359        std::string error_msg;
1360        if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1361          LOG(ERROR) << "Failed to strip elf file: " << error_msg;
1362          oat_file_->Erase();
1363          return false;
1364        }
1365
1366        if (!FlushCloseOatFile()) {
1367          return false;
1368        }
1369
1370        // We wrote the oat file successfully, and want to keep it.
1371        VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1372      } else {
1373        VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1374      }
1375    }
1376
1377    return true;
1378  }
1379
1380  bool FlushOatFile() {
1381    if (oat_file_.get() != nullptr) {
1382      TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1383      if (oat_file_->Flush() != 0) {
1384        PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1385            << oat_filename_;
1386        oat_file_->Erase();
1387        return false;
1388      }
1389    }
1390    return true;
1391  }
1392
1393  bool FlushCloseOatFile() {
1394    if (oat_file_.get() != nullptr) {
1395      std::unique_ptr<File> tmp(oat_file_.release());
1396      if (tmp->FlushCloseOrErase() != 0) {
1397        PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1398            << oat_filename_;
1399        return false;
1400      }
1401    }
1402    return true;
1403  }
1404
1405  void DumpTiming() {
1406    if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1407      LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1408    }
1409    if (dump_passes_) {
1410      LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1411    }
1412  }
1413
1414  CompilerOptions* GetCompilerOptions() const {
1415    return compiler_options_.get();
1416  }
1417
1418  bool IsImage() const {
1419    return image_;
1420  }
1421
1422  bool IsHost() const {
1423    return is_host_;
1424  }
1425
1426 private:
1427  static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1428                             const std::vector<const char*>& dex_locations,
1429                             std::vector<const DexFile*>& dex_files) {
1430    size_t failure_count = 0;
1431    for (size_t i = 0; i < dex_filenames.size(); i++) {
1432      const char* dex_filename = dex_filenames[i];
1433      const char* dex_location = dex_locations[i];
1434      ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1435      std::string error_msg;
1436      if (!OS::FileExists(dex_filename)) {
1437        LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1438        continue;
1439      }
1440      if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1441        LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1442        ++failure_count;
1443      }
1444      ATRACE_END();
1445    }
1446    return failure_count;
1447  }
1448
1449  // Returns true if dex_files has a dex with the named location.
1450  static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1451                               const std::string& location) {
1452    for (size_t i = 0; i < dex_files.size(); ++i) {
1453      if (dex_files[i]->GetLocation() == location) {
1454        return true;
1455      }
1456    }
1457    return false;
1458  }
1459
1460  // Appends to dex_files any elements of class_path that it doesn't already
1461  // contain. This will open those dex files as necessary.
1462  static void OpenClassPathFiles(const std::string& class_path,
1463                                 std::vector<const DexFile*>& dex_files) {
1464    std::vector<std::string> parsed;
1465    Split(class_path, ':', &parsed);
1466    // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1467    ScopedObjectAccess soa(Thread::Current());
1468    for (size_t i = 0; i < parsed.size(); ++i) {
1469      if (DexFilesContains(dex_files, parsed[i])) {
1470        continue;
1471      }
1472      std::string error_msg;
1473      if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1474        LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1475      }
1476    }
1477  }
1478
1479  // Create a runtime necessary for compilation.
1480  bool CreateRuntime(const RuntimeOptions& runtime_options)
1481      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1482    if (!Runtime::Create(runtime_options, false)) {
1483      LOG(ERROR) << "Failed to create runtime";
1484      return false;
1485    }
1486    Runtime* runtime = Runtime::Current();
1487    runtime->SetInstructionSet(instruction_set_);
1488    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1489      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1490      if (!runtime->HasCalleeSaveMethod(type)) {
1491        runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1492      }
1493    }
1494    runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1495    runtime->GetClassLinker()->RunRootClinits();
1496    runtime_ = runtime;
1497    return true;
1498  }
1499
1500  void PrepareImageWriter(uintptr_t image_base) {
1501    image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1502  }
1503
1504  // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1505  bool CreateImageFile()
1506      LOCKS_EXCLUDED(Locks::mutator_lock_) {
1507    CHECK(image_writer_ != nullptr);
1508    if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1509      LOG(ERROR) << "Failed to create image file " << image_filename_;
1510      return false;
1511    }
1512    uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1513
1514    // Destroy ImageWriter before doing FixupElf.
1515    image_writer_.reset();
1516
1517    // Do not fix up the ELF file if we are --compile-pic
1518    if (!compiler_options_->GetCompilePic()) {
1519      std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1520      if (oat_file.get() == nullptr) {
1521        PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1522        return false;
1523      }
1524
1525      if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
1526        oat_file->Erase();
1527        LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1528        return false;
1529      }
1530
1531      if (oat_file->FlushCloseOrErase()) {
1532        PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1533        return false;
1534      }
1535    }
1536
1537    return true;
1538  }
1539
1540  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1541  static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1542    std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1543                                                                        std::ifstream::in));
1544    if (image_classes_file.get() == nullptr) {
1545      LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1546      return nullptr;
1547    }
1548    std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1549    image_classes_file->close();
1550    return result.release();
1551  }
1552
1553  static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1554    std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1555    while (image_classes_stream.good()) {
1556      std::string dot;
1557      std::getline(image_classes_stream, dot);
1558      if (StartsWith(dot, "#") || dot.empty()) {
1559        continue;
1560      }
1561      std::string descriptor(DotToDescriptor(dot.c_str()));
1562      image_classes->insert(descriptor);
1563    }
1564    return image_classes.release();
1565  }
1566
1567  // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1568  static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1569                                                        const char* image_classes_filename,
1570                                                        std::string* error_msg) {
1571    std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1572    if (zip_archive.get() == nullptr) {
1573      return nullptr;
1574    }
1575    std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1576    if (zip_entry.get() == nullptr) {
1577      *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1578                                zip_filename, error_msg->c_str());
1579      return nullptr;
1580    }
1581    std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1582                                                                          image_classes_filename,
1583                                                                          error_msg));
1584    if (image_classes_file.get() == nullptr) {
1585      *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1586                                zip_filename, error_msg->c_str());
1587      return nullptr;
1588    }
1589    const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1590                                           image_classes_file->Size());
1591    std::istringstream image_classes_stream(image_classes_string);
1592    return ReadImageClasses(image_classes_stream);
1593  }
1594
1595  void LogCompletionTime() const {
1596    LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
1597              << " (threads: " << thread_count_ << ")";
1598  }
1599
1600  std::unique_ptr<CompilerOptions> compiler_options_;
1601  Compiler::Kind compiler_kind_;
1602
1603  InstructionSet instruction_set_;
1604  std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1605
1606  std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1607
1608  std::unique_ptr<VerificationResults> verification_results_;
1609  DexFileToMethodInlinerMap method_inliner_map_;
1610  std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1611
1612  // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1613  // in an orderly fashion. The destructor takes care of deleting this.
1614  Runtime* runtime_;
1615
1616  size_t thread_count_;
1617  uint64_t start_ns_;
1618  std::unique_ptr<WatchDog> watchdog_;
1619  std::unique_ptr<File> oat_file_;
1620  std::string oat_stripped_;
1621  std::string oat_unstripped_;
1622  std::string oat_location_;
1623  std::string oat_filename_;
1624  int oat_fd_;
1625  std::string bitcode_filename_;
1626  std::vector<const char*> dex_filenames_;
1627  std::vector<const char*> dex_locations_;
1628  int zip_fd_;
1629  std::string zip_location_;
1630  std::string boot_image_option_;
1631  std::vector<const char*> runtime_args_;
1632  std::string image_filename_;
1633  uintptr_t image_base_;
1634  const char* image_classes_zip_filename_;
1635  const char* image_classes_filename_;
1636  const char* compiled_classes_zip_filename_;
1637  const char* compiled_classes_filename_;
1638  std::unique_ptr<std::set<std::string>> image_classes_;
1639  std::unique_ptr<std::set<std::string>> compiled_classes_;
1640  bool image_;
1641  std::unique_ptr<ImageWriter> image_writer_;
1642  bool is_host_;
1643  std::string android_root_;
1644  std::vector<const DexFile*> dex_files_;
1645  std::unique_ptr<CompilerDriver> driver_;
1646  std::vector<std::string> verbose_methods_;
1647  bool dump_stats_;
1648  bool dump_passes_;
1649  bool dump_timing_;
1650  bool dump_slow_timing_;
1651  std::string profile_file_;  // Profile file to use
1652  TimingLogger* timings_;
1653  std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1654  std::unique_ptr<std::ostream> init_failure_output_;
1655
1656  DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1657};
1658
1659const unsigned int WatchDog::kWatchDogWarningSeconds;
1660const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1661
1662static void b13564922() {
1663#if defined(__linux__) && defined(__arm__)
1664  int major, minor;
1665  struct utsname uts;
1666  if (uname(&uts) != -1 &&
1667      sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1668      ((major < 3) || ((major == 3) && (minor < 4)))) {
1669    // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1670    // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1671    int old_personality = personality(0xffffffff);
1672    if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1673      int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1674      if (new_personality == -1) {
1675        LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1676      }
1677    }
1678  }
1679#endif
1680}
1681
1682static int CompileImage(Dex2Oat& dex2oat) {
1683  dex2oat.Compile();
1684
1685  // Create the boot.oat.
1686  if (!dex2oat.CreateOatFile()) {
1687    return EXIT_FAILURE;
1688  }
1689
1690  // Flush and close the boot.oat. We always expect the output file by name, and it will be
1691  // re-opened from the unstripped name.
1692  if (!dex2oat.FlushCloseOatFile()) {
1693    return EXIT_FAILURE;
1694  }
1695
1696  // Creates the boot.art and patches the boot.oat.
1697  if (!dex2oat.HandleImage()) {
1698    return EXIT_FAILURE;
1699  }
1700
1701  // When given --host, finish early without stripping.
1702  if (dex2oat.IsHost()) {
1703    dex2oat.DumpTiming();
1704    return EXIT_SUCCESS;
1705  }
1706
1707  // Copy unstripped to stripped location, if necessary.
1708  if (!dex2oat.CopyUnstrippedToStripped()) {
1709    return EXIT_FAILURE;
1710  }
1711
1712  // Strip, if necessary.
1713  if (!dex2oat.Strip()) {
1714    return EXIT_FAILURE;
1715  }
1716
1717  // FlushClose again, as stripping might have re-opened the oat file.
1718  if (!dex2oat.FlushCloseOatFile()) {
1719    return EXIT_FAILURE;
1720  }
1721
1722  dex2oat.DumpTiming();
1723  return EXIT_SUCCESS;
1724}
1725
1726static int CompileApp(Dex2Oat& dex2oat) {
1727  dex2oat.Compile();
1728
1729  // Create the app oat.
1730  if (!dex2oat.CreateOatFile()) {
1731    return EXIT_FAILURE;
1732  }
1733
1734  // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1735  // which we would lose.
1736  if (!dex2oat.FlushOatFile()) {
1737    return EXIT_FAILURE;
1738  }
1739
1740  // When given --host, finish early without stripping.
1741  if (dex2oat.IsHost()) {
1742    if (!dex2oat.FlushCloseOatFile()) {
1743      return EXIT_FAILURE;
1744    }
1745
1746    dex2oat.DumpTiming();
1747    return EXIT_SUCCESS;
1748  }
1749
1750  // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1751  // unstripped version. If this is given, we expect to be able to open writable files by name.
1752  if (!dex2oat.CopyUnstrippedToStripped()) {
1753    return EXIT_FAILURE;
1754  }
1755
1756  // Strip, if necessary.
1757  if (!dex2oat.Strip()) {
1758    return EXIT_FAILURE;
1759  }
1760
1761  // Flush and close the file.
1762  if (!dex2oat.FlushCloseOatFile()) {
1763    return EXIT_FAILURE;
1764  }
1765
1766  dex2oat.DumpTiming();
1767  return EXIT_SUCCESS;
1768}
1769
1770static int dex2oat(int argc, char** argv) {
1771  b13564922();
1772
1773  TimingLogger timings("compiler", false, false);
1774
1775  Dex2Oat dex2oat(&timings);
1776
1777  // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1778  dex2oat.ParseArgs(argc, argv);
1779
1780  // Check early that the result of compilation can be written
1781  if (!dex2oat.OpenFile()) {
1782    return EXIT_FAILURE;
1783  }
1784
1785  LOG(INFO) << CommandLine();
1786
1787  if (!dex2oat.Setup()) {
1788    return EXIT_FAILURE;
1789  }
1790
1791  if (dex2oat.IsImage()) {
1792    return CompileImage(dex2oat);
1793  } else {
1794    return CompileApp(dex2oat);
1795  }
1796}
1797}  // namespace art
1798
1799int main(int argc, char** argv) {
1800  int result = art::dex2oat(argc, argv);
1801  // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1802  // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1803  // should not destruct the runtime in this case.
1804  if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1805    exit(result);
1806  }
1807  return result;
1808}
1809