blob: fe3a978c4a05525f09357ce2863e0a16815046ef [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"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080037#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "base/stl_util.h"
40#include "base/stringpiece.h"
41#include "base/timing_logger.h"
42#include "base/unix_file/fd_file.h"
43#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000044#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000045#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070047#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000048#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "dex/quick_compiler_callbacks.h"
50#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080052#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080053#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070054#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/image_space.h"
56#include "gc/space/space-inl.h"
57#include "image_writer.h"
58#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070059#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/class-inl.h"
61#include "mirror/class_loader.h"
62#include "mirror/object-inl.h"
63#include "mirror/object_array-inl.h"
64#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "os.h"
66#include "runtime.h"
67#include "ScopedLocalRef.h"
68#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070069#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "vector_output_stream.h"
71#include "well_known_classes.h"
72#include "zip_archive.h"
73
74namespace art {
75
Brian Carlstrom6449c622014-02-10 23:48:36 -080076static int original_argc;
77static char** original_argv;
78
79static std::string CommandLine() {
80 std::vector<std::string> command;
81 for (int i = 0; i < original_argc; ++i) {
82 command.push_back(original_argv[i]);
83 }
84 return Join(command, ' ');
85}
86
Brian Carlstrom7940e442013-07-12 13:46:57 -070087static void UsageErrorV(const char* fmt, va_list ap) {
88 std::string error;
89 StringAppendV(&error, fmt, ap);
90 LOG(ERROR) << error;
91}
92
93static void UsageError(const char* fmt, ...) {
94 va_list ap;
95 va_start(ap, fmt);
96 UsageErrorV(fmt, ap);
97 va_end(ap);
98}
99
Ian Rogers7223d442014-10-10 20:05:39 -0700100[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101 va_list ap;
102 va_start(ap, fmt);
103 UsageErrorV(fmt, ap);
104 va_end(ap);
105
Brian Carlstrom6449c622014-02-10 23:48:36 -0800106 UsageError("Command: %s", CommandLine().c_str());
107
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108 UsageError("Usage: dex2oat [options]...");
109 UsageError("");
110 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
111 UsageError(" Example: --dex-file=/system/framework/core.jar");
112 UsageError("");
113 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
114 UsageError(" containing a classes.dex file to compile.");
115 UsageError(" Example: --zip-fd=5");
116 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700117 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
118 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700119 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
120 UsageError("");
121 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
122 UsageError(" Example: --oat-file=/system/framework/boot.oat");
123 UsageError("");
124 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900125 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700126 UsageError("");
127 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
128 UsageError(" to the file descriptor specified by --oat-fd.");
129 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
130 UsageError("");
131 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
132 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
133 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700134 UsageError(" --image=<file.art>: specifies the output image filename.");
135 UsageError(" Example: --image=/system/framework/boot.art");
136 UsageError("");
137 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
138 UsageError(" Example: --image=frameworks/base/preloaded-classes");
139 UsageError("");
140 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
141 UsageError(" Example: --base=0x50000000");
142 UsageError("");
143 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
144 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000145 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700146 UsageError("");
147 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
148 UsageError(" Example: --android-root=out/host/linux-x86");
149 UsageError(" Default: $ANDROID_ROOT");
150 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800151 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700152 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700153 UsageError(" Example: --instruction-set=x86");
154 UsageError(" Default: arm");
155 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700156 UsageError(" --instruction-set-features=...,: Specify instruction set features");
157 UsageError(" Example: --instruction-set-features=div");
158 UsageError(" Default: default");
159 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700160 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
161 UsageError(" Default: disabled");
162 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800163 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800165 UsageError(" Example: --compiler-backend=Optimizing");
166 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000167 UsageError(" Default: Optimizing");
168 } else {
169 UsageError(" Default: Quick");
170 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100172 UsageError(" --compiler-filter="
173 "(verify-none"
174 "|interpret-only"
175 "|space"
176 "|balanced"
177 "|speed"
178 "|everything"
179 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700180 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800181 UsageError(" Example: --compiler-filter=everything");
182#if ART_SMALL_MODE
183 UsageError(" Default: interpret-only");
184#else
185 UsageError(" Default: speed");
186#endif
187 UsageError("");
188 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
189 UsageError(" method for compiler filter tuning.");
190 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
191 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
192 UsageError("");
193 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
194 UsageError(" method for compiler filter tuning.");
195 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
196 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
197 UsageError("");
198 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
199 UsageError(" method for compiler filter tuning.");
200 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
201 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
202 UsageError("");
203 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
204 UsageError(" method for compiler filter tuning.");
205 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
206 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
207 UsageError("");
208 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
209 UsageError(" method for compiler filter tuning.");
210 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
211 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
212 UsageError("");
213 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
214 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700215 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
216 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800217 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
218 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
219 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700220 UsageError(" --dump-timing: display a breakdown of where time was spent");
221 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700222 UsageError(" --include-patch-information: Include patching information so the generated code");
223 UsageError(" can have its base address moved without full recompilation.");
224 UsageError("");
225 UsageError(" --no-include-patch-information: Do not include patching information.");
226 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700227 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
228 UsageError("");
229 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
230 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
232 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
233 UsageError(" Use a separate --runtime-arg switch for each argument.");
234 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700235 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000236 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700238 UsageError(" --print-pass-names: print a list of pass names");
239 UsageError("");
240 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
241 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
242 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700243 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
244 "with the setting.");
245 UsageError(" Will print default if no overridden setting exists.");
246 UsageError("");
247 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
248 "Pass2Name:Pass2OptionName:Pass2Option#");
249 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
250 UsageError(" Separator used between options is a comma.");
251 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800252 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
253 UsageError(" Example: --swap-file=/data/tmp/swap.001");
254 UsageError("");
255 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
256 UsageError(" Example: --swap-fd=10");
257 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700258 std::cerr << "See log for usage error information\n";
259 exit(EXIT_FAILURE);
260}
261
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262// The primary goal of the watchdog is to prevent stuck build servers
263// during development when fatal aborts lead to a cascade of failures
264// that result in a deadlock.
265class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800266// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267#undef CHECK_PTHREAD_CALL
268#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
269 do { \
270 int rc = call args; \
271 if (rc != 0) { \
272 errno = rc; \
273 std::string message(# call); \
274 message += " failed for "; \
275 message += reason; \
276 Fatal(message); \
277 } \
278 } while (false)
279
280 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700281 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700282 is_watch_dog_enabled_ = is_watch_dog_enabled;
283 if (!is_watch_dog_enabled_) {
284 return;
285 }
286 shutting_down_ = false;
287 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
293 }
294 ~WatchDog() {
295 if (!is_watch_dog_enabled_) {
296 return;
297 }
298 const char* reason = "dex2oat watch dog thread shutdown";
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
300 shutting_down_ = true;
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
303
Kenny Root51316382014-05-13 14:59:37 -0700304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700305
306 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
308 }
309
310 private:
311 static void* CallBack(void* arg) {
312 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
313 ::art::SetThreadName("dex2oat watch dog");
314 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700315 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700316 }
317
318 static void Message(char severity, const std::string& message) {
319 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
320 // cases.
321 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
322 kIsDebugBuild ? "d" : "",
323 severity,
324 getpid(),
325 GetTid(),
326 message.c_str());
327 }
328
Ian Rogers7223d442014-10-10 20:05:39 -0700329 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700330 Message('F', message);
331 exit(1);
332 }
333
334 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
336 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800337 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 timespec timeout_ts;
339 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
340 const char* reason = "dex2oat watch dog thread waiting";
341 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
342 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800343 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800345 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 } else if (rc != 0) {
347 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
348 strerror(errno)));
349 Fatal(message.c_str());
350 }
351 }
352 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
353 }
354
355 // 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 -0700356 // Debug builds are slower so they have larger timeouts.
357 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800358
Elliott Hughes956af0f2014-12-11 14:34:28 -0800359 // 6 minutes scaled by kSlowdownFactor.
360 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700361
362 bool is_watch_dog_enabled_;
363 bool shutting_down_;
364 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
365 pthread_mutex_t mutex_;
366 pthread_cond_t cond_;
367 pthread_attr_t attr_;
368 pthread_t pthread_;
369};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800371static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100372 std::string::size_type colon = s.find(c);
373 if (colon == std::string::npos) {
374 Usage("Missing char %c in option %s\n", c, s.c_str());
375 }
376 // Add one to remove the char we were trimming until.
377 *parsed_value = s.substr(colon + 1);
378}
379
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800380static void ParseDouble(const std::string& option, char after_char, double min, double max,
381 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100382 std::string substring;
383 ParseStringAfterChar(option, after_char, &substring);
384 bool sane_val = true;
385 double value;
386 if (false) {
387 // TODO: this doesn't seem to work on the emulator. b/15114595
388 std::stringstream iss(substring);
389 iss >> value;
390 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
391 sane_val = iss.eof() && (value >= min) && (value <= max);
392 } else {
393 char* end = nullptr;
394 value = strtod(substring.c_str(), &end);
395 sane_val = *end == '\0' && value >= min && value <= max;
396 }
397 if (!sane_val) {
398 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
399 }
400 *parsed_value = value;
401}
402
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800403static constexpr size_t kMinDexFilesForSwap = 2;
404static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
405
406static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
407 if (is_image) {
408 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
409 return false;
410 }
411 if (dex_files.size() < kMinDexFilesForSwap) {
412 // If there are less dex files than the threshold, assume it's gonna be fine.
413 return false;
414 }
415 size_t dex_files_size = 0;
416 for (const auto* dex_file : dex_files) {
417 dex_files_size += dex_file->GetHeader().file_size_;
418 }
419 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
420}
421
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800422class Dex2Oat FINAL {
423 public:
424 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800425 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800426 instruction_set_(kRuntimeISA),
427 // Take the default set of instruction features from the build.
428 method_inliner_map_(),
429 runtime_(nullptr),
430 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
431 start_ns_(NanoTime()),
432 oat_fd_(-1),
433 zip_fd_(-1),
434 image_base_(0U),
435 image_classes_zip_filename_(nullptr),
436 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800437 compiled_classes_zip_filename_(nullptr),
438 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800439 image_(false),
440 is_host_(false),
441 dump_stats_(false),
442 dump_passes_(false),
443 dump_timing_(false),
444 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800445 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800446 timings_(timings) {}
447
448 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800449 // Free opened dex files before deleting the runtime_, because ~DexFile
450 // uses MemMap, which is shut down by ~Runtime.
451 class_path_files_.clear();
452 opened_dex_files_.clear();
453
454 // Log completion time before deleting the runtime_, because this accesses
455 // the runtime.
456 LogCompletionTime();
457
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800458 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
459 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100460 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 }
462
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800463 // Parse the arguments from the command line. In case of an unrecognized option or impossible
464 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
465 // returns, arguments have been successfully parsed.
466 void ParseArgs(int argc, char** argv) {
467 original_argc = argc;
468 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700469
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800470 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700471
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472 // Skip over argv[0].
473 argv++;
474 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700475
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476 if (argc == 0) {
477 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700478 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800479
480 std::string oat_symbols;
481 std::string boot_image_filename;
482 const char* compiler_filter_string = nullptr;
483 bool compile_pic = false;
484 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
485 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
486 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
487 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
488 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
489
490 // Profile file to use
491 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
492
493 bool print_pass_options = false;
494 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
495 bool include_debug_symbols = kIsDebugBuild;
496 bool watch_dog_enabled = true;
497 bool generate_gdb_information = kIsDebugBuild;
498
499 std::string error_msg;
500
501 for (int i = 0; i < argc; i++) {
502 const StringPiece option(argv[i]);
503 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 if (log_options) {
505 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
506 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800507 if (option.starts_with("--dex-file=")) {
508 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
509 } else if (option.starts_with("--dex-location=")) {
510 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
511 } else if (option.starts_with("--zip-fd=")) {
512 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
513 if (!ParseInt(zip_fd_str, &zip_fd_)) {
514 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
515 }
516 if (zip_fd_ < 0) {
517 Usage("--zip-fd passed a negative value %d", zip_fd_);
518 }
519 } else if (option.starts_with("--zip-location=")) {
520 zip_location_ = option.substr(strlen("--zip-location=")).data();
521 } else if (option.starts_with("--oat-file=")) {
522 oat_filename_ = option.substr(strlen("--oat-file=")).data();
523 } else if (option.starts_with("--oat-symbols=")) {
524 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
525 } else if (option.starts_with("--oat-fd=")) {
526 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
527 if (!ParseInt(oat_fd_str, &oat_fd_)) {
528 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
529 }
530 if (oat_fd_ < 0) {
531 Usage("--oat-fd passed a negative value %d", oat_fd_);
532 }
533 } else if (option == "--watch-dog") {
534 watch_dog_enabled = true;
535 } else if (option == "--no-watch-dog") {
536 watch_dog_enabled = false;
537 } else if (option == "--gen-gdb-info") {
538 generate_gdb_information = true;
539 // Debug symbols are needed for gdb information.
540 include_debug_symbols = true;
541 } else if (option == "--no-gen-gdb-info") {
542 generate_gdb_information = false;
543 } else if (option.starts_with("-j")) {
544 const char* thread_count_str = option.substr(strlen("-j")).data();
545 if (!ParseUint(thread_count_str, &thread_count_)) {
546 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
547 }
548 } else if (option.starts_with("--oat-location=")) {
549 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800550 } else if (option.starts_with("--image=")) {
551 image_filename_ = option.substr(strlen("--image=")).data();
552 } else if (option.starts_with("--image-classes=")) {
553 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
554 } else if (option.starts_with("--image-classes-zip=")) {
555 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800556 } else if (option.starts_with("--compiled-classes=")) {
557 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
558 } else if (option.starts_with("--compiled-classes-zip=")) {
559 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800560 } else if (option.starts_with("--base=")) {
561 const char* image_base_str = option.substr(strlen("--base=")).data();
562 char* end;
563 image_base_ = strtoul(image_base_str, &end, 16);
564 if (end == image_base_str || *end != '\0') {
565 Usage("Failed to parse hexadecimal value for option %s", option.data());
566 }
567 } else if (option.starts_with("--boot-image=")) {
568 boot_image_filename = option.substr(strlen("--boot-image=")).data();
569 } else if (option.starts_with("--android-root=")) {
570 android_root_ = option.substr(strlen("--android-root=")).data();
571 } else if (option.starts_with("--instruction-set=")) {
572 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
573 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800574 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800575 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
576 buf.get()[instruction_set_str.length()] = 0;
577 instruction_set_ = GetInstructionSetFromString(buf.get());
578 // arm actually means thumb2.
579 if (instruction_set_ == InstructionSet::kArm) {
580 instruction_set_ = InstructionSet::kThumb2;
581 }
582 } else if (option.starts_with("--instruction-set-variant=")) {
583 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
584 instruction_set_features_.reset(
585 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
586 if (instruction_set_features_.get() == nullptr) {
587 Usage("%s", error_msg.c_str());
588 }
589 } else if (option.starts_with("--instruction-set-features=")) {
590 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800591 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800592 instruction_set_features_.reset(
593 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
594 if (instruction_set_features_.get() == nullptr) {
595 Usage("Problem initializing default instruction set features variant: %s",
596 error_msg.c_str());
597 }
598 }
599 instruction_set_features_.reset(
600 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
601 if (instruction_set_features_.get() == nullptr) {
602 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800603 }
604 } else if (option.starts_with("--compiler-backend=")) {
605 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
606 if (backend_str == "Quick") {
607 compiler_kind_ = Compiler::kQuick;
608 } else if (backend_str == "Optimizing") {
609 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800610 } else {
611 Usage("Unknown compiler backend: %s", backend_str.data());
612 }
613 } else if (option.starts_with("--compiler-filter=")) {
614 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
615 } else if (option == "--compile-pic") {
616 compile_pic = true;
617 } else if (option.starts_with("--huge-method-max=")) {
618 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
619 if (!ParseInt(threshold, &huge_method_threshold)) {
620 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
621 }
622 if (huge_method_threshold < 0) {
623 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
624 }
625 } else if (option.starts_with("--large-method-max=")) {
626 const char* threshold = option.substr(strlen("--large-method-max=")).data();
627 if (!ParseInt(threshold, &large_method_threshold)) {
628 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
629 }
630 if (large_method_threshold < 0) {
631 Usage("--large-method-max passed a negative value %s", large_method_threshold);
632 }
633 } else if (option.starts_with("--small-method-max=")) {
634 const char* threshold = option.substr(strlen("--small-method-max=")).data();
635 if (!ParseInt(threshold, &small_method_threshold)) {
636 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
637 }
638 if (small_method_threshold < 0) {
639 Usage("--small-method-max passed a negative value %s", small_method_threshold);
640 }
641 } else if (option.starts_with("--tiny-method-max=")) {
642 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
643 if (!ParseInt(threshold, &tiny_method_threshold)) {
644 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
645 }
646 if (tiny_method_threshold < 0) {
647 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
648 }
649 } else if (option.starts_with("--num-dex-methods=")) {
650 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
651 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
652 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
653 }
654 if (num_dex_methods_threshold < 0) {
655 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
656 }
657 } else if (option == "--host") {
658 is_host_ = true;
659 } else if (option == "--runtime-arg") {
660 if (++i >= argc) {
661 Usage("Missing required argument for --runtime-arg");
662 }
663 if (log_options) {
664 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
665 }
666 runtime_args_.push_back(argv[i]);
667 } else if (option == "--dump-timing") {
668 dump_timing_ = true;
669 } else if (option == "--dump-passes") {
670 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000671 } else if (option.starts_with("--dump-cfg=")) {
672 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800673 } else if (option == "--dump-stats") {
674 dump_stats_ = true;
675 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
676 include_debug_symbols = true;
677 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
678 include_debug_symbols = false;
679 generate_gdb_information = false; // Depends on debug symbols, see above.
680 } else if (option.starts_with("--profile-file=")) {
681 profile_file_ = option.substr(strlen("--profile-file=")).data();
682 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
683 } else if (option == "--no-profile-file") {
684 // No profile
685 } else if (option.starts_with("--top-k-profile-threshold=")) {
686 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
687 } else if (option == "--print-pass-names") {
688 PassDriverMEOpts::PrintPassNames();
689 } else if (option.starts_with("--disable-passes=")) {
690 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
691 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
692 } else if (option.starts_with("--print-passes=")) {
693 std::string print_passes = option.substr(strlen("--print-passes=")).data();
694 PassDriverMEOpts::SetPrintPassList(print_passes);
695 } else if (option == "--print-all-passes") {
696 PassDriverMEOpts::SetPrintAllPasses();
697 } else if (option.starts_with("--dump-cfg-passes=")) {
698 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
699 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
700 } else if (option == "--print-pass-options") {
701 print_pass_options = true;
702 } else if (option.starts_with("--pass-options=")) {
703 std::string options = option.substr(strlen("--pass-options=")).data();
704 PassDriverMEOpts::SetOverriddenPassOptions(options);
705 } else if (option == "--include-patch-information") {
706 include_patch_information = true;
707 } else if (option == "--no-include-patch-information") {
708 include_patch_information = false;
709 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800710 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
711 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800712 gLogVerbosity.compiler = false;
713 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800714 } else if (option.starts_with("--dump-init-failures=")) {
715 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
716 init_failure_output_.reset(new std::ofstream(file_name));
717 if (init_failure_output_.get() == nullptr) {
718 LOG(ERROR) << "Failed to allocate ofstream";
719 } else if (init_failure_output_->fail()) {
720 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
721 << "failures.";
722 init_failure_output_.reset();
723 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800724 } else if (option.starts_with("--swap-file=")) {
725 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
726 } else if (option.starts_with("--swap-fd=")) {
727 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
728 if (!ParseInt(swap_fd_str, &swap_fd_)) {
729 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
730 }
731 if (swap_fd_ < 0) {
732 Usage("--swap-fd passed a negative value %d", swap_fd_);
733 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 } else {
735 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700736 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800737 }
738
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000739 if (compiler_kind_ == Compiler::kOptimizing) {
740 // Optimizing only supports PIC mode.
741 compile_pic = true;
742 }
743
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800744 if (oat_filename_.empty() && oat_fd_ == -1) {
745 Usage("Output must be supplied with either --oat-file or --oat-fd");
746 }
747
748 if (!oat_filename_.empty() && oat_fd_ != -1) {
749 Usage("--oat-file should not be used with --oat-fd");
750 }
751
752 if (!oat_symbols.empty() && oat_fd_ != -1) {
753 Usage("--oat-symbols should not be used with --oat-fd");
754 }
755
756 if (!oat_symbols.empty() && is_host_) {
757 Usage("--oat-symbols should not be used with --host");
758 }
759
760 if (oat_fd_ != -1 && !image_filename_.empty()) {
761 Usage("--oat-fd should not be used with --image");
762 }
763
764 if (android_root_.empty()) {
765 const char* android_root_env_var = getenv("ANDROID_ROOT");
766 if (android_root_env_var == nullptr) {
767 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700768 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800769 android_root_ += android_root_env_var;
770 }
771
772 image_ = (!image_filename_.empty());
773 if (!image_ && boot_image_filename.empty()) {
774 boot_image_filename += android_root_;
775 boot_image_filename += "/framework/boot.art";
776 }
777 if (!boot_image_filename.empty()) {
778 boot_image_option_ += "-Ximage:";
779 boot_image_option_ += boot_image_filename;
780 }
781
782 if (image_classes_filename_ != nullptr && !image_) {
783 Usage("--image-classes should only be used with --image");
784 }
785
786 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
787 Usage("--image-classes should not be used with --boot-image");
788 }
789
790 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
791 Usage("--image-classes-zip should be used with --image-classes");
792 }
793
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800794 if (compiled_classes_filename_ != nullptr && !image_) {
795 Usage("--compiled-classes should only be used with --image");
796 }
797
798 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
799 Usage("--compiled-classes should not be used with --boot-image");
800 }
801
802 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
803 Usage("--compiled-classes-zip should be used with --compiled-classes");
804 }
805
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800806 if (dex_filenames_.empty() && zip_fd_ == -1) {
807 Usage("Input must be supplied with either --dex-file or --zip-fd");
808 }
809
810 if (!dex_filenames_.empty() && zip_fd_ != -1) {
811 Usage("--dex-file should not be used with --zip-fd");
812 }
813
814 if (!dex_filenames_.empty() && !zip_location_.empty()) {
815 Usage("--dex-file should not be used with --zip-location");
816 }
817
818 if (dex_locations_.empty()) {
819 for (const char* dex_file_name : dex_filenames_) {
820 dex_locations_.push_back(dex_file_name);
821 }
822 } else if (dex_locations_.size() != dex_filenames_.size()) {
823 Usage("--dex-location arguments do not match --dex-file arguments");
824 }
825
826 if (zip_fd_ != -1 && zip_location_.empty()) {
827 Usage("--zip-location should be supplied with --zip-fd");
828 }
829
830 if (boot_image_option_.empty()) {
831 if (image_base_ == 0) {
832 Usage("Non-zero --base not specified");
833 }
834 }
835
836 oat_stripped_ = oat_filename_;
837 if (!oat_symbols.empty()) {
838 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800840 oat_unstripped_ = oat_filename_;
841 }
842
843 // If no instruction set feature was given, use the default one for the target
844 // instruction set.
845 if (instruction_set_features_.get() == nullptr) {
846 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800847 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
848 if (instruction_set_features_.get() == nullptr) {
849 Usage("Problem initializing default instruction set features variant: %s",
850 error_msg.c_str());
851 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800852 }
853
854 if (instruction_set_ == kRuntimeISA) {
855 std::unique_ptr<const InstructionSetFeatures> runtime_features(
856 InstructionSetFeatures::FromCppDefines());
857 if (!instruction_set_features_->Equals(runtime_features.get())) {
858 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
859 << *instruction_set_features_ << ") and those of dex2oat executable ("
860 << *runtime_features <<") for the command line:\n"
861 << CommandLine();
862 }
863 }
864
865 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800866 if (instruction_set_ == kMips &&
867 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
868 IsR6()) {
869 // For R6, only interpreter mode is working.
870 // TODO: fix compiler for Mips32r6.
871 compiler_filter_string = "interpret-only";
872 } else if (instruction_set_ == kMips64) {
Andreas Gampe57b34292015-01-14 15:45:59 -0800873 // For Mips64, can only compile in interpreter mode.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800874 // TODO: fix compiler for Mips64.
875 compiler_filter_string = "interpret-only";
876 } else if (image_) {
877 compiler_filter_string = "speed";
878 } else {
879 // TODO: Migrate SMALL mode to command line option.
880 #if ART_SMALL_MODE
881 compiler_filter_string = "interpret-only";
882 #else
883 compiler_filter_string = "speed";
884 #endif
885 }
886 }
887 CHECK(compiler_filter_string != nullptr);
888 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
889 if (strcmp(compiler_filter_string, "verify-none") == 0) {
890 compiler_filter = CompilerOptions::kVerifyNone;
891 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
892 compiler_filter = CompilerOptions::kInterpretOnly;
893 } else if (strcmp(compiler_filter_string, "space") == 0) {
894 compiler_filter = CompilerOptions::kSpace;
895 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
896 compiler_filter = CompilerOptions::kBalanced;
897 } else if (strcmp(compiler_filter_string, "speed") == 0) {
898 compiler_filter = CompilerOptions::kSpeed;
899 } else if (strcmp(compiler_filter_string, "everything") == 0) {
900 compiler_filter = CompilerOptions::kEverything;
901 } else if (strcmp(compiler_filter_string, "time") == 0) {
902 compiler_filter = CompilerOptions::kTime;
903 } else {
904 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
905 }
906
907 // Checks are all explicit until we know the architecture.
908 bool implicit_null_checks = false;
909 bool implicit_so_checks = false;
910 bool implicit_suspend_checks = false;
911 // Set the compilation target's implicit checks options.
912 switch (instruction_set_) {
913 case kArm:
914 case kThumb2:
915 case kArm64:
916 case kX86:
917 case kX86_64:
918 implicit_null_checks = true;
919 implicit_so_checks = true;
920 break;
921
922 default:
923 // Defaults are correct.
924 break;
925 }
926
927 if (print_pass_options) {
928 PassDriverMEOpts::PrintPassOptions();
929 }
930
931 compiler_options_.reset(new CompilerOptions(compiler_filter,
932 huge_method_threshold,
933 large_method_threshold,
934 small_method_threshold,
935 tiny_method_threshold,
936 num_dex_methods_threshold,
937 generate_gdb_information,
938 include_patch_information,
939 top_k_profile_threshold,
940 include_debug_symbols,
941 implicit_null_checks,
942 implicit_so_checks,
943 implicit_suspend_checks,
944 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945 verbose_methods_.empty() ?
946 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800947 &verbose_methods_,
948 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800949
950 // Done with usage checks, enable watchdog if requested
951 if (watch_dog_enabled) {
952 watchdog_.reset(new WatchDog(true));
953 }
954
955 // Fill some values into the key-value store for the oat header.
956 key_value_store_.reset(new SafeMap<std::string, std::string>());
957
958 // Insert some compiler things.
959 {
960 std::ostringstream oss;
961 for (int i = 0; i < argc; ++i) {
962 if (i > 0) {
963 oss << ' ';
964 }
965 oss << argv[i];
966 }
967 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
968 oss.str(""); // Reset.
969 oss << kRuntimeISA;
970 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
971 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
972 }
973 }
974
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800975 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
976 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800977 bool OpenFile() {
978 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
979 if (create_file) {
980 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
981 if (oat_location_.empty()) {
982 oat_location_ = oat_filename_;
983 }
984 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800985 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800987 if (oat_file_->SetLength(0) != 0) {
988 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
989 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800990 }
991 if (oat_file_.get() == nullptr) {
992 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
993 return false;
994 }
995 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
996 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800997 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800998 return false;
999 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001000
1001 // Swap file handling.
1002 //
1003 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1004 // that we can use for swap.
1005 //
1006 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1007 // will immediately unlink to satisfy the swap fd assumption.
1008 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1009 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1010 if (swap_file.get() == nullptr) {
1011 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1012 return false;
1013 }
1014 swap_fd_ = swap_file->Fd();
1015 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1016 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1017 // released immediately.
1018 unlink(swap_file_name_.c_str());
1019 }
1020
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001021 return true;
1022 }
1023
Andreas Gampea650e702014-12-03 14:28:02 -08001024 void EraseOatFile() {
1025 DCHECK(oat_file_.get() != nullptr);
1026 oat_file_->Erase();
1027 oat_file_.reset();
1028 }
1029
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001030 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1031 // boot class path.
1032 bool Setup() {
1033 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1034 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001035 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1036 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001037 std::string boot_class_path = "-Xbootclasspath:";
1038 boot_class_path += Join(dex_filenames_, ':');
1039 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1040 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1041 boot_class_path_locations += Join(dex_locations_, ':');
1042 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001043 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001044 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001045 }
1046 for (size_t i = 0; i < runtime_args_.size(); i++) {
1047 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001048 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001049
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001050 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1051 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1052 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1053 runtime_options.push_back(
1054 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1055
1056 if (!CreateRuntime(runtime_options)) {
1057 return false;
1058 }
1059
1060 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1061 // Runtime::Start, give it away now so that we don't starve GC.
1062 Thread* self = Thread::Current();
1063 self->TransitionFromRunnableToSuspended(kNative);
1064 // If we're doing the image, override the compiler filter to force full compilation. Must be
1065 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1066 // compilation of class initializers.
1067 // Whilst we're in native take the opportunity to initialize well known classes.
1068 WellKnownClasses::Init(self->GetJniEnv());
1069
1070 // If --image-classes was specified, calculate the full list of classes to include in the image
1071 if (image_classes_filename_ != nullptr) {
1072 std::string error_msg;
1073 if (image_classes_zip_filename_ != nullptr) {
1074 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1075 image_classes_filename_,
1076 &error_msg));
1077 } else {
1078 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1079 }
1080 if (image_classes_.get() == nullptr) {
1081 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1082 "': " << error_msg;
1083 return false;
1084 }
1085 } else if (image_) {
1086 image_classes_.reset(new std::set<std::string>);
1087 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001088 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1089 // image.
1090 if (compiled_classes_filename_ != nullptr) {
1091 std::string error_msg;
1092 if (compiled_classes_zip_filename_ != nullptr) {
1093 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1094 compiled_classes_filename_,
1095 &error_msg));
1096 } else {
1097 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1098 }
1099 if (compiled_classes_.get() == nullptr) {
1100 LOG(ERROR) << "Failed to create list of compiled classes from '"
1101 << compiled_classes_filename_ << "': " << error_msg;
1102 return false;
1103 }
1104 } else if (image_) {
1105 compiled_classes_.reset(nullptr); // By default compile everything.
1106 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001107
1108 if (boot_image_option_.empty()) {
1109 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1110 } else {
1111 if (dex_filenames_.empty()) {
1112 ATRACE_BEGIN("Opening zip archive from file descriptor");
1113 std::string error_msg;
1114 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1115 zip_location_.c_str(),
1116 &error_msg));
1117 if (zip_archive.get() == nullptr) {
1118 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1119 << error_msg;
1120 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001121 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001122 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001123 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1124 << "': " << error_msg;
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 ATRACE_END();
1131 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001132 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001133 if (failure_count > 0) {
1134 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1135 return false;
1136 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001137 for (auto& dex_file : opened_dex_files_) {
1138 dex_files_.push_back(dex_file.get());
1139 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 }
1141
1142 constexpr bool kSaveDexInput = false;
1143 if (kSaveDexInput) {
1144 for (size_t i = 0; i < dex_files_.size(); ++i) {
1145 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001146 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1147 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001148 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1149 if (tmp_file.get() == nullptr) {
1150 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1151 << ". Try: adb shell chmod 777 /data/local/tmp";
1152 continue;
1153 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001154 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1155 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1156 UNUSED(tmp_file->Flush());
1157 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001158 LOG(INFO) << "Wrote input to " << tmp_file_name;
1159 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001160 }
1161 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001162 // Ensure opened dex files are writable for dex-to-dex transformations.
1163 for (const auto& dex_file : dex_files_) {
1164 if (!dex_file->EnableWrite()) {
1165 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001166 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001167 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001169 // If we use a swap file, ensure we are above the threshold to make it necessary.
1170 if (swap_fd_ != -1) {
1171 if (!UseSwap(image_, dex_files_)) {
1172 close(swap_fd_);
1173 swap_fd_ = -1;
1174 LOG(INFO) << "Decided to run without swap.";
1175 } else {
1176 LOG(INFO) << "Accepted running with swap.";
1177 }
1178 }
1179 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1180
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001181 /*
1182 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1183 * Don't bother to check if we're doing the image.
1184 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001185 if (!image_ &&
1186 compiler_options_->IsCompilationEnabled() &&
1187 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001188 size_t num_methods = 0;
1189 for (size_t i = 0; i != dex_files_.size(); ++i) {
1190 const DexFile* dex_file = dex_files_[i];
1191 CHECK(dex_file != nullptr);
1192 num_methods += dex_file->NumMethodIds();
1193 }
1194 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1195 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1196 VLOG(compiler) << "Below method threshold, compiling anyways";
1197 }
1198 }
1199
1200 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001201 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001202
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001203 // Create and invoke the compiler driver. This will compile all the dex files.
1204 void Compile() {
1205 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1206 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001207
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 // Handle and ClassLoader creation needs to come after Runtime::Create
1209 jobject class_loader = nullptr;
1210 Thread* self = Thread::Current();
1211 if (!boot_image_option_.empty()) {
1212 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001213 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001214 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001215 std::vector<const DexFile*> class_path_files(dex_files_);
1216 for (auto& class_path_file : class_path_files_) {
1217 class_path_files.push_back(class_path_file.get());
1218 }
1219
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001220 for (size_t i = 0; i < class_path_files.size(); i++) {
1221 class_linker->RegisterDexFile(*class_path_files[i]);
1222 }
1223 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1224 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1225 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1226 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1227 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1228 }
1229
1230 driver_.reset(new CompilerDriver(compiler_options_.get(),
1231 verification_results_.get(),
1232 &method_inliner_map_,
1233 compiler_kind_,
1234 instruction_set_,
1235 instruction_set_features_.get(),
1236 image_,
1237 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001238 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001239 thread_count_,
1240 dump_stats_,
1241 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001242 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001243 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001244 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001245 profile_file_));
1246
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001247 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001248 }
1249
Brian Carlstrom7940e442013-07-12 13:46:57 -07001250 // Notes on the interleaving of creating the image and oat file to
1251 // ensure the references between the two are correct.
1252 //
1253 // Currently we have a memory layout that looks something like this:
1254 //
1255 // +--------------+
1256 // | image |
1257 // +--------------+
1258 // | boot oat |
1259 // +--------------+
1260 // | alloc spaces |
1261 // +--------------+
1262 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001263 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001264 //
1265 // 1. The image is expected to be loaded at an absolute address and
1266 // contains Objects with absolute pointers within the image.
1267 //
1268 // 2. There are absolute pointers from Methods in the image to their
1269 // code in the oat.
1270 //
1271 // 3. There are absolute pointers from the code in the oat to Methods
1272 // in the image.
1273 //
1274 // 4. There are absolute pointers from code in the oat to other code
1275 // in the oat.
1276 //
1277 // To get this all correct, we go through several steps.
1278 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001279 // 1. We prepare offsets for all data in the oat file and calculate
1280 // the oat data size and code size. During this stage, we also set
1281 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001282 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001283 // 2. We prepare offsets for the objects in the image and calculate
1284 // the image size.
1285 //
1286 // 3. We create the oat file. Originally this was just our own proprietary
1287 // file but now it is contained within an ELF dynamic object (aka an .so
1288 // file). Since we know the image size and oat data size and code size we
1289 // can prepare the ELF headers and we then know the ELF memory segment
1290 // layout and we can now resolve all references. The compiler provides
1291 // LinkerPatch information in each CompiledMethod and we resolve these,
1292 // using the layout information and image object locations provided by
1293 // image writer, as we're writing the method code.
1294 //
1295 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001296 // will be loaded after itself. Originally when oat file was simply
1297 // memory mapped so we could predict where its contents were based
1298 // on the file size. Now that it is an ELF file, we need to inspect
1299 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001300 // where the oat header is located within.
1301 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001302 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001303 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001304 // load the .so at the desired location at runtime by offsetting the
1305 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001306 // TODO: Do this in step 3. We already know the layout there.
1307 //
1308 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1309 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001310
1311
1312 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1313 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001314 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1315 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001316 bool CreateOatFile() {
1317 CHECK(key_value_store_.get() != nullptr);
1318
1319 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1320
1321 std::unique_ptr<OatWriter> oat_writer;
1322 {
1323 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1324 std::string image_file_location;
1325 uint32_t image_file_location_oat_checksum = 0;
1326 uintptr_t image_file_location_oat_data_begin = 0;
1327 int32_t image_patch_delta = 0;
1328 if (image_) {
1329 PrepareImageWriter(image_base_);
1330 } else {
1331 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1332 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1333 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1334 image_file_location_oat_data_begin =
1335 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1336 image_file_location = image_space->GetImageFilename();
1337 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1338 }
1339
1340 if (!image_file_location.empty()) {
1341 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1342 }
1343
1344 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1345 image_file_location_oat_data_begin,
1346 image_patch_delta,
1347 driver_.get(),
1348 image_writer_.get(),
1349 timings_,
1350 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001351 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001352
1353 if (image_) {
1354 // The OatWriter constructor has already updated offsets in methods and we need to
1355 // prepare method offsets in the image address space for direct method patching.
1356 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1357 if (!image_writer_->PrepareImageAddressSpace()) {
1358 LOG(ERROR) << "Failed to prepare image address space.";
1359 return false;
1360 }
1361 }
1362
1363 {
1364 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1365 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1366 oat_file_.get())) {
1367 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1368 return false;
1369 }
1370 }
1371
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001372 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1373 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001374 }
1375
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001376 // If we are compiling an image, invoke the image creation routine. Else just skip.
1377 bool HandleImage() {
1378 if (image_) {
1379 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1380 if (!CreateImageFile()) {
1381 return false;
1382 }
1383 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001384 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001385 return true;
1386 }
1387
Andreas Gampe10e477d2014-11-19 12:57:42 -08001388 // Create a copy from unstripped to stripped.
1389 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001390 // If we don't want to strip in place, copy from unstripped location to stripped location.
1391 // We need to strip after image creation because FixupElf needs to use .strtab.
1392 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001393 // If the oat file is still open, flush it.
1394 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1395 if (!FlushCloseOatFile()) {
1396 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001397 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001398 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001399
1400 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001401 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1402 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1403 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001404 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001405 while (true) {
1406 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1407 if (bytes_read <= 0) {
1408 break;
1409 }
1410 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1411 CHECK(write_ok);
1412 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001413 if (out->FlushCloseOrErase() != 0) {
1414 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1415 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001416 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001417 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001418 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001419 return true;
1420 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001421
Andreas Gampe10e477d2014-11-19 12:57:42 -08001422 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001423 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001424 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1425 if (oat_file_->Flush() != 0) {
1426 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1427 << oat_filename_;
1428 oat_file_->Erase();
1429 return false;
1430 }
1431 }
1432 return true;
1433 }
1434
1435 bool FlushCloseOatFile() {
1436 if (oat_file_.get() != nullptr) {
1437 std::unique_ptr<File> tmp(oat_file_.release());
1438 if (tmp->FlushCloseOrErase() != 0) {
1439 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1440 << oat_filename_;
1441 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001442 }
1443 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001444 return true;
1445 }
1446
1447 void DumpTiming() {
1448 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1449 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1450 }
1451 if (dump_passes_) {
1452 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1453 }
1454 }
1455
1456 CompilerOptions* GetCompilerOptions() const {
1457 return compiler_options_.get();
1458 }
1459
Andreas Gampe10e477d2014-11-19 12:57:42 -08001460 bool IsImage() const {
1461 return image_;
1462 }
1463
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001464 bool IsHost() const {
1465 return is_host_;
1466 }
1467
1468 private:
1469 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1470 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001471 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1472 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001473 size_t failure_count = 0;
1474 for (size_t i = 0; i < dex_filenames.size(); i++) {
1475 const char* dex_filename = dex_filenames[i];
1476 const char* dex_location = dex_locations[i];
1477 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1478 std::string error_msg;
1479 if (!OS::FileExists(dex_filename)) {
1480 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1481 continue;
1482 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001483 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001484 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1485 ++failure_count;
1486 }
1487 ATRACE_END();
1488 }
1489 return failure_count;
1490 }
1491
1492 // Returns true if dex_files has a dex with the named location.
1493 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1494 const std::string& location) {
1495 for (size_t i = 0; i < dex_files.size(); ++i) {
1496 if (dex_files[i]->GetLocation() == location) {
1497 return true;
1498 }
1499 }
1500 return false;
1501 }
1502
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001503 // Appends to opened_dex_files any elements of class_path that dex_files
1504 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001505 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001506 std::vector<const DexFile*> dex_files,
1507 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1508 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001509 std::vector<std::string> parsed;
1510 Split(class_path, ':', &parsed);
1511 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1512 ScopedObjectAccess soa(Thread::Current());
1513 for (size_t i = 0; i < parsed.size(); ++i) {
1514 if (DexFilesContains(dex_files, parsed[i])) {
1515 continue;
1516 }
1517 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001518 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001519 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1520 }
1521 }
1522 }
1523
1524 // Create a runtime necessary for compilation.
1525 bool CreateRuntime(const RuntimeOptions& runtime_options)
1526 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1527 if (!Runtime::Create(runtime_options, false)) {
1528 LOG(ERROR) << "Failed to create runtime";
1529 return false;
1530 }
1531 Runtime* runtime = Runtime::Current();
1532 runtime->SetInstructionSet(instruction_set_);
1533 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1534 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1535 if (!runtime->HasCalleeSaveMethod(type)) {
1536 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1537 }
1538 }
1539 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1540 runtime->GetClassLinker()->RunRootClinits();
1541 runtime_ = runtime;
1542 return true;
1543 }
1544
1545 void PrepareImageWriter(uintptr_t image_base) {
1546 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1547 }
1548
1549 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1550 bool CreateImageFile()
1551 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1552 CHECK(image_writer_ != nullptr);
1553 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1554 LOG(ERROR) << "Failed to create image file " << image_filename_;
1555 return false;
1556 }
1557 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1558
1559 // Destroy ImageWriter before doing FixupElf.
1560 image_writer_.reset();
1561
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001562 // Do not fix up the ELF file if we are --compile-pic
1563 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001564 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1565 if (oat_file.get() == nullptr) {
1566 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1567 return false;
1568 }
1569
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001570 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001571 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001572 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1573 return false;
1574 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001575
1576 if (oat_file->FlushCloseOrErase()) {
1577 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1578 return false;
1579 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001580 }
1581
1582 return true;
1583 }
1584
1585 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1586 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1587 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1588 std::ifstream::in));
1589 if (image_classes_file.get() == nullptr) {
1590 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1591 return nullptr;
1592 }
1593 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1594 image_classes_file->close();
1595 return result.release();
1596 }
1597
1598 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1599 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1600 while (image_classes_stream.good()) {
1601 std::string dot;
1602 std::getline(image_classes_stream, dot);
1603 if (StartsWith(dot, "#") || dot.empty()) {
1604 continue;
1605 }
1606 std::string descriptor(DotToDescriptor(dot.c_str()));
1607 image_classes->insert(descriptor);
1608 }
1609 return image_classes.release();
1610 }
1611
1612 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1613 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1614 const char* image_classes_filename,
1615 std::string* error_msg) {
1616 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1617 if (zip_archive.get() == nullptr) {
1618 return nullptr;
1619 }
1620 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1621 if (zip_entry.get() == nullptr) {
1622 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1623 zip_filename, error_msg->c_str());
1624 return nullptr;
1625 }
1626 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1627 image_classes_filename,
1628 error_msg));
1629 if (image_classes_file.get() == nullptr) {
1630 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1631 zip_filename, error_msg->c_str());
1632 return nullptr;
1633 }
1634 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1635 image_classes_file->Size());
1636 std::istringstream image_classes_stream(image_classes_string);
1637 return ReadImageClasses(image_classes_stream);
1638 }
1639
Mathieu Chartier49285c52014-12-02 15:43:48 -08001640 void LogCompletionTime() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001641 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001642 << " (threads: " << thread_count_ << ") "
Andreas Gampe8d295f82015-01-20 14:50:21 -08001643 << driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001644 }
1645
1646 std::unique_ptr<CompilerOptions> compiler_options_;
1647 Compiler::Kind compiler_kind_;
1648
1649 InstructionSet instruction_set_;
1650 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1651
1652 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1653
1654 std::unique_ptr<VerificationResults> verification_results_;
1655 DexFileToMethodInlinerMap method_inliner_map_;
1656 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1657
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001658 // Ownership for the class path files.
1659 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1660
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001661 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1662 // in an orderly fashion. The destructor takes care of deleting this.
1663 Runtime* runtime_;
1664
1665 size_t thread_count_;
1666 uint64_t start_ns_;
1667 std::unique_ptr<WatchDog> watchdog_;
1668 std::unique_ptr<File> oat_file_;
1669 std::string oat_stripped_;
1670 std::string oat_unstripped_;
1671 std::string oat_location_;
1672 std::string oat_filename_;
1673 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001674 std::vector<const char*> dex_filenames_;
1675 std::vector<const char*> dex_locations_;
1676 int zip_fd_;
1677 std::string zip_location_;
1678 std::string boot_image_option_;
1679 std::vector<const char*> runtime_args_;
1680 std::string image_filename_;
1681 uintptr_t image_base_;
1682 const char* image_classes_zip_filename_;
1683 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001684 const char* compiled_classes_zip_filename_;
1685 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001686 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001687 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001688 bool image_;
1689 std::unique_ptr<ImageWriter> image_writer_;
1690 bool is_host_;
1691 std::string android_root_;
1692 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001693 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001694 std::unique_ptr<CompilerDriver> driver_;
1695 std::vector<std::string> verbose_methods_;
1696 bool dump_stats_;
1697 bool dump_passes_;
1698 bool dump_timing_;
1699 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001700 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001701 std::string swap_file_name_;
1702 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001703 std::string profile_file_; // Profile file to use
1704 TimingLogger* timings_;
1705 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001706 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001707
1708 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1709};
1710
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001711const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1712
1713static void b13564922() {
1714#if defined(__linux__) && defined(__arm__)
1715 int major, minor;
1716 struct utsname uts;
1717 if (uname(&uts) != -1 &&
1718 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1719 ((major < 3) || ((major == 3) && (minor < 4)))) {
1720 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1721 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1722 int old_personality = personality(0xffffffff);
1723 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1724 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1725 if (new_personality == -1) {
1726 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1727 }
1728 }
1729 }
1730#endif
1731}
1732
Andreas Gampe10e477d2014-11-19 12:57:42 -08001733static int CompileImage(Dex2Oat& dex2oat) {
1734 dex2oat.Compile();
1735
1736 // Create the boot.oat.
1737 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001738 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001739 return EXIT_FAILURE;
1740 }
1741
1742 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1743 // re-opened from the unstripped name.
1744 if (!dex2oat.FlushCloseOatFile()) {
1745 return EXIT_FAILURE;
1746 }
1747
1748 // Creates the boot.art and patches the boot.oat.
1749 if (!dex2oat.HandleImage()) {
1750 return EXIT_FAILURE;
1751 }
1752
1753 // When given --host, finish early without stripping.
1754 if (dex2oat.IsHost()) {
1755 dex2oat.DumpTiming();
1756 return EXIT_SUCCESS;
1757 }
1758
1759 // Copy unstripped to stripped location, if necessary.
1760 if (!dex2oat.CopyUnstrippedToStripped()) {
1761 return EXIT_FAILURE;
1762 }
1763
Andreas Gampe10e477d2014-11-19 12:57:42 -08001764 // FlushClose again, as stripping might have re-opened the oat file.
1765 if (!dex2oat.FlushCloseOatFile()) {
1766 return EXIT_FAILURE;
1767 }
1768
1769 dex2oat.DumpTiming();
1770 return EXIT_SUCCESS;
1771}
1772
1773static int CompileApp(Dex2Oat& dex2oat) {
1774 dex2oat.Compile();
1775
1776 // Create the app oat.
1777 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001778 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001779 return EXIT_FAILURE;
1780 }
1781
1782 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1783 // which we would lose.
1784 if (!dex2oat.FlushOatFile()) {
1785 return EXIT_FAILURE;
1786 }
1787
1788 // When given --host, finish early without stripping.
1789 if (dex2oat.IsHost()) {
1790 if (!dex2oat.FlushCloseOatFile()) {
1791 return EXIT_FAILURE;
1792 }
1793
1794 dex2oat.DumpTiming();
1795 return EXIT_SUCCESS;
1796 }
1797
1798 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1799 // unstripped version. If this is given, we expect to be able to open writable files by name.
1800 if (!dex2oat.CopyUnstrippedToStripped()) {
1801 return EXIT_FAILURE;
1802 }
1803
Andreas Gampe10e477d2014-11-19 12:57:42 -08001804 // Flush and close the file.
1805 if (!dex2oat.FlushCloseOatFile()) {
1806 return EXIT_FAILURE;
1807 }
1808
1809 dex2oat.DumpTiming();
1810 return EXIT_SUCCESS;
1811}
1812
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001813static int dex2oat(int argc, char** argv) {
1814 b13564922();
1815
1816 TimingLogger timings("compiler", false, false);
1817
1818 Dex2Oat dex2oat(&timings);
1819
1820 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1821 dex2oat.ParseArgs(argc, argv);
1822
1823 // Check early that the result of compilation can be written
1824 if (!dex2oat.OpenFile()) {
1825 return EXIT_FAILURE;
1826 }
1827
1828 LOG(INFO) << CommandLine();
1829
1830 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001831 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001832 return EXIT_FAILURE;
1833 }
1834
Andreas Gampe10e477d2014-11-19 12:57:42 -08001835 if (dex2oat.IsImage()) {
1836 return CompileImage(dex2oat);
1837 } else {
1838 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001839 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001840}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001841} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001842
1843int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001844 int result = art::dex2oat(argc, argv);
1845 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1846 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1847 // should not destruct the runtime in this case.
1848 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1849 exit(result);
1850 }
1851 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001852}