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