blob: c8b27dba05f5c8616da014eec176d13299afb287 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
Vladimir Markof94b7812014-06-05 15:48:04 +010028#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
Ian Rogerscf7f1912014-10-22 22:06:39 -070033#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080034#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070035
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include "arch/instruction_set_features.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070037#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000043#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000044#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070046#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000047#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070048#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080051#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080052#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070053#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070058#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070068#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
Brian Carlstrom6449c622014-02-10 23:48:36 -080075static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79 std::vector<std::string> command;
80 for (int i = 0; i < original_argc; ++i) {
81 command.push_back(original_argv[i]);
82 }
83 return Join(command, ' ');
84}
85
Brian Carlstrom7940e442013-07-12 13:46:57 -070086static void UsageErrorV(const char* fmt, va_list ap) {
87 std::string error;
88 StringAppendV(&error, fmt, ap);
89 LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93 va_list ap;
94 va_start(ap, fmt);
95 UsageErrorV(fmt, ap);
96 va_end(ap);
97}
98
Ian Rogers7223d442014-10-10 20:05:39 -070099[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700100 va_list ap;
101 va_start(ap, fmt);
102 UsageErrorV(fmt, ap);
103 va_end(ap);
104
Brian Carlstrom6449c622014-02-10 23:48:36 -0800105 UsageError("Command: %s", CommandLine().c_str());
106
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 UsageError("Usage: dex2oat [options]...");
108 UsageError("");
109 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
110 UsageError(" Example: --dex-file=/system/framework/core.jar");
111 UsageError("");
112 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113 UsageError(" containing a classes.dex file to compile.");
114 UsageError(" Example: --zip-fd=5");
115 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700116 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
117 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
119 UsageError("");
120 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121 UsageError(" Example: --oat-file=/system/framework/boot.oat");
122 UsageError("");
123 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900124 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 UsageError("");
126 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127 UsageError(" to the file descriptor specified by --oat-fd.");
128 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129 UsageError("");
130 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
132 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 UsageError(" --image=<file.art>: specifies the output image filename.");
134 UsageError(" Example: --image=/system/framework/boot.art");
135 UsageError("");
136 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
137 UsageError(" Example: --image=frameworks/base/preloaded-classes");
138 UsageError("");
139 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
140 UsageError(" Example: --base=0x50000000");
141 UsageError("");
142 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
143 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000144 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145 UsageError("");
146 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
147 UsageError(" Example: --android-root=out/host/linux-x86");
148 UsageError(" Default: $ANDROID_ROOT");
149 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700150 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
151 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 UsageError(" Example: --instruction-set=x86");
153 UsageError(" Default: arm");
154 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700155 UsageError(" --instruction-set-features=...,: Specify instruction set features");
156 UsageError(" Example: --instruction-set-features=div");
157 UsageError(" Default: default");
158 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700159 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
160 UsageError(" Default: disabled");
161 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800162 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800164 UsageError(" Example: --compiler-backend=Optimizing");
165 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000166 UsageError(" Default: Optimizing");
167 } else {
168 UsageError(" Default: Quick");
169 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100171 UsageError(" --compiler-filter="
172 "(verify-none"
173 "|interpret-only"
174 "|space"
175 "|balanced"
176 "|speed"
177 "|everything"
178 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700179 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800180 UsageError(" Example: --compiler-filter=everything");
181#if ART_SMALL_MODE
182 UsageError(" Default: interpret-only");
183#else
184 UsageError(" Default: speed");
185#endif
186 UsageError("");
187 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
188 UsageError(" method for compiler filter tuning.");
189 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
190 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
191 UsageError("");
192 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
193 UsageError(" method for compiler filter tuning.");
194 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
196 UsageError("");
197 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
198 UsageError(" method for compiler filter tuning.");
199 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
200 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
201 UsageError("");
202 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
203 UsageError(" method for compiler filter tuning.");
204 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
205 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
206 UsageError("");
207 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
208 UsageError(" method for compiler filter tuning.");
209 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
210 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
211 UsageError("");
212 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
213 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700214 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
215 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800216 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
218 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700219 UsageError(" --dump-timing: display a breakdown of where time was spent");
220 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700221 UsageError(" --include-patch-information: Include patching information so the generated code");
222 UsageError(" can have its base address moved without full recompilation.");
223 UsageError("");
224 UsageError(" --no-include-patch-information: Do not include patching information.");
225 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700226 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
227 UsageError("");
228 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
229 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
231 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
232 UsageError(" Use a separate --runtime-arg switch for each argument.");
233 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700234 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000235 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700237 UsageError(" --print-pass-names: print a list of pass names");
238 UsageError("");
239 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
240 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
241 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700242 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
243 "with the setting.");
244 UsageError(" Will print default if no overridden setting exists.");
245 UsageError("");
246 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
247 "Pass2Name:Pass2OptionName:Pass2Option#");
248 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
249 UsageError(" Separator used between options is a comma.");
250 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800251 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
252 UsageError(" Example: --swap-file=/data/tmp/swap.001");
253 UsageError("");
254 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
255 UsageError(" Example: --swap-fd=10");
256 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 std::cerr << "See log for usage error information\n";
258 exit(EXIT_FAILURE);
259}
260
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261// The primary goal of the watchdog is to prevent stuck build servers
262// during development when fatal aborts lead to a cascade of failures
263// that result in a deadlock.
264class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800265// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700266#undef CHECK_PTHREAD_CALL
267#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
268 do { \
269 int rc = call args; \
270 if (rc != 0) { \
271 errno = rc; \
272 std::string message(# call); \
273 message += " failed for "; \
274 message += reason; \
275 Fatal(message); \
276 } \
277 } while (false)
278
279 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700280 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281 is_watch_dog_enabled_ = is_watch_dog_enabled;
282 if (!is_watch_dog_enabled_) {
283 return;
284 }
285 shutting_down_ = false;
286 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
292 }
293 ~WatchDog() {
294 if (!is_watch_dog_enabled_) {
295 return;
296 }
297 const char* reason = "dex2oat watch dog thread shutdown";
298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
299 shutting_down_ = true;
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
302
Kenny Root51316382014-05-13 14:59:37 -0700303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700304
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
306 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
307 }
308
309 private:
310 static void* CallBack(void* arg) {
311 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
312 ::art::SetThreadName("dex2oat watch dog");
313 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700314 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700315 }
316
317 static void Message(char severity, const std::string& message) {
318 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
319 // cases.
320 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
321 kIsDebugBuild ? "d" : "",
322 severity,
323 getpid(),
324 GetTid(),
325 message.c_str());
326 }
327
Ian Rogers7223d442014-10-10 20:05:39 -0700328 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700329 Message('F', message);
330 exit(1);
331 }
332
333 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
335 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800336 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 timespec timeout_ts;
338 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
339 const char* reason = "dex2oat watch dog thread waiting";
340 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
341 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800342 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800344 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 } else if (rc != 0) {
346 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
347 strerror(errno)));
348 Fatal(message.c_str());
349 }
350 }
351 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
352 }
353
354 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
Mathieu Chartier13b9f432014-09-09 17:26:58 -0700355 // Debug builds are slower so they have larger timeouts.
356 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800357
Elliott Hughes956af0f2014-12-11 14:34:28 -0800358 // 6 minutes scaled by kSlowdownFactor.
359 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360
361 bool is_watch_dog_enabled_;
362 bool shutting_down_;
363 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
364 pthread_mutex_t mutex_;
365 pthread_cond_t cond_;
366 pthread_attr_t attr_;
367 pthread_t pthread_;
368};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700369
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800370static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100371 std::string::size_type colon = s.find(c);
372 if (colon == std::string::npos) {
373 Usage("Missing char %c in option %s\n", c, s.c_str());
374 }
375 // Add one to remove the char we were trimming until.
376 *parsed_value = s.substr(colon + 1);
377}
378
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800379static void ParseDouble(const std::string& option, char after_char, double min, double max,
380 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100381 std::string substring;
382 ParseStringAfterChar(option, after_char, &substring);
383 bool sane_val = true;
384 double value;
385 if (false) {
386 // TODO: this doesn't seem to work on the emulator. b/15114595
387 std::stringstream iss(substring);
388 iss >> value;
389 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
390 sane_val = iss.eof() && (value >= min) && (value <= max);
391 } else {
392 char* end = nullptr;
393 value = strtod(substring.c_str(), &end);
394 sane_val = *end == '\0' && value >= min && value <= max;
395 }
396 if (!sane_val) {
397 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
398 }
399 *parsed_value = value;
400}
401
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800402static constexpr size_t kMinDexFilesForSwap = 2;
403static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
404
405static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
406 if (is_image) {
407 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
408 return false;
409 }
410 if (dex_files.size() < kMinDexFilesForSwap) {
411 // If there are less dex files than the threshold, assume it's gonna be fine.
412 return false;
413 }
414 size_t dex_files_size = 0;
415 for (const auto* dex_file : dex_files) {
416 dex_files_size += dex_file->GetHeader().file_size_;
417 }
418 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
419}
420
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800421class Dex2Oat FINAL {
422 public:
423 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800424 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800425 instruction_set_(kRuntimeISA),
426 // Take the default set of instruction features from the build.
427 method_inliner_map_(),
428 runtime_(nullptr),
429 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
430 start_ns_(NanoTime()),
431 oat_fd_(-1),
432 zip_fd_(-1),
433 image_base_(0U),
434 image_classes_zip_filename_(nullptr),
435 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800436 compiled_classes_zip_filename_(nullptr),
437 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800438 image_(false),
439 is_host_(false),
440 dump_stats_(false),
441 dump_passes_(false),
442 dump_timing_(false),
443 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800444 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445 timings_(timings) {}
446
447 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800448 // Free opened dex files before deleting the runtime_, because ~DexFile
449 // uses MemMap, which is shut down by ~Runtime.
450 class_path_files_.clear();
451 opened_dex_files_.clear();
452
453 // Log completion time before deleting the runtime_, because this accesses
454 // the runtime.
455 LogCompletionTime();
456
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800457 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
458 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100459 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 }
461
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800462 // Parse the arguments from the command line. In case of an unrecognized option or impossible
463 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
464 // returns, arguments have been successfully parsed.
465 void ParseArgs(int argc, char** argv) {
466 original_argc = argc;
467 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700468
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700470
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800471 // Skip over argv[0].
472 argv++;
473 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700474
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800475 if (argc == 0) {
476 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700477 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800478
479 std::string oat_symbols;
480 std::string boot_image_filename;
481 const char* compiler_filter_string = nullptr;
482 bool compile_pic = false;
483 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
484 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
485 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
486 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
487 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
488
489 // Profile file to use
490 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
491
492 bool print_pass_options = false;
493 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
494 bool include_debug_symbols = kIsDebugBuild;
495 bool watch_dog_enabled = true;
496 bool generate_gdb_information = kIsDebugBuild;
497
498 std::string error_msg;
499
500 for (int i = 0; i < argc; i++) {
501 const StringPiece option(argv[i]);
502 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503 if (log_options) {
504 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
505 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 if (option.starts_with("--dex-file=")) {
507 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
508 } else if (option.starts_with("--dex-location=")) {
509 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
510 } else if (option.starts_with("--zip-fd=")) {
511 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
512 if (!ParseInt(zip_fd_str, &zip_fd_)) {
513 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
514 }
515 if (zip_fd_ < 0) {
516 Usage("--zip-fd passed a negative value %d", zip_fd_);
517 }
518 } else if (option.starts_with("--zip-location=")) {
519 zip_location_ = option.substr(strlen("--zip-location=")).data();
520 } else if (option.starts_with("--oat-file=")) {
521 oat_filename_ = option.substr(strlen("--oat-file=")).data();
522 } else if (option.starts_with("--oat-symbols=")) {
523 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
524 } else if (option.starts_with("--oat-fd=")) {
525 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
526 if (!ParseInt(oat_fd_str, &oat_fd_)) {
527 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
528 }
529 if (oat_fd_ < 0) {
530 Usage("--oat-fd passed a negative value %d", oat_fd_);
531 }
532 } else if (option == "--watch-dog") {
533 watch_dog_enabled = true;
534 } else if (option == "--no-watch-dog") {
535 watch_dog_enabled = false;
536 } else if (option == "--gen-gdb-info") {
537 generate_gdb_information = true;
538 // Debug symbols are needed for gdb information.
539 include_debug_symbols = true;
540 } else if (option == "--no-gen-gdb-info") {
541 generate_gdb_information = false;
542 } else if (option.starts_with("-j")) {
543 const char* thread_count_str = option.substr(strlen("-j")).data();
544 if (!ParseUint(thread_count_str, &thread_count_)) {
545 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
546 }
547 } else if (option.starts_with("--oat-location=")) {
548 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800549 } else if (option.starts_with("--image=")) {
550 image_filename_ = option.substr(strlen("--image=")).data();
551 } else if (option.starts_with("--image-classes=")) {
552 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
553 } else if (option.starts_with("--image-classes-zip=")) {
554 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800555 } else if (option.starts_with("--compiled-classes=")) {
556 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
557 } else if (option.starts_with("--compiled-classes-zip=")) {
558 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800559 } else if (option.starts_with("--base=")) {
560 const char* image_base_str = option.substr(strlen("--base=")).data();
561 char* end;
562 image_base_ = strtoul(image_base_str, &end, 16);
563 if (end == image_base_str || *end != '\0') {
564 Usage("Failed to parse hexadecimal value for option %s", option.data());
565 }
566 } else if (option.starts_with("--boot-image=")) {
567 boot_image_filename = option.substr(strlen("--boot-image=")).data();
568 } else if (option.starts_with("--android-root=")) {
569 android_root_ = option.substr(strlen("--android-root=")).data();
570 } else if (option.starts_with("--instruction-set=")) {
571 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
572 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800573 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800574 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
575 buf.get()[instruction_set_str.length()] = 0;
576 instruction_set_ = GetInstructionSetFromString(buf.get());
577 // arm actually means thumb2.
578 if (instruction_set_ == InstructionSet::kArm) {
579 instruction_set_ = InstructionSet::kThumb2;
580 }
581 } else if (option.starts_with("--instruction-set-variant=")) {
582 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
583 instruction_set_features_.reset(
584 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
585 if (instruction_set_features_.get() == nullptr) {
586 Usage("%s", error_msg.c_str());
587 }
588 } else if (option.starts_with("--instruction-set-features=")) {
589 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800590 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800591 instruction_set_features_.reset(
592 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
593 if (instruction_set_features_.get() == nullptr) {
594 Usage("Problem initializing default instruction set features variant: %s",
595 error_msg.c_str());
596 }
597 }
598 instruction_set_features_.reset(
599 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
600 if (instruction_set_features_.get() == nullptr) {
601 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800602 }
603 } else if (option.starts_with("--compiler-backend=")) {
604 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
605 if (backend_str == "Quick") {
606 compiler_kind_ = Compiler::kQuick;
607 } else if (backend_str == "Optimizing") {
608 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800609 } else {
610 Usage("Unknown compiler backend: %s", backend_str.data());
611 }
612 } else if (option.starts_with("--compiler-filter=")) {
613 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
614 } else if (option == "--compile-pic") {
615 compile_pic = true;
616 } else if (option.starts_with("--huge-method-max=")) {
617 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
618 if (!ParseInt(threshold, &huge_method_threshold)) {
619 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
620 }
621 if (huge_method_threshold < 0) {
622 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
623 }
624 } else if (option.starts_with("--large-method-max=")) {
625 const char* threshold = option.substr(strlen("--large-method-max=")).data();
626 if (!ParseInt(threshold, &large_method_threshold)) {
627 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
628 }
629 if (large_method_threshold < 0) {
630 Usage("--large-method-max passed a negative value %s", large_method_threshold);
631 }
632 } else if (option.starts_with("--small-method-max=")) {
633 const char* threshold = option.substr(strlen("--small-method-max=")).data();
634 if (!ParseInt(threshold, &small_method_threshold)) {
635 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
636 }
637 if (small_method_threshold < 0) {
638 Usage("--small-method-max passed a negative value %s", small_method_threshold);
639 }
640 } else if (option.starts_with("--tiny-method-max=")) {
641 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
642 if (!ParseInt(threshold, &tiny_method_threshold)) {
643 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
644 }
645 if (tiny_method_threshold < 0) {
646 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
647 }
648 } else if (option.starts_with("--num-dex-methods=")) {
649 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
650 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
651 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
652 }
653 if (num_dex_methods_threshold < 0) {
654 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
655 }
656 } else if (option == "--host") {
657 is_host_ = true;
658 } else if (option == "--runtime-arg") {
659 if (++i >= argc) {
660 Usage("Missing required argument for --runtime-arg");
661 }
662 if (log_options) {
663 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
664 }
665 runtime_args_.push_back(argv[i]);
666 } else if (option == "--dump-timing") {
667 dump_timing_ = true;
668 } else if (option == "--dump-passes") {
669 dump_passes_ = true;
670 } else if (option == "--dump-stats") {
671 dump_stats_ = true;
672 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
673 include_debug_symbols = true;
674 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
675 include_debug_symbols = false;
676 generate_gdb_information = false; // Depends on debug symbols, see above.
677 } else if (option.starts_with("--profile-file=")) {
678 profile_file_ = option.substr(strlen("--profile-file=")).data();
679 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
680 } else if (option == "--no-profile-file") {
681 // No profile
682 } else if (option.starts_with("--top-k-profile-threshold=")) {
683 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
684 } else if (option == "--print-pass-names") {
685 PassDriverMEOpts::PrintPassNames();
686 } else if (option.starts_with("--disable-passes=")) {
687 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
688 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
689 } else if (option.starts_with("--print-passes=")) {
690 std::string print_passes = option.substr(strlen("--print-passes=")).data();
691 PassDriverMEOpts::SetPrintPassList(print_passes);
692 } else if (option == "--print-all-passes") {
693 PassDriverMEOpts::SetPrintAllPasses();
694 } else if (option.starts_with("--dump-cfg-passes=")) {
695 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
696 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
697 } else if (option == "--print-pass-options") {
698 print_pass_options = true;
699 } else if (option.starts_with("--pass-options=")) {
700 std::string options = option.substr(strlen("--pass-options=")).data();
701 PassDriverMEOpts::SetOverriddenPassOptions(options);
702 } else if (option == "--include-patch-information") {
703 include_patch_information = true;
704 } else if (option == "--no-include-patch-information") {
705 include_patch_information = false;
706 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800707 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
708 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800709 gLogVerbosity.compiler = false;
710 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800711 } else if (option.starts_with("--dump-init-failures=")) {
712 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
713 init_failure_output_.reset(new std::ofstream(file_name));
714 if (init_failure_output_.get() == nullptr) {
715 LOG(ERROR) << "Failed to allocate ofstream";
716 } else if (init_failure_output_->fail()) {
717 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
718 << "failures.";
719 init_failure_output_.reset();
720 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800721 } else if (option.starts_with("--swap-file=")) {
722 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
723 } else if (option.starts_with("--swap-fd=")) {
724 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
725 if (!ParseInt(swap_fd_str, &swap_fd_)) {
726 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
727 }
728 if (swap_fd_ < 0) {
729 Usage("--swap-fd passed a negative value %d", swap_fd_);
730 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800731 } else {
732 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 }
735
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000736 if (compiler_kind_ == Compiler::kOptimizing) {
737 // Optimizing only supports PIC mode.
738 compile_pic = true;
739 }
740
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800741 if (oat_filename_.empty() && oat_fd_ == -1) {
742 Usage("Output must be supplied with either --oat-file or --oat-fd");
743 }
744
745 if (!oat_filename_.empty() && oat_fd_ != -1) {
746 Usage("--oat-file should not be used with --oat-fd");
747 }
748
749 if (!oat_symbols.empty() && oat_fd_ != -1) {
750 Usage("--oat-symbols should not be used with --oat-fd");
751 }
752
753 if (!oat_symbols.empty() && is_host_) {
754 Usage("--oat-symbols should not be used with --host");
755 }
756
757 if (oat_fd_ != -1 && !image_filename_.empty()) {
758 Usage("--oat-fd should not be used with --image");
759 }
760
761 if (android_root_.empty()) {
762 const char* android_root_env_var = getenv("ANDROID_ROOT");
763 if (android_root_env_var == nullptr) {
764 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700765 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800766 android_root_ += android_root_env_var;
767 }
768
769 image_ = (!image_filename_.empty());
770 if (!image_ && boot_image_filename.empty()) {
771 boot_image_filename += android_root_;
772 boot_image_filename += "/framework/boot.art";
773 }
774 if (!boot_image_filename.empty()) {
775 boot_image_option_ += "-Ximage:";
776 boot_image_option_ += boot_image_filename;
777 }
778
779 if (image_classes_filename_ != nullptr && !image_) {
780 Usage("--image-classes should only be used with --image");
781 }
782
783 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
784 Usage("--image-classes should not be used with --boot-image");
785 }
786
787 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
788 Usage("--image-classes-zip should be used with --image-classes");
789 }
790
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800791 if (compiled_classes_filename_ != nullptr && !image_) {
792 Usage("--compiled-classes should only be used with --image");
793 }
794
795 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
796 Usage("--compiled-classes should not be used with --boot-image");
797 }
798
799 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
800 Usage("--compiled-classes-zip should be used with --compiled-classes");
801 }
802
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800803 if (dex_filenames_.empty() && zip_fd_ == -1) {
804 Usage("Input must be supplied with either --dex-file or --zip-fd");
805 }
806
807 if (!dex_filenames_.empty() && zip_fd_ != -1) {
808 Usage("--dex-file should not be used with --zip-fd");
809 }
810
811 if (!dex_filenames_.empty() && !zip_location_.empty()) {
812 Usage("--dex-file should not be used with --zip-location");
813 }
814
815 if (dex_locations_.empty()) {
816 for (const char* dex_file_name : dex_filenames_) {
817 dex_locations_.push_back(dex_file_name);
818 }
819 } else if (dex_locations_.size() != dex_filenames_.size()) {
820 Usage("--dex-location arguments do not match --dex-file arguments");
821 }
822
823 if (zip_fd_ != -1 && zip_location_.empty()) {
824 Usage("--zip-location should be supplied with --zip-fd");
825 }
826
827 if (boot_image_option_.empty()) {
828 if (image_base_ == 0) {
829 Usage("Non-zero --base not specified");
830 }
831 }
832
833 oat_stripped_ = oat_filename_;
834 if (!oat_symbols.empty()) {
835 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800837 oat_unstripped_ = oat_filename_;
838 }
839
840 // If no instruction set feature was given, use the default one for the target
841 // instruction set.
842 if (instruction_set_features_.get() == nullptr) {
843 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800844 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
845 if (instruction_set_features_.get() == nullptr) {
846 Usage("Problem initializing default instruction set features variant: %s",
847 error_msg.c_str());
848 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800849 }
850
851 if (instruction_set_ == kRuntimeISA) {
852 std::unique_ptr<const InstructionSetFeatures> runtime_features(
853 InstructionSetFeatures::FromCppDefines());
854 if (!instruction_set_features_->Equals(runtime_features.get())) {
855 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
856 << *instruction_set_features_ << ") and those of dex2oat executable ("
857 << *runtime_features <<") for the command line:\n"
858 << CommandLine();
859 }
860 }
861
862 if (compiler_filter_string == nullptr) {
863 if (instruction_set_ == kMips64) {
864 // TODO: fix compiler for Mips64.
865 compiler_filter_string = "interpret-only";
866 } else if (image_) {
867 compiler_filter_string = "speed";
868 } else {
869 // TODO: Migrate SMALL mode to command line option.
870 #if ART_SMALL_MODE
871 compiler_filter_string = "interpret-only";
872 #else
873 compiler_filter_string = "speed";
874 #endif
875 }
876 }
877 CHECK(compiler_filter_string != nullptr);
878 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
879 if (strcmp(compiler_filter_string, "verify-none") == 0) {
880 compiler_filter = CompilerOptions::kVerifyNone;
881 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
882 compiler_filter = CompilerOptions::kInterpretOnly;
883 } else if (strcmp(compiler_filter_string, "space") == 0) {
884 compiler_filter = CompilerOptions::kSpace;
885 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
886 compiler_filter = CompilerOptions::kBalanced;
887 } else if (strcmp(compiler_filter_string, "speed") == 0) {
888 compiler_filter = CompilerOptions::kSpeed;
889 } else if (strcmp(compiler_filter_string, "everything") == 0) {
890 compiler_filter = CompilerOptions::kEverything;
891 } else if (strcmp(compiler_filter_string, "time") == 0) {
892 compiler_filter = CompilerOptions::kTime;
893 } else {
894 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
895 }
896
897 // Checks are all explicit until we know the architecture.
898 bool implicit_null_checks = false;
899 bool implicit_so_checks = false;
900 bool implicit_suspend_checks = false;
901 // Set the compilation target's implicit checks options.
902 switch (instruction_set_) {
903 case kArm:
904 case kThumb2:
905 case kArm64:
906 case kX86:
907 case kX86_64:
908 implicit_null_checks = true;
909 implicit_so_checks = true;
910 break;
911
912 default:
913 // Defaults are correct.
914 break;
915 }
916
917 if (print_pass_options) {
918 PassDriverMEOpts::PrintPassOptions();
919 }
920
921 compiler_options_.reset(new CompilerOptions(compiler_filter,
922 huge_method_threshold,
923 large_method_threshold,
924 small_method_threshold,
925 tiny_method_threshold,
926 num_dex_methods_threshold,
927 generate_gdb_information,
928 include_patch_information,
929 top_k_profile_threshold,
930 include_debug_symbols,
931 implicit_null_checks,
932 implicit_so_checks,
933 implicit_suspend_checks,
934 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800935 verbose_methods_.empty() ?
936 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800937 &verbose_methods_,
938 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800939
940 // Done with usage checks, enable watchdog if requested
941 if (watch_dog_enabled) {
942 watchdog_.reset(new WatchDog(true));
943 }
944
945 // Fill some values into the key-value store for the oat header.
946 key_value_store_.reset(new SafeMap<std::string, std::string>());
947
948 // Insert some compiler things.
949 {
950 std::ostringstream oss;
951 for (int i = 0; i < argc; ++i) {
952 if (i > 0) {
953 oss << ' ';
954 }
955 oss << argv[i];
956 }
957 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
958 oss.str(""); // Reset.
959 oss << kRuntimeISA;
960 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
961 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
962 }
963 }
964
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800965 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
966 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800967 bool OpenFile() {
968 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
969 if (create_file) {
970 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
971 if (oat_location_.empty()) {
972 oat_location_ = oat_filename_;
973 }
974 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800975 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800976 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800977 if (oat_file_->SetLength(0) != 0) {
978 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
979 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800980 }
981 if (oat_file_.get() == nullptr) {
982 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
983 return false;
984 }
985 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
986 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800987 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800988 return false;
989 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800990
991 // Swap file handling.
992 //
993 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
994 // that we can use for swap.
995 //
996 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
997 // will immediately unlink to satisfy the swap fd assumption.
998 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
999 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1000 if (swap_file.get() == nullptr) {
1001 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1002 return false;
1003 }
1004 swap_fd_ = swap_file->Fd();
1005 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1006 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1007 // released immediately.
1008 unlink(swap_file_name_.c_str());
1009 }
1010
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001011 return true;
1012 }
1013
Andreas Gampea650e702014-12-03 14:28:02 -08001014 void EraseOatFile() {
1015 DCHECK(oat_file_.get() != nullptr);
1016 oat_file_->Erase();
1017 oat_file_.reset();
1018 }
1019
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001020 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1021 // boot class path.
1022 bool Setup() {
1023 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1024 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001025 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1026 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001027 std::string boot_class_path = "-Xbootclasspath:";
1028 boot_class_path += Join(dex_filenames_, ':');
1029 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1030 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1031 boot_class_path_locations += Join(dex_locations_, ':');
1032 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001033 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001034 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001035 }
1036 for (size_t i = 0; i < runtime_args_.size(); i++) {
1037 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001039
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001040 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1041 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1042 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1043 runtime_options.push_back(
1044 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1045
1046 if (!CreateRuntime(runtime_options)) {
1047 return false;
1048 }
1049
1050 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1051 // Runtime::Start, give it away now so that we don't starve GC.
1052 Thread* self = Thread::Current();
1053 self->TransitionFromRunnableToSuspended(kNative);
1054 // If we're doing the image, override the compiler filter to force full compilation. Must be
1055 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1056 // compilation of class initializers.
1057 // Whilst we're in native take the opportunity to initialize well known classes.
1058 WellKnownClasses::Init(self->GetJniEnv());
1059
1060 // If --image-classes was specified, calculate the full list of classes to include in the image
1061 if (image_classes_filename_ != nullptr) {
1062 std::string error_msg;
1063 if (image_classes_zip_filename_ != nullptr) {
1064 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1065 image_classes_filename_,
1066 &error_msg));
1067 } else {
1068 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1069 }
1070 if (image_classes_.get() == nullptr) {
1071 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1072 "': " << error_msg;
1073 return false;
1074 }
1075 } else if (image_) {
1076 image_classes_.reset(new std::set<std::string>);
1077 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001078 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1079 // image.
1080 if (compiled_classes_filename_ != nullptr) {
1081 std::string error_msg;
1082 if (compiled_classes_zip_filename_ != nullptr) {
1083 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1084 compiled_classes_filename_,
1085 &error_msg));
1086 } else {
1087 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1088 }
1089 if (compiled_classes_.get() == nullptr) {
1090 LOG(ERROR) << "Failed to create list of compiled classes from '"
1091 << compiled_classes_filename_ << "': " << error_msg;
1092 return false;
1093 }
1094 } else if (image_) {
1095 compiled_classes_.reset(nullptr); // By default compile everything.
1096 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001097
1098 if (boot_image_option_.empty()) {
1099 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1100 } else {
1101 if (dex_filenames_.empty()) {
1102 ATRACE_BEGIN("Opening zip archive from file descriptor");
1103 std::string error_msg;
1104 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1105 zip_location_.c_str(),
1106 &error_msg));
1107 if (zip_archive.get() == nullptr) {
1108 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1109 << error_msg;
1110 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001111 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001112 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001113 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1114 << "': " << error_msg;
1115 return false;
1116 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001117 for (auto& dex_file : opened_dex_files_) {
1118 dex_files_.push_back(dex_file.get());
1119 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001120 ATRACE_END();
1121 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001122 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001123 if (failure_count > 0) {
1124 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1125 return false;
1126 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001127 for (auto& dex_file : opened_dex_files_) {
1128 dex_files_.push_back(dex_file.get());
1129 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 }
1131
1132 constexpr bool kSaveDexInput = false;
1133 if (kSaveDexInput) {
1134 for (size_t i = 0; i < dex_files_.size(); ++i) {
1135 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001136 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1137 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001138 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1139 if (tmp_file.get() == nullptr) {
1140 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1141 << ". Try: adb shell chmod 777 /data/local/tmp";
1142 continue;
1143 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001144 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1145 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1146 UNUSED(tmp_file->Flush());
1147 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001148 LOG(INFO) << "Wrote input to " << tmp_file_name;
1149 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001150 }
1151 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001152 // Ensure opened dex files are writable for dex-to-dex transformations.
1153 for (const auto& dex_file : dex_files_) {
1154 if (!dex_file->EnableWrite()) {
1155 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001156 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001157 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001158
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001159 // If we use a swap file, ensure we are above the threshold to make it necessary.
1160 if (swap_fd_ != -1) {
1161 if (!UseSwap(image_, dex_files_)) {
1162 close(swap_fd_);
1163 swap_fd_ = -1;
1164 LOG(INFO) << "Decided to run without swap.";
1165 } else {
1166 LOG(INFO) << "Accepted running with swap.";
1167 }
1168 }
1169 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1170
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001171 /*
1172 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1173 * Don't bother to check if we're doing the image.
1174 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001175 if (!image_ &&
1176 compiler_options_->IsCompilationEnabled() &&
1177 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178 size_t num_methods = 0;
1179 for (size_t i = 0; i != dex_files_.size(); ++i) {
1180 const DexFile* dex_file = dex_files_[i];
1181 CHECK(dex_file != nullptr);
1182 num_methods += dex_file->NumMethodIds();
1183 }
1184 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1185 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1186 VLOG(compiler) << "Below method threshold, compiling anyways";
1187 }
1188 }
1189
1190 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001191 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001192
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001193 // Create and invoke the compiler driver. This will compile all the dex files.
1194 void Compile() {
1195 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1196 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001197
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001198 // Handle and ClassLoader creation needs to come after Runtime::Create
1199 jobject class_loader = nullptr;
1200 Thread* self = Thread::Current();
1201 if (!boot_image_option_.empty()) {
1202 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001203 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001204 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001205 std::vector<const DexFile*> class_path_files(dex_files_);
1206 for (auto& class_path_file : class_path_files_) {
1207 class_path_files.push_back(class_path_file.get());
1208 }
1209
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001210 for (size_t i = 0; i < class_path_files.size(); i++) {
1211 class_linker->RegisterDexFile(*class_path_files[i]);
1212 }
1213 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1214 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1215 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1216 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1217 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1218 }
1219
1220 driver_.reset(new CompilerDriver(compiler_options_.get(),
1221 verification_results_.get(),
1222 &method_inliner_map_,
1223 compiler_kind_,
1224 instruction_set_,
1225 instruction_set_features_.get(),
1226 image_,
1227 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001228 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001229 thread_count_,
1230 dump_stats_,
1231 dump_passes_,
1232 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001233 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001234 profile_file_));
1235
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001236 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001237 }
1238
Brian Carlstrom7940e442013-07-12 13:46:57 -07001239 // Notes on the interleaving of creating the image and oat file to
1240 // ensure the references between the two are correct.
1241 //
1242 // Currently we have a memory layout that looks something like this:
1243 //
1244 // +--------------+
1245 // | image |
1246 // +--------------+
1247 // | boot oat |
1248 // +--------------+
1249 // | alloc spaces |
1250 // +--------------+
1251 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001252 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001253 //
1254 // 1. The image is expected to be loaded at an absolute address and
1255 // contains Objects with absolute pointers within the image.
1256 //
1257 // 2. There are absolute pointers from Methods in the image to their
1258 // code in the oat.
1259 //
1260 // 3. There are absolute pointers from the code in the oat to Methods
1261 // in the image.
1262 //
1263 // 4. There are absolute pointers from code in the oat to other code
1264 // in the oat.
1265 //
1266 // To get this all correct, we go through several steps.
1267 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001268 // 1. We prepare offsets for all data in the oat file and calculate
1269 // the oat data size and code size. During this stage, we also set
1270 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001271 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001272 // 2. We prepare offsets for the objects in the image and calculate
1273 // the image size.
1274 //
1275 // 3. We create the oat file. Originally this was just our own proprietary
1276 // file but now it is contained within an ELF dynamic object (aka an .so
1277 // file). Since we know the image size and oat data size and code size we
1278 // can prepare the ELF headers and we then know the ELF memory segment
1279 // layout and we can now resolve all references. The compiler provides
1280 // LinkerPatch information in each CompiledMethod and we resolve these,
1281 // using the layout information and image object locations provided by
1282 // image writer, as we're writing the method code.
1283 //
1284 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001285 // will be loaded after itself. Originally when oat file was simply
1286 // memory mapped so we could predict where its contents were based
1287 // on the file size. Now that it is an ELF file, we need to inspect
1288 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001289 // where the oat header is located within.
1290 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001291 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001292 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001293 // load the .so at the desired location at runtime by offsetting the
1294 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001295 // TODO: Do this in step 3. We already know the layout there.
1296 //
1297 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1298 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001299
1300
1301 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1302 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001303 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1304 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001305 bool CreateOatFile() {
1306 CHECK(key_value_store_.get() != nullptr);
1307
1308 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1309
1310 std::unique_ptr<OatWriter> oat_writer;
1311 {
1312 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1313 std::string image_file_location;
1314 uint32_t image_file_location_oat_checksum = 0;
1315 uintptr_t image_file_location_oat_data_begin = 0;
1316 int32_t image_patch_delta = 0;
1317 if (image_) {
1318 PrepareImageWriter(image_base_);
1319 } else {
1320 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1321 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1322 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1323 image_file_location_oat_data_begin =
1324 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1325 image_file_location = image_space->GetImageFilename();
1326 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1327 }
1328
1329 if (!image_file_location.empty()) {
1330 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1331 }
1332
1333 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1334 image_file_location_oat_data_begin,
1335 image_patch_delta,
1336 driver_.get(),
1337 image_writer_.get(),
1338 timings_,
1339 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001340 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001341
1342 if (image_) {
1343 // The OatWriter constructor has already updated offsets in methods and we need to
1344 // prepare method offsets in the image address space for direct method patching.
1345 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1346 if (!image_writer_->PrepareImageAddressSpace()) {
1347 LOG(ERROR) << "Failed to prepare image address space.";
1348 return false;
1349 }
1350 }
1351
1352 {
1353 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1354 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1355 oat_file_.get())) {
1356 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1357 return false;
1358 }
1359 }
1360
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001361 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1362 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001363 }
1364
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 // If we are compiling an image, invoke the image creation routine. Else just skip.
1366 bool HandleImage() {
1367 if (image_) {
1368 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1369 if (!CreateImageFile()) {
1370 return false;
1371 }
1372 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001373 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001374 return true;
1375 }
1376
Andreas Gampe10e477d2014-11-19 12:57:42 -08001377 // Create a copy from unstripped to stripped.
1378 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 // If we don't want to strip in place, copy from unstripped location to stripped location.
1380 // We need to strip after image creation because FixupElf needs to use .strtab.
1381 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001382 // If the oat file is still open, flush it.
1383 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1384 if (!FlushCloseOatFile()) {
1385 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001386 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001387 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001388
1389 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001390 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1391 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1392 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001393 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001394 while (true) {
1395 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1396 if (bytes_read <= 0) {
1397 break;
1398 }
1399 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1400 CHECK(write_ok);
1401 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001402 if (out->FlushCloseOrErase() != 0) {
1403 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1404 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001405 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001407 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001408 return true;
1409 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001410
Andreas Gampe10e477d2014-11-19 12:57:42 -08001411 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001412 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001413 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1414 if (oat_file_->Flush() != 0) {
1415 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1416 << oat_filename_;
1417 oat_file_->Erase();
1418 return false;
1419 }
1420 }
1421 return true;
1422 }
1423
1424 bool FlushCloseOatFile() {
1425 if (oat_file_.get() != nullptr) {
1426 std::unique_ptr<File> tmp(oat_file_.release());
1427 if (tmp->FlushCloseOrErase() != 0) {
1428 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1429 << oat_filename_;
1430 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001431 }
1432 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001433 return true;
1434 }
1435
1436 void DumpTiming() {
1437 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1438 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1439 }
1440 if (dump_passes_) {
1441 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1442 }
1443 }
1444
1445 CompilerOptions* GetCompilerOptions() const {
1446 return compiler_options_.get();
1447 }
1448
Andreas Gampe10e477d2014-11-19 12:57:42 -08001449 bool IsImage() const {
1450 return image_;
1451 }
1452
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001453 bool IsHost() const {
1454 return is_host_;
1455 }
1456
1457 private:
1458 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1459 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001460 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1461 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001462 size_t failure_count = 0;
1463 for (size_t i = 0; i < dex_filenames.size(); i++) {
1464 const char* dex_filename = dex_filenames[i];
1465 const char* dex_location = dex_locations[i];
1466 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1467 std::string error_msg;
1468 if (!OS::FileExists(dex_filename)) {
1469 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1470 continue;
1471 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001472 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001473 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1474 ++failure_count;
1475 }
1476 ATRACE_END();
1477 }
1478 return failure_count;
1479 }
1480
1481 // Returns true if dex_files has a dex with the named location.
1482 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1483 const std::string& location) {
1484 for (size_t i = 0; i < dex_files.size(); ++i) {
1485 if (dex_files[i]->GetLocation() == location) {
1486 return true;
1487 }
1488 }
1489 return false;
1490 }
1491
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001492 // Appends to opened_dex_files any elements of class_path that dex_files
1493 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001495 std::vector<const DexFile*> dex_files,
1496 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1497 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001498 std::vector<std::string> parsed;
1499 Split(class_path, ':', &parsed);
1500 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1501 ScopedObjectAccess soa(Thread::Current());
1502 for (size_t i = 0; i < parsed.size(); ++i) {
1503 if (DexFilesContains(dex_files, parsed[i])) {
1504 continue;
1505 }
1506 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001507 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001508 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1509 }
1510 }
1511 }
1512
1513 // Create a runtime necessary for compilation.
1514 bool CreateRuntime(const RuntimeOptions& runtime_options)
1515 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1516 if (!Runtime::Create(runtime_options, false)) {
1517 LOG(ERROR) << "Failed to create runtime";
1518 return false;
1519 }
1520 Runtime* runtime = Runtime::Current();
1521 runtime->SetInstructionSet(instruction_set_);
1522 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1523 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1524 if (!runtime->HasCalleeSaveMethod(type)) {
1525 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1526 }
1527 }
1528 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1529 runtime->GetClassLinker()->RunRootClinits();
1530 runtime_ = runtime;
1531 return true;
1532 }
1533
1534 void PrepareImageWriter(uintptr_t image_base) {
1535 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1536 }
1537
1538 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1539 bool CreateImageFile()
1540 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1541 CHECK(image_writer_ != nullptr);
1542 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1543 LOG(ERROR) << "Failed to create image file " << image_filename_;
1544 return false;
1545 }
1546 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1547
1548 // Destroy ImageWriter before doing FixupElf.
1549 image_writer_.reset();
1550
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001551 // Do not fix up the ELF file if we are --compile-pic
1552 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001553 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1554 if (oat_file.get() == nullptr) {
1555 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1556 return false;
1557 }
1558
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001559 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001560 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001561 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1562 return false;
1563 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001564
1565 if (oat_file->FlushCloseOrErase()) {
1566 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1567 return false;
1568 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001569 }
1570
1571 return true;
1572 }
1573
1574 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1575 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1576 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1577 std::ifstream::in));
1578 if (image_classes_file.get() == nullptr) {
1579 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1580 return nullptr;
1581 }
1582 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1583 image_classes_file->close();
1584 return result.release();
1585 }
1586
1587 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1588 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1589 while (image_classes_stream.good()) {
1590 std::string dot;
1591 std::getline(image_classes_stream, dot);
1592 if (StartsWith(dot, "#") || dot.empty()) {
1593 continue;
1594 }
1595 std::string descriptor(DotToDescriptor(dot.c_str()));
1596 image_classes->insert(descriptor);
1597 }
1598 return image_classes.release();
1599 }
1600
1601 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1602 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1603 const char* image_classes_filename,
1604 std::string* error_msg) {
1605 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1606 if (zip_archive.get() == nullptr) {
1607 return nullptr;
1608 }
1609 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1610 if (zip_entry.get() == nullptr) {
1611 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1612 zip_filename, error_msg->c_str());
1613 return nullptr;
1614 }
1615 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1616 image_classes_filename,
1617 error_msg));
1618 if (image_classes_file.get() == nullptr) {
1619 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1620 zip_filename, error_msg->c_str());
1621 return nullptr;
1622 }
1623 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1624 image_classes_file->Size());
1625 std::istringstream image_classes_stream(image_classes_string);
1626 return ReadImageClasses(image_classes_stream);
1627 }
1628
Mathieu Chartier49285c52014-12-02 15:43:48 -08001629 void LogCompletionTime() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001630 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001631 << " (threads: " << thread_count_ << ") "
1632 << driver_->GetMemoryUsageString();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 }
1634
1635 std::unique_ptr<CompilerOptions> compiler_options_;
1636 Compiler::Kind compiler_kind_;
1637
1638 InstructionSet instruction_set_;
1639 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1640
1641 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1642
1643 std::unique_ptr<VerificationResults> verification_results_;
1644 DexFileToMethodInlinerMap method_inliner_map_;
1645 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1646
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001647 // Ownership for the class path files.
1648 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1649
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001650 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1651 // in an orderly fashion. The destructor takes care of deleting this.
1652 Runtime* runtime_;
1653
1654 size_t thread_count_;
1655 uint64_t start_ns_;
1656 std::unique_ptr<WatchDog> watchdog_;
1657 std::unique_ptr<File> oat_file_;
1658 std::string oat_stripped_;
1659 std::string oat_unstripped_;
1660 std::string oat_location_;
1661 std::string oat_filename_;
1662 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001663 std::vector<const char*> dex_filenames_;
1664 std::vector<const char*> dex_locations_;
1665 int zip_fd_;
1666 std::string zip_location_;
1667 std::string boot_image_option_;
1668 std::vector<const char*> runtime_args_;
1669 std::string image_filename_;
1670 uintptr_t image_base_;
1671 const char* image_classes_zip_filename_;
1672 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001673 const char* compiled_classes_zip_filename_;
1674 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001675 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001676 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001677 bool image_;
1678 std::unique_ptr<ImageWriter> image_writer_;
1679 bool is_host_;
1680 std::string android_root_;
1681 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001682 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001683 std::unique_ptr<CompilerDriver> driver_;
1684 std::vector<std::string> verbose_methods_;
1685 bool dump_stats_;
1686 bool dump_passes_;
1687 bool dump_timing_;
1688 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001689 std::string swap_file_name_;
1690 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001691 std::string profile_file_; // Profile file to use
1692 TimingLogger* timings_;
1693 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001694 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695
1696 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1697};
1698
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001699const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1700
1701static void b13564922() {
1702#if defined(__linux__) && defined(__arm__)
1703 int major, minor;
1704 struct utsname uts;
1705 if (uname(&uts) != -1 &&
1706 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1707 ((major < 3) || ((major == 3) && (minor < 4)))) {
1708 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1709 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1710 int old_personality = personality(0xffffffff);
1711 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1712 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1713 if (new_personality == -1) {
1714 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1715 }
1716 }
1717 }
1718#endif
1719}
1720
Andreas Gampe10e477d2014-11-19 12:57:42 -08001721static int CompileImage(Dex2Oat& dex2oat) {
1722 dex2oat.Compile();
1723
1724 // Create the boot.oat.
1725 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001726 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001727 return EXIT_FAILURE;
1728 }
1729
1730 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1731 // re-opened from the unstripped name.
1732 if (!dex2oat.FlushCloseOatFile()) {
1733 return EXIT_FAILURE;
1734 }
1735
1736 // Creates the boot.art and patches the boot.oat.
1737 if (!dex2oat.HandleImage()) {
1738 return EXIT_FAILURE;
1739 }
1740
1741 // When given --host, finish early without stripping.
1742 if (dex2oat.IsHost()) {
1743 dex2oat.DumpTiming();
1744 return EXIT_SUCCESS;
1745 }
1746
1747 // Copy unstripped to stripped location, if necessary.
1748 if (!dex2oat.CopyUnstrippedToStripped()) {
1749 return EXIT_FAILURE;
1750 }
1751
Andreas Gampe10e477d2014-11-19 12:57:42 -08001752 // FlushClose again, as stripping might have re-opened the oat file.
1753 if (!dex2oat.FlushCloseOatFile()) {
1754 return EXIT_FAILURE;
1755 }
1756
1757 dex2oat.DumpTiming();
1758 return EXIT_SUCCESS;
1759}
1760
1761static int CompileApp(Dex2Oat& dex2oat) {
1762 dex2oat.Compile();
1763
1764 // Create the app oat.
1765 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001766 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001767 return EXIT_FAILURE;
1768 }
1769
1770 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1771 // which we would lose.
1772 if (!dex2oat.FlushOatFile()) {
1773 return EXIT_FAILURE;
1774 }
1775
1776 // When given --host, finish early without stripping.
1777 if (dex2oat.IsHost()) {
1778 if (!dex2oat.FlushCloseOatFile()) {
1779 return EXIT_FAILURE;
1780 }
1781
1782 dex2oat.DumpTiming();
1783 return EXIT_SUCCESS;
1784 }
1785
1786 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1787 // unstripped version. If this is given, we expect to be able to open writable files by name.
1788 if (!dex2oat.CopyUnstrippedToStripped()) {
1789 return EXIT_FAILURE;
1790 }
1791
Andreas Gampe10e477d2014-11-19 12:57:42 -08001792 // Flush and close the file.
1793 if (!dex2oat.FlushCloseOatFile()) {
1794 return EXIT_FAILURE;
1795 }
1796
1797 dex2oat.DumpTiming();
1798 return EXIT_SUCCESS;
1799}
1800
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001801static int dex2oat(int argc, char** argv) {
1802 b13564922();
1803
1804 TimingLogger timings("compiler", false, false);
1805
1806 Dex2Oat dex2oat(&timings);
1807
1808 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1809 dex2oat.ParseArgs(argc, argv);
1810
1811 // Check early that the result of compilation can be written
1812 if (!dex2oat.OpenFile()) {
1813 return EXIT_FAILURE;
1814 }
1815
1816 LOG(INFO) << CommandLine();
1817
1818 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001819 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001820 return EXIT_FAILURE;
1821 }
1822
Andreas Gampe10e477d2014-11-19 12:57:42 -08001823 if (dex2oat.IsImage()) {
1824 return CompileImage(dex2oat);
1825 } else {
1826 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001827 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001828}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001829} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001830
1831int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001832 int result = art::dex2oat(argc, argv);
1833 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1834 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1835 // should not destruct the runtime in this case.
1836 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1837 exit(result);
1838 }
1839 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840}