blob: d727e0a252dd15fb0b418047ff8e605f1c9ac9d8 [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"
Andreas Gampe794ad762015-02-23 08:12:24 -080039#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "base/stl_util.h"
41#include "base/stringpiece.h"
42#include "base/timing_logger.h"
43#include "base/unix_file/fd_file.h"
44#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000045#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000046#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080048#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000049#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070050#include "dex/quick_compiler_callbacks.h"
51#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080053#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080054#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070055#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "gc/space/image_space.h"
57#include "gc/space/space-inl.h"
58#include "image_writer.h"
59#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070060#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/class-inl.h"
62#include "mirror/class_loader.h"
63#include "mirror/object-inl.h"
64#include "mirror/object_array-inl.h"
65#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "os.h"
67#include "runtime.h"
68#include "ScopedLocalRef.h"
69#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070070#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071#include "vector_output_stream.h"
72#include "well_known_classes.h"
73#include "zip_archive.h"
74
75namespace art {
76
Brian Carlstrom6449c622014-02-10 23:48:36 -080077static int original_argc;
78static char** original_argv;
79
80static std::string CommandLine() {
81 std::vector<std::string> command;
82 for (int i = 0; i < original_argc; ++i) {
83 command.push_back(original_argv[i]);
84 }
85 return Join(command, ' ');
86}
87
Brian Carlstrom7940e442013-07-12 13:46:57 -070088static void UsageErrorV(const char* fmt, va_list ap) {
89 std::string error;
90 StringAppendV(&error, fmt, ap);
91 LOG(ERROR) << error;
92}
93
94static void UsageError(const char* fmt, ...) {
95 va_list ap;
96 va_start(ap, fmt);
97 UsageErrorV(fmt, ap);
98 va_end(ap);
99}
100
Andreas Gampe794ad762015-02-23 08:12:24 -0800101NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102 va_list ap;
103 va_start(ap, fmt);
104 UsageErrorV(fmt, ap);
105 va_end(ap);
106
Brian Carlstrom6449c622014-02-10 23:48:36 -0800107 UsageError("Command: %s", CommandLine().c_str());
108
Brian Carlstrom7940e442013-07-12 13:46:57 -0700109 UsageError("Usage: dex2oat [options]...");
110 UsageError("");
111 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
112 UsageError(" Example: --dex-file=/system/framework/core.jar");
113 UsageError("");
114 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
115 UsageError(" containing a classes.dex file to compile.");
116 UsageError(" Example: --zip-fd=5");
117 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700118 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
119 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
121 UsageError("");
122 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
123 UsageError(" Example: --oat-file=/system/framework/boot.oat");
124 UsageError("");
125 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900126 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127 UsageError("");
128 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
129 UsageError(" to the file descriptor specified by --oat-fd.");
130 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
131 UsageError("");
132 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
133 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
134 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700135 UsageError(" --image=<file.art>: specifies the output image filename.");
136 UsageError(" Example: --image=/system/framework/boot.art");
137 UsageError("");
138 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
139 UsageError(" Example: --image=frameworks/base/preloaded-classes");
140 UsageError("");
141 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
142 UsageError(" Example: --base=0x50000000");
143 UsageError("");
144 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
145 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000146 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError("");
148 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
149 UsageError(" Example: --android-root=out/host/linux-x86");
150 UsageError(" Default: $ANDROID_ROOT");
151 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800152 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700153 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 UsageError(" Example: --instruction-set=x86");
155 UsageError(" Default: arm");
156 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700157 UsageError(" --instruction-set-features=...,: Specify instruction set features");
158 UsageError(" Example: --instruction-set-features=div");
159 UsageError(" Default: default");
160 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700161 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
162 UsageError(" Default: disabled");
163 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800164 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800166 UsageError(" Example: --compiler-backend=Optimizing");
167 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000168 UsageError(" Default: Optimizing");
169 } else {
170 UsageError(" Default: Quick");
171 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100173 UsageError(" --compiler-filter="
174 "(verify-none"
175 "|interpret-only"
176 "|space"
177 "|balanced"
178 "|speed"
179 "|everything"
180 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700181 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800182 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800183 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800184 UsageError("");
185 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
186 UsageError(" method for compiler filter tuning.");
187 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
188 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
189 UsageError("");
190 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
191 UsageError(" method for compiler filter tuning.");
192 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
193 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError("");
195 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
196 UsageError(" method for compiler filter tuning.");
197 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
198 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
199 UsageError("");
200 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
201 UsageError(" method for compiler filter tuning.");
202 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
203 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
204 UsageError("");
205 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
206 UsageError(" method for compiler filter tuning.");
207 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
208 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
209 UsageError("");
210 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
211 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700212 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
213 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800214 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
215 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700217 UsageError(" --dump-timing: display a breakdown of where time was spent");
218 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700219 UsageError(" --include-patch-information: Include patching information so the generated code");
220 UsageError(" can have its base address moved without full recompilation.");
221 UsageError("");
222 UsageError(" --no-include-patch-information: Do not include patching information.");
223 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700224 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
225 UsageError("");
226 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
227 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
229 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
230 UsageError(" Use a separate --runtime-arg switch for each argument.");
231 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700232 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000233 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700235 UsageError(" --print-pass-names: print a list of pass names");
236 UsageError("");
237 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
238 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
239 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700240 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
241 "with the setting.");
242 UsageError(" Will print default if no overridden setting exists.");
243 UsageError("");
244 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
245 "Pass2Name:Pass2OptionName:Pass2Option#");
246 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
247 UsageError(" Separator used between options is a comma.");
248 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800249 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
250 UsageError(" Example: --swap-file=/data/tmp/swap.001");
251 UsageError("");
252 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
253 UsageError(" Example: --swap-fd=10");
254 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 std::cerr << "See log for usage error information\n";
256 exit(EXIT_FAILURE);
257}
258
Brian Carlstrom7940e442013-07-12 13:46:57 -0700259// The primary goal of the watchdog is to prevent stuck build servers
260// during development when fatal aborts lead to a cascade of failures
261// that result in a deadlock.
262class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800263// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700264#undef CHECK_PTHREAD_CALL
265#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
266 do { \
267 int rc = call args; \
268 if (rc != 0) { \
269 errno = rc; \
270 std::string message(# call); \
271 message += " failed for "; \
272 message += reason; \
273 Fatal(message); \
274 } \
275 } while (false)
276
277 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700278 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 is_watch_dog_enabled_ = is_watch_dog_enabled;
280 if (!is_watch_dog_enabled_) {
281 return;
282 }
283 shutting_down_ = false;
284 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700285 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
286 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
290 }
291 ~WatchDog() {
292 if (!is_watch_dog_enabled_) {
293 return;
294 }
295 const char* reason = "dex2oat watch dog thread shutdown";
296 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
297 shutting_down_ = true;
298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
300
Kenny Root51316382014-05-13 14:59:37 -0700301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700302
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
305 }
306
307 private:
308 static void* CallBack(void* arg) {
309 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
310 ::art::SetThreadName("dex2oat watch dog");
311 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700312 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313 }
314
315 static void Message(char severity, const std::string& message) {
316 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
317 // cases.
318 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
319 kIsDebugBuild ? "d" : "",
320 severity,
321 getpid(),
322 GetTid(),
323 message.c_str());
324 }
325
Andreas Gampe794ad762015-02-23 08:12:24 -0800326 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 Message('F', message);
328 exit(1);
329 }
330
331 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700332 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
333 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800334 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 timespec timeout_ts;
336 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
337 const char* reason = "dex2oat watch dog thread waiting";
338 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
339 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800340 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800342 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 } else if (rc != 0) {
344 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
345 strerror(errno)));
346 Fatal(message.c_str());
347 }
348 }
349 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
350 }
351
352 // 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 -0700353 // Debug builds are slower so they have larger timeouts.
354 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800355
Elliott Hughes956af0f2014-12-11 14:34:28 -0800356 // 6 minutes scaled by kSlowdownFactor.
357 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358
359 bool is_watch_dog_enabled_;
360 bool shutting_down_;
361 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
362 pthread_mutex_t mutex_;
363 pthread_cond_t cond_;
364 pthread_attr_t attr_;
365 pthread_t pthread_;
366};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800368static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100369 std::string::size_type colon = s.find(c);
370 if (colon == std::string::npos) {
371 Usage("Missing char %c in option %s\n", c, s.c_str());
372 }
373 // Add one to remove the char we were trimming until.
374 *parsed_value = s.substr(colon + 1);
375}
376
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800377static void ParseDouble(const std::string& option, char after_char, double min, double max,
378 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100379 std::string substring;
380 ParseStringAfterChar(option, after_char, &substring);
381 bool sane_val = true;
382 double value;
383 if (false) {
384 // TODO: this doesn't seem to work on the emulator. b/15114595
385 std::stringstream iss(substring);
386 iss >> value;
387 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
388 sane_val = iss.eof() && (value >= min) && (value <= max);
389 } else {
390 char* end = nullptr;
391 value = strtod(substring.c_str(), &end);
392 sane_val = *end == '\0' && value >= min && value <= max;
393 }
394 if (!sane_val) {
395 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
396 }
397 *parsed_value = value;
398}
399
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800400static constexpr size_t kMinDexFilesForSwap = 2;
401static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
402
403static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
404 if (is_image) {
405 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
406 return false;
407 }
408 if (dex_files.size() < kMinDexFilesForSwap) {
409 // If there are less dex files than the threshold, assume it's gonna be fine.
410 return false;
411 }
412 size_t dex_files_size = 0;
413 for (const auto* dex_file : dex_files) {
414 dex_files_size += dex_file->GetHeader().file_size_;
415 }
416 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
417}
418
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800419class Dex2Oat FINAL {
420 public:
421 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800422 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800423 instruction_set_(kRuntimeISA),
424 // Take the default set of instruction features from the build.
425 method_inliner_map_(),
426 runtime_(nullptr),
427 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
428 start_ns_(NanoTime()),
429 oat_fd_(-1),
430 zip_fd_(-1),
431 image_base_(0U),
432 image_classes_zip_filename_(nullptr),
433 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800434 compiled_classes_zip_filename_(nullptr),
435 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800436 image_(false),
437 is_host_(false),
438 dump_stats_(false),
439 dump_passes_(false),
440 dump_timing_(false),
441 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800442 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800443 timings_(timings) {}
444
445 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800446 // Free opened dex files before deleting the runtime_, because ~DexFile
447 // uses MemMap, which is shut down by ~Runtime.
448 class_path_files_.clear();
449 opened_dex_files_.clear();
450
451 // Log completion time before deleting the runtime_, because this accesses
452 // the runtime.
453 LogCompletionTime();
454
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
456 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100457 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 }
459
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800460 // Parse the arguments from the command line. In case of an unrecognized option or impossible
461 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
462 // returns, arguments have been successfully parsed.
463 void ParseArgs(int argc, char** argv) {
464 original_argc = argc;
465 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700466
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700468
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469 // Skip over argv[0].
470 argv++;
471 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700472
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800473 if (argc == 0) {
474 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476
477 std::string oat_symbols;
478 std::string boot_image_filename;
479 const char* compiler_filter_string = nullptr;
480 bool compile_pic = false;
481 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
482 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
483 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
484 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
485 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
486
487 // Profile file to use
488 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
489
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800490 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
491 bool include_debug_symbols = kIsDebugBuild;
492 bool watch_dog_enabled = true;
493 bool generate_gdb_information = kIsDebugBuild;
494
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800495 PassManagerOptions pass_manager_options;
496
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800497 std::string error_msg;
498
499 for (int i = 0; i < argc; i++) {
500 const StringPiece option(argv[i]);
501 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 if (log_options) {
503 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
504 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505 if (option.starts_with("--dex-file=")) {
506 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
507 } else if (option.starts_with("--dex-location=")) {
508 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
509 } else if (option.starts_with("--zip-fd=")) {
510 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
511 if (!ParseInt(zip_fd_str, &zip_fd_)) {
512 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
513 }
514 if (zip_fd_ < 0) {
515 Usage("--zip-fd passed a negative value %d", zip_fd_);
516 }
517 } else if (option.starts_with("--zip-location=")) {
518 zip_location_ = option.substr(strlen("--zip-location=")).data();
519 } else if (option.starts_with("--oat-file=")) {
520 oat_filename_ = option.substr(strlen("--oat-file=")).data();
521 } else if (option.starts_with("--oat-symbols=")) {
522 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
523 } else if (option.starts_with("--oat-fd=")) {
524 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
525 if (!ParseInt(oat_fd_str, &oat_fd_)) {
526 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
527 }
528 if (oat_fd_ < 0) {
529 Usage("--oat-fd passed a negative value %d", oat_fd_);
530 }
531 } else if (option == "--watch-dog") {
532 watch_dog_enabled = true;
533 } else if (option == "--no-watch-dog") {
534 watch_dog_enabled = false;
535 } else if (option == "--gen-gdb-info") {
536 generate_gdb_information = true;
537 // Debug symbols are needed for gdb information.
538 include_debug_symbols = true;
539 } else if (option == "--no-gen-gdb-info") {
540 generate_gdb_information = false;
541 } else if (option.starts_with("-j")) {
542 const char* thread_count_str = option.substr(strlen("-j")).data();
543 if (!ParseUint(thread_count_str, &thread_count_)) {
544 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
545 }
546 } else if (option.starts_with("--oat-location=")) {
547 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800548 } else if (option.starts_with("--image=")) {
549 image_filename_ = option.substr(strlen("--image=")).data();
550 } else if (option.starts_with("--image-classes=")) {
551 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
552 } else if (option.starts_with("--image-classes-zip=")) {
553 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800554 } else if (option.starts_with("--compiled-classes=")) {
555 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
556 } else if (option.starts_with("--compiled-classes-zip=")) {
557 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800558 } else if (option.starts_with("--base=")) {
559 const char* image_base_str = option.substr(strlen("--base=")).data();
560 char* end;
561 image_base_ = strtoul(image_base_str, &end, 16);
562 if (end == image_base_str || *end != '\0') {
563 Usage("Failed to parse hexadecimal value for option %s", option.data());
564 }
565 } else if (option.starts_with("--boot-image=")) {
566 boot_image_filename = option.substr(strlen("--boot-image=")).data();
567 } else if (option.starts_with("--android-root=")) {
568 android_root_ = option.substr(strlen("--android-root=")).data();
569 } else if (option.starts_with("--instruction-set=")) {
570 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
571 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800572 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800573 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
574 buf.get()[instruction_set_str.length()] = 0;
575 instruction_set_ = GetInstructionSetFromString(buf.get());
576 // arm actually means thumb2.
577 if (instruction_set_ == InstructionSet::kArm) {
578 instruction_set_ = InstructionSet::kThumb2;
579 }
580 } else if (option.starts_with("--instruction-set-variant=")) {
581 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
582 instruction_set_features_.reset(
583 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
584 if (instruction_set_features_.get() == nullptr) {
585 Usage("%s", error_msg.c_str());
586 }
587 } else if (option.starts_with("--instruction-set-features=")) {
588 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800589 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800590 instruction_set_features_.reset(
591 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
592 if (instruction_set_features_.get() == nullptr) {
593 Usage("Problem initializing default instruction set features variant: %s",
594 error_msg.c_str());
595 }
596 }
597 instruction_set_features_.reset(
598 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
599 if (instruction_set_features_.get() == nullptr) {
600 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800601 }
602 } else if (option.starts_with("--compiler-backend=")) {
603 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
604 if (backend_str == "Quick") {
605 compiler_kind_ = Compiler::kQuick;
606 } else if (backend_str == "Optimizing") {
607 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800608 } else {
609 Usage("Unknown compiler backend: %s", backend_str.data());
610 }
611 } else if (option.starts_with("--compiler-filter=")) {
612 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
613 } else if (option == "--compile-pic") {
614 compile_pic = true;
615 } else if (option.starts_with("--huge-method-max=")) {
616 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
617 if (!ParseInt(threshold, &huge_method_threshold)) {
618 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
619 }
620 if (huge_method_threshold < 0) {
621 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
622 }
623 } else if (option.starts_with("--large-method-max=")) {
624 const char* threshold = option.substr(strlen("--large-method-max=")).data();
625 if (!ParseInt(threshold, &large_method_threshold)) {
626 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
627 }
628 if (large_method_threshold < 0) {
629 Usage("--large-method-max passed a negative value %s", large_method_threshold);
630 }
631 } else if (option.starts_with("--small-method-max=")) {
632 const char* threshold = option.substr(strlen("--small-method-max=")).data();
633 if (!ParseInt(threshold, &small_method_threshold)) {
634 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
635 }
636 if (small_method_threshold < 0) {
637 Usage("--small-method-max passed a negative value %s", small_method_threshold);
638 }
639 } else if (option.starts_with("--tiny-method-max=")) {
640 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
641 if (!ParseInt(threshold, &tiny_method_threshold)) {
642 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
643 }
644 if (tiny_method_threshold < 0) {
645 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
646 }
647 } else if (option.starts_with("--num-dex-methods=")) {
648 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
649 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
650 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
651 }
652 if (num_dex_methods_threshold < 0) {
653 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
654 }
655 } else if (option == "--host") {
656 is_host_ = true;
657 } else if (option == "--runtime-arg") {
658 if (++i >= argc) {
659 Usage("Missing required argument for --runtime-arg");
660 }
661 if (log_options) {
662 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
663 }
664 runtime_args_.push_back(argv[i]);
665 } else if (option == "--dump-timing") {
666 dump_timing_ = true;
667 } else if (option == "--dump-passes") {
668 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000669 } else if (option.starts_with("--dump-cfg=")) {
670 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800671 } else if (option == "--dump-stats") {
672 dump_stats_ = true;
673 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
674 include_debug_symbols = true;
675 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
676 include_debug_symbols = false;
677 generate_gdb_information = false; // Depends on debug symbols, see above.
678 } else if (option.starts_with("--profile-file=")) {
679 profile_file_ = option.substr(strlen("--profile-file=")).data();
680 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
681 } else if (option == "--no-profile-file") {
682 // No profile
683 } else if (option.starts_with("--top-k-profile-threshold=")) {
684 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
685 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800686 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800687 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800688 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
689 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800691 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
692 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800693 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800694 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800695 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800696 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
697 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800698 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800699 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800700 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800701 const std::string options = option.substr(strlen("--pass-options=")).data();
702 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800703 } else if (option == "--include-patch-information") {
704 include_patch_information = true;
705 } else if (option == "--no-include-patch-information") {
706 include_patch_information = false;
707 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800708 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
709 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 gLogVerbosity.compiler = false;
711 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800712 } else if (option.starts_with("--dump-init-failures=")) {
713 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
714 init_failure_output_.reset(new std::ofstream(file_name));
715 if (init_failure_output_.get() == nullptr) {
716 LOG(ERROR) << "Failed to allocate ofstream";
717 } else if (init_failure_output_->fail()) {
718 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
719 << "failures.";
720 init_failure_output_.reset();
721 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800722 } else if (option.starts_with("--swap-file=")) {
723 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
724 } else if (option.starts_with("--swap-fd=")) {
725 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
726 if (!ParseInt(swap_fd_str, &swap_fd_)) {
727 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
728 }
729 if (swap_fd_ < 0) {
730 Usage("--swap-fd passed a negative value %d", swap_fd_);
731 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800732 } else {
733 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800735 }
736
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000737 if (compiler_kind_ == Compiler::kOptimizing) {
738 // Optimizing only supports PIC mode.
739 compile_pic = true;
740 }
741
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800742 if (oat_filename_.empty() && oat_fd_ == -1) {
743 Usage("Output must be supplied with either --oat-file or --oat-fd");
744 }
745
746 if (!oat_filename_.empty() && oat_fd_ != -1) {
747 Usage("--oat-file should not be used with --oat-fd");
748 }
749
750 if (!oat_symbols.empty() && oat_fd_ != -1) {
751 Usage("--oat-symbols should not be used with --oat-fd");
752 }
753
754 if (!oat_symbols.empty() && is_host_) {
755 Usage("--oat-symbols should not be used with --host");
756 }
757
758 if (oat_fd_ != -1 && !image_filename_.empty()) {
759 Usage("--oat-fd should not be used with --image");
760 }
761
762 if (android_root_.empty()) {
763 const char* android_root_env_var = getenv("ANDROID_ROOT");
764 if (android_root_env_var == nullptr) {
765 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800767 android_root_ += android_root_env_var;
768 }
769
770 image_ = (!image_filename_.empty());
771 if (!image_ && boot_image_filename.empty()) {
772 boot_image_filename += android_root_;
773 boot_image_filename += "/framework/boot.art";
774 }
775 if (!boot_image_filename.empty()) {
776 boot_image_option_ += "-Ximage:";
777 boot_image_option_ += boot_image_filename;
778 }
779
780 if (image_classes_filename_ != nullptr && !image_) {
781 Usage("--image-classes should only be used with --image");
782 }
783
784 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
785 Usage("--image-classes should not be used with --boot-image");
786 }
787
788 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
789 Usage("--image-classes-zip should be used with --image-classes");
790 }
791
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800792 if (compiled_classes_filename_ != nullptr && !image_) {
793 Usage("--compiled-classes should only be used with --image");
794 }
795
796 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
797 Usage("--compiled-classes should not be used with --boot-image");
798 }
799
800 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
801 Usage("--compiled-classes-zip should be used with --compiled-classes");
802 }
803
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800804 if (dex_filenames_.empty() && zip_fd_ == -1) {
805 Usage("Input must be supplied with either --dex-file or --zip-fd");
806 }
807
808 if (!dex_filenames_.empty() && zip_fd_ != -1) {
809 Usage("--dex-file should not be used with --zip-fd");
810 }
811
812 if (!dex_filenames_.empty() && !zip_location_.empty()) {
813 Usage("--dex-file should not be used with --zip-location");
814 }
815
816 if (dex_locations_.empty()) {
817 for (const char* dex_file_name : dex_filenames_) {
818 dex_locations_.push_back(dex_file_name);
819 }
820 } else if (dex_locations_.size() != dex_filenames_.size()) {
821 Usage("--dex-location arguments do not match --dex-file arguments");
822 }
823
824 if (zip_fd_ != -1 && zip_location_.empty()) {
825 Usage("--zip-location should be supplied with --zip-fd");
826 }
827
828 if (boot_image_option_.empty()) {
829 if (image_base_ == 0) {
830 Usage("Non-zero --base not specified");
831 }
832 }
833
834 oat_stripped_ = oat_filename_;
835 if (!oat_symbols.empty()) {
836 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800838 oat_unstripped_ = oat_filename_;
839 }
840
841 // If no instruction set feature was given, use the default one for the target
842 // instruction set.
843 if (instruction_set_features_.get() == nullptr) {
844 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800845 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
846 if (instruction_set_features_.get() == nullptr) {
847 Usage("Problem initializing default instruction set features variant: %s",
848 error_msg.c_str());
849 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800850 }
851
852 if (instruction_set_ == kRuntimeISA) {
853 std::unique_ptr<const InstructionSetFeatures> runtime_features(
854 InstructionSetFeatures::FromCppDefines());
855 if (!instruction_set_features_->Equals(runtime_features.get())) {
856 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
857 << *instruction_set_features_ << ") and those of dex2oat executable ("
858 << *runtime_features <<") for the command line:\n"
859 << CommandLine();
860 }
861 }
862
863 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800864 if (instruction_set_ == kMips &&
865 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
866 IsR6()) {
867 // For R6, only interpreter mode is working.
868 // TODO: fix compiler for Mips32r6.
869 compiler_filter_string = "interpret-only";
870 } else if (instruction_set_ == kMips64) {
Andreas Gampe57b34292015-01-14 15:45:59 -0800871 // For Mips64, can only compile in interpreter mode.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800872 // TODO: fix compiler for Mips64.
873 compiler_filter_string = "interpret-only";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800874 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800875 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800876 }
877 }
878 CHECK(compiler_filter_string != nullptr);
879 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
880 if (strcmp(compiler_filter_string, "verify-none") == 0) {
881 compiler_filter = CompilerOptions::kVerifyNone;
882 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
883 compiler_filter = CompilerOptions::kInterpretOnly;
884 } else if (strcmp(compiler_filter_string, "space") == 0) {
885 compiler_filter = CompilerOptions::kSpace;
886 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
887 compiler_filter = CompilerOptions::kBalanced;
888 } else if (strcmp(compiler_filter_string, "speed") == 0) {
889 compiler_filter = CompilerOptions::kSpeed;
890 } else if (strcmp(compiler_filter_string, "everything") == 0) {
891 compiler_filter = CompilerOptions::kEverything;
892 } else if (strcmp(compiler_filter_string, "time") == 0) {
893 compiler_filter = CompilerOptions::kTime;
894 } else {
895 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
896 }
897
898 // Checks are all explicit until we know the architecture.
899 bool implicit_null_checks = false;
900 bool implicit_so_checks = false;
901 bool implicit_suspend_checks = false;
902 // Set the compilation target's implicit checks options.
903 switch (instruction_set_) {
904 case kArm:
905 case kThumb2:
906 case kArm64:
907 case kX86:
908 case kX86_64:
909 implicit_null_checks = true;
910 implicit_so_checks = true;
911 break;
912
913 default:
914 // Defaults are correct.
915 break;
916 }
917
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800918 compiler_options_.reset(new CompilerOptions(compiler_filter,
919 huge_method_threshold,
920 large_method_threshold,
921 small_method_threshold,
922 tiny_method_threshold,
923 num_dex_methods_threshold,
924 generate_gdb_information,
925 include_patch_information,
926 top_k_profile_threshold,
927 include_debug_symbols,
928 implicit_null_checks,
929 implicit_so_checks,
930 implicit_suspend_checks,
931 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800932 verbose_methods_.empty() ?
933 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800934 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800935 new PassManagerOptions(pass_manager_options),
Andreas Gampedbfe2542014-11-25 22:21:42 -0800936 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800937
938 // Done with usage checks, enable watchdog if requested
939 if (watch_dog_enabled) {
940 watchdog_.reset(new WatchDog(true));
941 }
942
943 // Fill some values into the key-value store for the oat header.
944 key_value_store_.reset(new SafeMap<std::string, std::string>());
945
946 // Insert some compiler things.
947 {
948 std::ostringstream oss;
949 for (int i = 0; i < argc; ++i) {
950 if (i > 0) {
951 oss << ' ';
952 }
953 oss << argv[i];
954 }
955 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
956 oss.str(""); // Reset.
957 oss << kRuntimeISA;
958 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
959 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
960 }
961 }
962
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800963 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
964 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800965 bool OpenFile() {
966 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
967 if (create_file) {
968 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
969 if (oat_location_.empty()) {
970 oat_location_ = oat_filename_;
971 }
972 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800973 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800974 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800975 if (oat_file_->SetLength(0) != 0) {
976 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
977 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800978 }
979 if (oat_file_.get() == nullptr) {
980 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
981 return false;
982 }
983 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
984 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800985 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 return false;
987 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800988
989 // Swap file handling.
990 //
991 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
992 // that we can use for swap.
993 //
994 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
995 // will immediately unlink to satisfy the swap fd assumption.
996 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
997 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
998 if (swap_file.get() == nullptr) {
999 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1000 return false;
1001 }
1002 swap_fd_ = swap_file->Fd();
1003 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1004 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1005 // released immediately.
1006 unlink(swap_file_name_.c_str());
1007 }
1008
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001009 return true;
1010 }
1011
Andreas Gampea650e702014-12-03 14:28:02 -08001012 void EraseOatFile() {
1013 DCHECK(oat_file_.get() != nullptr);
1014 oat_file_->Erase();
1015 oat_file_.reset();
1016 }
1017
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001018 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1019 // boot class path.
1020 bool Setup() {
1021 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1022 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001023 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1024 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001025 std::string boot_class_path = "-Xbootclasspath:";
1026 boot_class_path += Join(dex_filenames_, ':');
1027 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1028 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1029 boot_class_path_locations += Join(dex_locations_, ':');
1030 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001031 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001032 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001033 }
1034 for (size_t i = 0; i < runtime_args_.size(); i++) {
1035 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001036 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001037
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001038 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1039 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1040 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1041 runtime_options.push_back(
1042 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1043
1044 if (!CreateRuntime(runtime_options)) {
1045 return false;
1046 }
1047
1048 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1049 // Runtime::Start, give it away now so that we don't starve GC.
1050 Thread* self = Thread::Current();
1051 self->TransitionFromRunnableToSuspended(kNative);
1052 // If we're doing the image, override the compiler filter to force full compilation. Must be
1053 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1054 // compilation of class initializers.
1055 // Whilst we're in native take the opportunity to initialize well known classes.
1056 WellKnownClasses::Init(self->GetJniEnv());
1057
1058 // If --image-classes was specified, calculate the full list of classes to include in the image
1059 if (image_classes_filename_ != nullptr) {
1060 std::string error_msg;
1061 if (image_classes_zip_filename_ != nullptr) {
1062 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1063 image_classes_filename_,
1064 &error_msg));
1065 } else {
1066 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1067 }
1068 if (image_classes_.get() == nullptr) {
1069 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1070 "': " << error_msg;
1071 return false;
1072 }
1073 } else if (image_) {
1074 image_classes_.reset(new std::set<std::string>);
1075 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001076 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1077 // image.
1078 if (compiled_classes_filename_ != nullptr) {
1079 std::string error_msg;
1080 if (compiled_classes_zip_filename_ != nullptr) {
1081 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1082 compiled_classes_filename_,
1083 &error_msg));
1084 } else {
1085 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1086 }
1087 if (compiled_classes_.get() == nullptr) {
1088 LOG(ERROR) << "Failed to create list of compiled classes from '"
1089 << compiled_classes_filename_ << "': " << error_msg;
1090 return false;
1091 }
1092 } else if (image_) {
1093 compiled_classes_.reset(nullptr); // By default compile everything.
1094 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001095
1096 if (boot_image_option_.empty()) {
1097 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1098 } else {
1099 if (dex_filenames_.empty()) {
1100 ATRACE_BEGIN("Opening zip archive from file descriptor");
1101 std::string error_msg;
1102 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1103 zip_location_.c_str(),
1104 &error_msg));
1105 if (zip_archive.get() == nullptr) {
1106 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1107 << error_msg;
1108 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001109 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001110 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001111 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1112 << "': " << error_msg;
1113 return false;
1114 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001115 for (auto& dex_file : opened_dex_files_) {
1116 dex_files_.push_back(dex_file.get());
1117 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001118 ATRACE_END();
1119 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001120 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001121 if (failure_count > 0) {
1122 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1123 return false;
1124 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001125 for (auto& dex_file : opened_dex_files_) {
1126 dex_files_.push_back(dex_file.get());
1127 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001128 }
1129
1130 constexpr bool kSaveDexInput = false;
1131 if (kSaveDexInput) {
1132 for (size_t i = 0; i < dex_files_.size(); ++i) {
1133 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001134 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1135 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001136 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1137 if (tmp_file.get() == nullptr) {
1138 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1139 << ". Try: adb shell chmod 777 /data/local/tmp";
1140 continue;
1141 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001142 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1143 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1144 UNUSED(tmp_file->Flush());
1145 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001146 LOG(INFO) << "Wrote input to " << tmp_file_name;
1147 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001148 }
1149 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001150 // Ensure opened dex files are writable for dex-to-dex transformations.
1151 for (const auto& dex_file : dex_files_) {
1152 if (!dex_file->EnableWrite()) {
1153 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001154 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001155 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001156
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001157 // If we use a swap file, ensure we are above the threshold to make it necessary.
1158 if (swap_fd_ != -1) {
1159 if (!UseSwap(image_, dex_files_)) {
1160 close(swap_fd_);
1161 swap_fd_ = -1;
1162 LOG(INFO) << "Decided to run without swap.";
1163 } else {
1164 LOG(INFO) << "Accepted running with swap.";
1165 }
1166 }
1167 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1168
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001169 /*
1170 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1171 * Don't bother to check if we're doing the image.
1172 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001173 if (!image_ &&
1174 compiler_options_->IsCompilationEnabled() &&
1175 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001176 size_t num_methods = 0;
1177 for (size_t i = 0; i != dex_files_.size(); ++i) {
1178 const DexFile* dex_file = dex_files_[i];
1179 CHECK(dex_file != nullptr);
1180 num_methods += dex_file->NumMethodIds();
1181 }
1182 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1183 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1184 VLOG(compiler) << "Below method threshold, compiling anyways";
1185 }
1186 }
1187
1188 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001189 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001190
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001191 // Create and invoke the compiler driver. This will compile all the dex files.
1192 void Compile() {
1193 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1194 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001195
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001196 // Handle and ClassLoader creation needs to come after Runtime::Create
1197 jobject class_loader = nullptr;
1198 Thread* self = Thread::Current();
1199 if (!boot_image_option_.empty()) {
1200 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001201 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001202 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001203 std::vector<const DexFile*> class_path_files(dex_files_);
1204 for (auto& class_path_file : class_path_files_) {
1205 class_path_files.push_back(class_path_file.get());
1206 }
1207
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 for (size_t i = 0; i < class_path_files.size(); i++) {
1209 class_linker->RegisterDexFile(*class_path_files[i]);
1210 }
1211 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1212 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1213 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1214 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1215 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1216 }
1217
1218 driver_.reset(new CompilerDriver(compiler_options_.get(),
1219 verification_results_.get(),
1220 &method_inliner_map_,
1221 compiler_kind_,
1222 instruction_set_,
1223 instruction_set_features_.get(),
1224 image_,
1225 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001226 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001227 thread_count_,
1228 dump_stats_,
1229 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001230 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001231 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001232 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001233 profile_file_));
1234
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 }
1237
Brian Carlstrom7940e442013-07-12 13:46:57 -07001238 // Notes on the interleaving of creating the image and oat file to
1239 // ensure the references between the two are correct.
1240 //
1241 // Currently we have a memory layout that looks something like this:
1242 //
1243 // +--------------+
1244 // | image |
1245 // +--------------+
1246 // | boot oat |
1247 // +--------------+
1248 // | alloc spaces |
1249 // +--------------+
1250 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001251 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001252 //
1253 // 1. The image is expected to be loaded at an absolute address and
1254 // contains Objects with absolute pointers within the image.
1255 //
1256 // 2. There are absolute pointers from Methods in the image to their
1257 // code in the oat.
1258 //
1259 // 3. There are absolute pointers from the code in the oat to Methods
1260 // in the image.
1261 //
1262 // 4. There are absolute pointers from code in the oat to other code
1263 // in the oat.
1264 //
1265 // To get this all correct, we go through several steps.
1266 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001267 // 1. We prepare offsets for all data in the oat file and calculate
1268 // the oat data size and code size. During this stage, we also set
1269 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001270 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001271 // 2. We prepare offsets for the objects in the image and calculate
1272 // the image size.
1273 //
1274 // 3. We create the oat file. Originally this was just our own proprietary
1275 // file but now it is contained within an ELF dynamic object (aka an .so
1276 // file). Since we know the image size and oat data size and code size we
1277 // can prepare the ELF headers and we then know the ELF memory segment
1278 // layout and we can now resolve all references. The compiler provides
1279 // LinkerPatch information in each CompiledMethod and we resolve these,
1280 // using the layout information and image object locations provided by
1281 // image writer, as we're writing the method code.
1282 //
1283 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001284 // will be loaded after itself. Originally when oat file was simply
1285 // memory mapped so we could predict where its contents were based
1286 // on the file size. Now that it is an ELF file, we need to inspect
1287 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001288 // where the oat header is located within.
1289 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001290 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001291 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292 // load the .so at the desired location at runtime by offsetting the
1293 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001294 // TODO: Do this in step 3. We already know the layout there.
1295 //
1296 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1297 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001298
1299
1300 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1301 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001302 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1303 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001304 bool CreateOatFile() {
1305 CHECK(key_value_store_.get() != nullptr);
1306
1307 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1308
1309 std::unique_ptr<OatWriter> oat_writer;
1310 {
1311 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1312 std::string image_file_location;
1313 uint32_t image_file_location_oat_checksum = 0;
1314 uintptr_t image_file_location_oat_data_begin = 0;
1315 int32_t image_patch_delta = 0;
1316 if (image_) {
1317 PrepareImageWriter(image_base_);
1318 } else {
1319 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1320 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1321 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1322 image_file_location_oat_data_begin =
1323 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1324 image_file_location = image_space->GetImageFilename();
1325 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1326 }
1327
1328 if (!image_file_location.empty()) {
1329 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1330 }
1331
1332 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1333 image_file_location_oat_data_begin,
1334 image_patch_delta,
1335 driver_.get(),
1336 image_writer_.get(),
1337 timings_,
1338 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001339 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001340
1341 if (image_) {
1342 // The OatWriter constructor has already updated offsets in methods and we need to
1343 // prepare method offsets in the image address space for direct method patching.
1344 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1345 if (!image_writer_->PrepareImageAddressSpace()) {
1346 LOG(ERROR) << "Failed to prepare image address space.";
1347 return false;
1348 }
1349 }
1350
1351 {
1352 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1353 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1354 oat_file_.get())) {
1355 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1356 return false;
1357 }
1358 }
1359
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001360 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1361 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001362 }
1363
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001364 // If we are compiling an image, invoke the image creation routine. Else just skip.
1365 bool HandleImage() {
1366 if (image_) {
1367 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1368 if (!CreateImageFile()) {
1369 return false;
1370 }
1371 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001372 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001373 return true;
1374 }
1375
Andreas Gampe10e477d2014-11-19 12:57:42 -08001376 // Create a copy from unstripped to stripped.
1377 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001378 // If we don't want to strip in place, copy from unstripped location to stripped location.
1379 // We need to strip after image creation because FixupElf needs to use .strtab.
1380 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001381 // If the oat file is still open, flush it.
1382 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1383 if (!FlushCloseOatFile()) {
1384 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001385 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001386 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001387
1388 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001389 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1390 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1391 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001392 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393 while (true) {
1394 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1395 if (bytes_read <= 0) {
1396 break;
1397 }
1398 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1399 CHECK(write_ok);
1400 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001401 if (out->FlushCloseOrErase() != 0) {
1402 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1403 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001404 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001405 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001406 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001407 return true;
1408 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001409
Andreas Gampe10e477d2014-11-19 12:57:42 -08001410 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001411 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001412 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1413 if (oat_file_->Flush() != 0) {
1414 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1415 << oat_filename_;
1416 oat_file_->Erase();
1417 return false;
1418 }
1419 }
1420 return true;
1421 }
1422
1423 bool FlushCloseOatFile() {
1424 if (oat_file_.get() != nullptr) {
1425 std::unique_ptr<File> tmp(oat_file_.release());
1426 if (tmp->FlushCloseOrErase() != 0) {
1427 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1428 << oat_filename_;
1429 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001430 }
1431 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001432 return true;
1433 }
1434
1435 void DumpTiming() {
1436 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1437 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1438 }
1439 if (dump_passes_) {
1440 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1441 }
1442 }
1443
1444 CompilerOptions* GetCompilerOptions() const {
1445 return compiler_options_.get();
1446 }
1447
Andreas Gampe10e477d2014-11-19 12:57:42 -08001448 bool IsImage() const {
1449 return image_;
1450 }
1451
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001452 bool IsHost() const {
1453 return is_host_;
1454 }
1455
1456 private:
1457 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1458 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001459 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1460 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001461 size_t failure_count = 0;
1462 for (size_t i = 0; i < dex_filenames.size(); i++) {
1463 const char* dex_filename = dex_filenames[i];
1464 const char* dex_location = dex_locations[i];
1465 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1466 std::string error_msg;
1467 if (!OS::FileExists(dex_filename)) {
1468 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1469 continue;
1470 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001471 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001472 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1473 ++failure_count;
1474 }
1475 ATRACE_END();
1476 }
1477 return failure_count;
1478 }
1479
1480 // Returns true if dex_files has a dex with the named location.
1481 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1482 const std::string& location) {
1483 for (size_t i = 0; i < dex_files.size(); ++i) {
1484 if (dex_files[i]->GetLocation() == location) {
1485 return true;
1486 }
1487 }
1488 return false;
1489 }
1490
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001491 // Appends to opened_dex_files any elements of class_path that dex_files
1492 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001493 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001494 std::vector<const DexFile*> dex_files,
1495 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1496 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001497 std::vector<std::string> parsed;
1498 Split(class_path, ':', &parsed);
1499 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1500 ScopedObjectAccess soa(Thread::Current());
1501 for (size_t i = 0; i < parsed.size(); ++i) {
1502 if (DexFilesContains(dex_files, parsed[i])) {
1503 continue;
1504 }
1505 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001506 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001507 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1508 }
1509 }
1510 }
1511
1512 // Create a runtime necessary for compilation.
1513 bool CreateRuntime(const RuntimeOptions& runtime_options)
1514 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1515 if (!Runtime::Create(runtime_options, false)) {
1516 LOG(ERROR) << "Failed to create runtime";
1517 return false;
1518 }
1519 Runtime* runtime = Runtime::Current();
1520 runtime->SetInstructionSet(instruction_set_);
1521 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1522 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1523 if (!runtime->HasCalleeSaveMethod(type)) {
1524 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1525 }
1526 }
1527 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1528 runtime->GetClassLinker()->RunRootClinits();
1529 runtime_ = runtime;
1530 return true;
1531 }
1532
1533 void PrepareImageWriter(uintptr_t image_base) {
1534 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1535 }
1536
1537 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1538 bool CreateImageFile()
1539 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1540 CHECK(image_writer_ != nullptr);
1541 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1542 LOG(ERROR) << "Failed to create image file " << image_filename_;
1543 return false;
1544 }
1545 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1546
1547 // Destroy ImageWriter before doing FixupElf.
1548 image_writer_.reset();
1549
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001550 // Do not fix up the ELF file if we are --compile-pic
1551 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001552 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1553 if (oat_file.get() == nullptr) {
1554 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1555 return false;
1556 }
1557
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001558 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001559 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001560 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1561 return false;
1562 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001563
1564 if (oat_file->FlushCloseOrErase()) {
1565 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1566 return false;
1567 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001568 }
1569
1570 return true;
1571 }
1572
1573 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1574 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1575 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1576 std::ifstream::in));
1577 if (image_classes_file.get() == nullptr) {
1578 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1579 return nullptr;
1580 }
1581 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1582 image_classes_file->close();
1583 return result.release();
1584 }
1585
1586 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1587 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1588 while (image_classes_stream.good()) {
1589 std::string dot;
1590 std::getline(image_classes_stream, dot);
1591 if (StartsWith(dot, "#") || dot.empty()) {
1592 continue;
1593 }
1594 std::string descriptor(DotToDescriptor(dot.c_str()));
1595 image_classes->insert(descriptor);
1596 }
1597 return image_classes.release();
1598 }
1599
1600 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1601 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1602 const char* image_classes_filename,
1603 std::string* error_msg) {
1604 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1605 if (zip_archive.get() == nullptr) {
1606 return nullptr;
1607 }
1608 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1609 if (zip_entry.get() == nullptr) {
1610 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1611 zip_filename, error_msg->c_str());
1612 return nullptr;
1613 }
1614 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1615 image_classes_filename,
1616 error_msg));
1617 if (image_classes_file.get() == nullptr) {
1618 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1619 zip_filename, error_msg->c_str());
1620 return nullptr;
1621 }
1622 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1623 image_classes_file->Size());
1624 std::istringstream image_classes_stream(image_classes_string);
1625 return ReadImageClasses(image_classes_stream);
1626 }
1627
Mathieu Chartier49285c52014-12-02 15:43:48 -08001628 void LogCompletionTime() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001629 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001630 << " (threads: " << thread_count_ << ") "
Andreas Gampe8d295f82015-01-20 14:50:21 -08001631 << driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632 }
1633
1634 std::unique_ptr<CompilerOptions> compiler_options_;
1635 Compiler::Kind compiler_kind_;
1636
1637 InstructionSet instruction_set_;
1638 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1639
1640 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1641
1642 std::unique_ptr<VerificationResults> verification_results_;
1643 DexFileToMethodInlinerMap method_inliner_map_;
1644 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1645
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001646 // Ownership for the class path files.
1647 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1648
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001649 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1650 // in an orderly fashion. The destructor takes care of deleting this.
1651 Runtime* runtime_;
1652
1653 size_t thread_count_;
1654 uint64_t start_ns_;
1655 std::unique_ptr<WatchDog> watchdog_;
1656 std::unique_ptr<File> oat_file_;
1657 std::string oat_stripped_;
1658 std::string oat_unstripped_;
1659 std::string oat_location_;
1660 std::string oat_filename_;
1661 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001662 std::vector<const char*> dex_filenames_;
1663 std::vector<const char*> dex_locations_;
1664 int zip_fd_;
1665 std::string zip_location_;
1666 std::string boot_image_option_;
1667 std::vector<const char*> runtime_args_;
1668 std::string image_filename_;
1669 uintptr_t image_base_;
1670 const char* image_classes_zip_filename_;
1671 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001672 const char* compiled_classes_zip_filename_;
1673 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001674 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001675 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001676 bool image_;
1677 std::unique_ptr<ImageWriter> image_writer_;
1678 bool is_host_;
1679 std::string android_root_;
1680 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001681 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001682 std::unique_ptr<CompilerDriver> driver_;
1683 std::vector<std::string> verbose_methods_;
1684 bool dump_stats_;
1685 bool dump_passes_;
1686 bool dump_timing_;
1687 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001688 std::string dump_cfg_file_name_;
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}