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