blob: 06a3d3ff871b32980a20b655fa31f5f6a4db9926 [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"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070059#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070061#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/class-inl.h"
63#include "mirror/class_loader.h"
64#include "mirror/object-inl.h"
65#include "mirror/object_array-inl.h"
66#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "os.h"
68#include "runtime.h"
69#include "ScopedLocalRef.h"
70#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070071#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "vector_output_stream.h"
73#include "well_known_classes.h"
74#include "zip_archive.h"
75
76namespace art {
77
Brian Carlstrom6449c622014-02-10 23:48:36 -080078static int original_argc;
79static char** original_argv;
80
81static std::string CommandLine() {
82 std::vector<std::string> command;
83 for (int i = 0; i < original_argc; ++i) {
84 command.push_back(original_argv[i]);
85 }
86 return Join(command, ' ');
87}
88
Brian Carlstrom7940e442013-07-12 13:46:57 -070089static void UsageErrorV(const char* fmt, va_list ap) {
90 std::string error;
91 StringAppendV(&error, fmt, ap);
92 LOG(ERROR) << error;
93}
94
95static void UsageError(const char* fmt, ...) {
96 va_list ap;
97 va_start(ap, fmt);
98 UsageErrorV(fmt, ap);
99 va_end(ap);
100}
101
Andreas Gampe794ad762015-02-23 08:12:24 -0800102NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103 va_list ap;
104 va_start(ap, fmt);
105 UsageErrorV(fmt, ap);
106 va_end(ap);
107
Brian Carlstrom6449c622014-02-10 23:48:36 -0800108 UsageError("Command: %s", CommandLine().c_str());
109
Brian Carlstrom7940e442013-07-12 13:46:57 -0700110 UsageError("Usage: dex2oat [options]...");
111 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100112 UsageError(" -j<number>: specifies the number of threads used for compilation.");
113 UsageError(" Default is the number of detected hardware threads available on the");
114 UsageError(" host system.");
115 UsageError(" Example: -j12");
116 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700117 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 UsageError(" Example: --dex-file=/system/framework/core.jar");
119 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700120 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
121 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
122 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
123 UsageError(" --dex-location=/system/framework/core.jar");
124 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
126 UsageError(" containing a classes.dex file to compile.");
127 UsageError(" Example: --zip-fd=5");
128 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700129 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
130 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700131 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
132 UsageError("");
133 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
134 UsageError(" Example: --oat-file=/system/framework/boot.oat");
135 UsageError("");
136 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900137 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700138 UsageError("");
139 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
140 UsageError(" to the file descriptor specified by --oat-fd.");
141 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
142 UsageError("");
143 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
144 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
145 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700146 UsageError(" --image=<file.art>: specifies the output image filename.");
147 UsageError(" Example: --image=/system/framework/boot.art");
148 UsageError("");
149 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
150 UsageError(" Example: --image=frameworks/base/preloaded-classes");
151 UsageError("");
152 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
153 UsageError(" Example: --base=0x50000000");
154 UsageError("");
155 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
156 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000157 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700158 UsageError("");
159 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
160 UsageError(" Example: --android-root=out/host/linux-x86");
161 UsageError(" Default: $ANDROID_ROOT");
162 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800163 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700164 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 UsageError(" Example: --instruction-set=x86");
166 UsageError(" Default: arm");
167 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700168 UsageError(" --instruction-set-features=...,: Specify instruction set features");
169 UsageError(" Example: --instruction-set-features=div");
170 UsageError(" Default: default");
171 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700172 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
173 UsageError(" Default: disabled");
174 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800175 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800177 UsageError(" Example: --compiler-backend=Optimizing");
178 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000179 UsageError(" Default: Optimizing");
180 } else {
181 UsageError(" Default: Quick");
182 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100184 UsageError(" --compiler-filter="
185 "(verify-none"
186 "|interpret-only"
187 "|space"
188 "|balanced"
189 "|speed"
190 "|everything"
191 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700192 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800193 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800194 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800195 UsageError("");
196 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
197 UsageError(" method for compiler filter tuning.");
198 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
199 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
200 UsageError("");
201 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
202 UsageError(" method for compiler filter tuning.");
203 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
204 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
205 UsageError("");
206 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
207 UsageError(" method for compiler filter tuning.");
208 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
209 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
210 UsageError("");
211 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
212 UsageError(" method for compiler filter tuning.");
213 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
214 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
215 UsageError("");
216 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
217 UsageError(" method for compiler filter tuning.");
218 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
219 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
220 UsageError("");
221 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
222 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700223 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
224 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800225 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
226 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
227 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700228 UsageError(" --dump-timing: display a breakdown of where time was spent");
229 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700230 UsageError(" --include-patch-information: Include patching information so the generated code");
231 UsageError(" can have its base address moved without full recompilation.");
232 UsageError("");
233 UsageError(" --no-include-patch-information: Do not include patching information.");
234 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700235 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
236 UsageError("");
237 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
238 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
240 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
241 UsageError(" Use a separate --runtime-arg switch for each argument.");
242 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700243 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000244 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700246 UsageError(" --print-pass-names: print a list of pass names");
247 UsageError("");
248 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
249 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
250 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700251 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
252 "with the setting.");
253 UsageError(" Will print default if no overridden setting exists.");
254 UsageError("");
255 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
256 "Pass2Name:Pass2OptionName:Pass2Option#");
257 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
258 UsageError(" Separator used between options is a comma.");
259 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800260 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
261 UsageError(" Example: --swap-file=/data/tmp/swap.001");
262 UsageError("");
263 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
264 UsageError(" Example: --swap-fd=10");
265 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700266 std::cerr << "See log for usage error information\n";
267 exit(EXIT_FAILURE);
268}
269
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270// The primary goal of the watchdog is to prevent stuck build servers
271// during development when fatal aborts lead to a cascade of failures
272// that result in a deadlock.
273class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800274// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700275#undef CHECK_PTHREAD_CALL
276#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
277 do { \
278 int rc = call args; \
279 if (rc != 0) { \
280 errno = rc; \
281 std::string message(# call); \
282 message += " failed for "; \
283 message += reason; \
284 Fatal(message); \
285 } \
286 } while (false)
287
288 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700289 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 is_watch_dog_enabled_ = is_watch_dog_enabled;
291 if (!is_watch_dog_enabled_) {
292 return;
293 }
294 shutting_down_ = false;
295 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700296 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
297 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
301 }
302 ~WatchDog() {
303 if (!is_watch_dog_enabled_) {
304 return;
305 }
306 const char* reason = "dex2oat watch dog thread shutdown";
307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
308 shutting_down_ = true;
309 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
311
Kenny Root51316382014-05-13 14:59:37 -0700312 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313
314 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
315 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
316 }
317
318 private:
319 static void* CallBack(void* arg) {
320 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
321 ::art::SetThreadName("dex2oat watch dog");
322 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700323 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700324 }
325
326 static void Message(char severity, const std::string& message) {
327 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
328 // cases.
329 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
330 kIsDebugBuild ? "d" : "",
331 severity,
332 getpid(),
333 GetTid(),
334 message.c_str());
335 }
336
Andreas Gampe794ad762015-02-23 08:12:24 -0800337 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 Message('F', message);
339 exit(1);
340 }
341
342 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
344 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800345 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 timespec timeout_ts;
347 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
348 const char* reason = "dex2oat watch dog thread waiting";
349 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
350 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800351 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700352 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800353 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700354 } else if (rc != 0) {
355 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
356 strerror(errno)));
357 Fatal(message.c_str());
358 }
359 }
360 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
361 }
362
363 // 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 -0700364 // Debug builds are slower so they have larger timeouts.
365 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800366
Elliott Hughes956af0f2014-12-11 14:34:28 -0800367 // 6 minutes scaled by kSlowdownFactor.
368 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700369
370 bool is_watch_dog_enabled_;
371 bool shutting_down_;
372 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
373 pthread_mutex_t mutex_;
374 pthread_cond_t cond_;
375 pthread_attr_t attr_;
376 pthread_t pthread_;
377};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800379static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100380 std::string::size_type colon = s.find(c);
381 if (colon == std::string::npos) {
382 Usage("Missing char %c in option %s\n", c, s.c_str());
383 }
384 // Add one to remove the char we were trimming until.
385 *parsed_value = s.substr(colon + 1);
386}
387
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800388static void ParseDouble(const std::string& option, char after_char, double min, double max,
389 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100390 std::string substring;
391 ParseStringAfterChar(option, after_char, &substring);
392 bool sane_val = true;
393 double value;
394 if (false) {
395 // TODO: this doesn't seem to work on the emulator. b/15114595
396 std::stringstream iss(substring);
397 iss >> value;
398 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
399 sane_val = iss.eof() && (value >= min) && (value <= max);
400 } else {
401 char* end = nullptr;
402 value = strtod(substring.c_str(), &end);
403 sane_val = *end == '\0' && value >= min && value <= max;
404 }
405 if (!sane_val) {
406 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
407 }
408 *parsed_value = value;
409}
410
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800411static constexpr size_t kMinDexFilesForSwap = 2;
412static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
413
414static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
415 if (is_image) {
416 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
417 return false;
418 }
419 if (dex_files.size() < kMinDexFilesForSwap) {
420 // If there are less dex files than the threshold, assume it's gonna be fine.
421 return false;
422 }
423 size_t dex_files_size = 0;
424 for (const auto* dex_file : dex_files) {
425 dex_files_size += dex_file->GetHeader().file_size_;
426 }
427 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
428}
429
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800430class Dex2Oat FINAL {
431 public:
432 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800433 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800434 instruction_set_(kRuntimeISA),
435 // Take the default set of instruction features from the build.
436 method_inliner_map_(),
437 runtime_(nullptr),
438 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
439 start_ns_(NanoTime()),
440 oat_fd_(-1),
441 zip_fd_(-1),
442 image_base_(0U),
443 image_classes_zip_filename_(nullptr),
444 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800445 compiled_classes_zip_filename_(nullptr),
446 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800447 image_(false),
448 is_host_(false),
449 dump_stats_(false),
450 dump_passes_(false),
451 dump_timing_(false),
452 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800453 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800454 timings_(timings) {}
455
456 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800457 // Free opened dex files before deleting the runtime_, because ~DexFile
458 // uses MemMap, which is shut down by ~Runtime.
459 class_path_files_.clear();
460 opened_dex_files_.clear();
461
462 // Log completion time before deleting the runtime_, because this accesses
463 // the runtime.
464 LogCompletionTime();
465
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800466 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
467 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100468 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 }
470
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800471 // Parse the arguments from the command line. In case of an unrecognized option or impossible
472 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
473 // returns, arguments have been successfully parsed.
474 void ParseArgs(int argc, char** argv) {
475 original_argc = argc;
476 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700477
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800478 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700479
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800480 // Skip over argv[0].
481 argv++;
482 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700483
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800484 if (argc == 0) {
485 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800487
488 std::string oat_symbols;
489 std::string boot_image_filename;
490 const char* compiler_filter_string = nullptr;
491 bool compile_pic = false;
492 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
493 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
494 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
495 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
496 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
497
498 // Profile file to use
499 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
500
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800501 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800502 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
503 bool include_debug_symbols = kIsDebugBuild;
504 bool watch_dog_enabled = true;
505 bool generate_gdb_information = kIsDebugBuild;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800506 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000507 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800508
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800509 PassManagerOptions pass_manager_options;
510
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800511 std::string error_msg;
512
513 for (int i = 0; i < argc; i++) {
514 const StringPiece option(argv[i]);
515 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700516 if (log_options) {
517 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
518 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800519 if (option.starts_with("--dex-file=")) {
520 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
521 } else if (option.starts_with("--dex-location=")) {
522 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
523 } else if (option.starts_with("--zip-fd=")) {
524 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
525 if (!ParseInt(zip_fd_str, &zip_fd_)) {
526 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
527 }
528 if (zip_fd_ < 0) {
529 Usage("--zip-fd passed a negative value %d", zip_fd_);
530 }
531 } else if (option.starts_with("--zip-location=")) {
532 zip_location_ = option.substr(strlen("--zip-location=")).data();
533 } else if (option.starts_with("--oat-file=")) {
534 oat_filename_ = option.substr(strlen("--oat-file=")).data();
535 } else if (option.starts_with("--oat-symbols=")) {
536 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
537 } else if (option.starts_with("--oat-fd=")) {
538 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
539 if (!ParseInt(oat_fd_str, &oat_fd_)) {
540 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
541 }
542 if (oat_fd_ < 0) {
543 Usage("--oat-fd passed a negative value %d", oat_fd_);
544 }
545 } else if (option == "--watch-dog") {
546 watch_dog_enabled = true;
547 } else if (option == "--no-watch-dog") {
548 watch_dog_enabled = false;
549 } else if (option == "--gen-gdb-info") {
550 generate_gdb_information = true;
551 // Debug symbols are needed for gdb information.
552 include_debug_symbols = true;
553 } else if (option == "--no-gen-gdb-info") {
554 generate_gdb_information = false;
555 } else if (option.starts_with("-j")) {
556 const char* thread_count_str = option.substr(strlen("-j")).data();
557 if (!ParseUint(thread_count_str, &thread_count_)) {
558 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
559 }
560 } else if (option.starts_with("--oat-location=")) {
561 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800562 } else if (option.starts_with("--image=")) {
563 image_filename_ = option.substr(strlen("--image=")).data();
564 } else if (option.starts_with("--image-classes=")) {
565 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
566 } else if (option.starts_with("--image-classes-zip=")) {
567 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800568 } else if (option.starts_with("--compiled-classes=")) {
569 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
570 } else if (option.starts_with("--compiled-classes-zip=")) {
571 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800572 } else if (option.starts_with("--base=")) {
573 const char* image_base_str = option.substr(strlen("--base=")).data();
574 char* end;
575 image_base_ = strtoul(image_base_str, &end, 16);
576 if (end == image_base_str || *end != '\0') {
577 Usage("Failed to parse hexadecimal value for option %s", option.data());
578 }
579 } else if (option.starts_with("--boot-image=")) {
580 boot_image_filename = option.substr(strlen("--boot-image=")).data();
581 } else if (option.starts_with("--android-root=")) {
582 android_root_ = option.substr(strlen("--android-root=")).data();
583 } else if (option.starts_with("--instruction-set=")) {
584 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
585 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800586 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
588 buf.get()[instruction_set_str.length()] = 0;
589 instruction_set_ = GetInstructionSetFromString(buf.get());
590 // arm actually means thumb2.
591 if (instruction_set_ == InstructionSet::kArm) {
592 instruction_set_ = InstructionSet::kThumb2;
593 }
594 } else if (option.starts_with("--instruction-set-variant=")) {
595 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
596 instruction_set_features_.reset(
597 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
598 if (instruction_set_features_.get() == nullptr) {
599 Usage("%s", error_msg.c_str());
600 }
601 } else if (option.starts_with("--instruction-set-features=")) {
602 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800603 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800604 instruction_set_features_.reset(
605 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
606 if (instruction_set_features_.get() == nullptr) {
607 Usage("Problem initializing default instruction set features variant: %s",
608 error_msg.c_str());
609 }
610 }
611 instruction_set_features_.reset(
612 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
613 if (instruction_set_features_.get() == nullptr) {
614 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800615 }
616 } else if (option.starts_with("--compiler-backend=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000617 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800618 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
619 if (backend_str == "Quick") {
620 compiler_kind_ = Compiler::kQuick;
621 } else if (backend_str == "Optimizing") {
622 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800623 } else {
624 Usage("Unknown compiler backend: %s", backend_str.data());
625 }
626 } else if (option.starts_with("--compiler-filter=")) {
627 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
628 } else if (option == "--compile-pic") {
629 compile_pic = true;
630 } else if (option.starts_with("--huge-method-max=")) {
631 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
632 if (!ParseInt(threshold, &huge_method_threshold)) {
633 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
634 }
635 if (huge_method_threshold < 0) {
636 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
637 }
638 } else if (option.starts_with("--large-method-max=")) {
639 const char* threshold = option.substr(strlen("--large-method-max=")).data();
640 if (!ParseInt(threshold, &large_method_threshold)) {
641 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
642 }
643 if (large_method_threshold < 0) {
644 Usage("--large-method-max passed a negative value %s", large_method_threshold);
645 }
646 } else if (option.starts_with("--small-method-max=")) {
647 const char* threshold = option.substr(strlen("--small-method-max=")).data();
648 if (!ParseInt(threshold, &small_method_threshold)) {
649 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
650 }
651 if (small_method_threshold < 0) {
652 Usage("--small-method-max passed a negative value %s", small_method_threshold);
653 }
654 } else if (option.starts_with("--tiny-method-max=")) {
655 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
656 if (!ParseInt(threshold, &tiny_method_threshold)) {
657 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
658 }
659 if (tiny_method_threshold < 0) {
660 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
661 }
662 } else if (option.starts_with("--num-dex-methods=")) {
663 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
664 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
665 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
666 }
667 if (num_dex_methods_threshold < 0) {
668 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
669 }
670 } else if (option == "--host") {
671 is_host_ = true;
672 } else if (option == "--runtime-arg") {
673 if (++i >= argc) {
674 Usage("Missing required argument for --runtime-arg");
675 }
676 if (log_options) {
677 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
678 }
679 runtime_args_.push_back(argv[i]);
680 } else if (option == "--dump-timing") {
681 dump_timing_ = true;
682 } else if (option == "--dump-passes") {
683 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000684 } else if (option.starts_with("--dump-cfg=")) {
685 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800686 } else if (option == "--dump-stats") {
687 dump_stats_ = true;
688 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
689 include_debug_symbols = true;
690 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
691 include_debug_symbols = false;
692 generate_gdb_information = false; // Depends on debug symbols, see above.
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800693 } else if (option == "--debuggable") {
694 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800695 } else if (option.starts_with("--profile-file=")) {
696 profile_file_ = option.substr(strlen("--profile-file=")).data();
697 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
698 } else if (option == "--no-profile-file") {
699 // No profile
700 } else if (option.starts_with("--top-k-profile-threshold=")) {
701 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
702 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800703 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800704 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800705 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
706 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800707 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800708 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
709 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800711 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800712 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800713 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
714 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800715 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800716 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800717 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800718 const std::string options = option.substr(strlen("--pass-options=")).data();
719 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 } else if (option == "--include-patch-information") {
721 include_patch_information = true;
722 } else if (option == "--no-include-patch-information") {
723 include_patch_information = false;
724 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800725 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
726 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800727 gLogVerbosity.compiler = false;
728 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800729 } else if (option.starts_with("--dump-init-failures=")) {
730 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
731 init_failure_output_.reset(new std::ofstream(file_name));
732 if (init_failure_output_.get() == nullptr) {
733 LOG(ERROR) << "Failed to allocate ofstream";
734 } else if (init_failure_output_->fail()) {
735 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
736 << "failures.";
737 init_failure_output_.reset();
738 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800739 } else if (option.starts_with("--swap-file=")) {
740 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
741 } else if (option.starts_with("--swap-fd=")) {
742 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
743 if (!ParseInt(swap_fd_str, &swap_fd_)) {
744 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
745 }
746 if (swap_fd_ < 0) {
747 Usage("--swap-fd passed a negative value %d", swap_fd_);
748 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800749 } else if (option == "--abort-on-hard-verifier-error") {
750 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 } else {
752 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 }
755
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000756 image_ = (!image_filename_.empty());
757 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
758 // If no specific compiler is requested, the current behavior is
759 // to compile the boot image with Quick, and the rest with Optimizing.
760 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
761 }
762
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000763 if (compiler_kind_ == Compiler::kOptimizing) {
764 // Optimizing only supports PIC mode.
765 compile_pic = true;
766 }
767
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800768 if (oat_filename_.empty() && oat_fd_ == -1) {
769 Usage("Output must be supplied with either --oat-file or --oat-fd");
770 }
771
772 if (!oat_filename_.empty() && oat_fd_ != -1) {
773 Usage("--oat-file should not be used with --oat-fd");
774 }
775
776 if (!oat_symbols.empty() && oat_fd_ != -1) {
777 Usage("--oat-symbols should not be used with --oat-fd");
778 }
779
780 if (!oat_symbols.empty() && is_host_) {
781 Usage("--oat-symbols should not be used with --host");
782 }
783
784 if (oat_fd_ != -1 && !image_filename_.empty()) {
785 Usage("--oat-fd should not be used with --image");
786 }
787
788 if (android_root_.empty()) {
789 const char* android_root_env_var = getenv("ANDROID_ROOT");
790 if (android_root_env_var == nullptr) {
791 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800793 android_root_ += android_root_env_var;
794 }
795
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800796 if (!image_ && boot_image_filename.empty()) {
797 boot_image_filename += android_root_;
798 boot_image_filename += "/framework/boot.art";
799 }
800 if (!boot_image_filename.empty()) {
801 boot_image_option_ += "-Ximage:";
802 boot_image_option_ += boot_image_filename;
803 }
804
805 if (image_classes_filename_ != nullptr && !image_) {
806 Usage("--image-classes should only be used with --image");
807 }
808
809 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
810 Usage("--image-classes should not be used with --boot-image");
811 }
812
813 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
814 Usage("--image-classes-zip should be used with --image-classes");
815 }
816
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800817 if (compiled_classes_filename_ != nullptr && !image_) {
818 Usage("--compiled-classes should only be used with --image");
819 }
820
821 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
822 Usage("--compiled-classes should not be used with --boot-image");
823 }
824
825 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
826 Usage("--compiled-classes-zip should be used with --compiled-classes");
827 }
828
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800829 if (dex_filenames_.empty() && zip_fd_ == -1) {
830 Usage("Input must be supplied with either --dex-file or --zip-fd");
831 }
832
833 if (!dex_filenames_.empty() && zip_fd_ != -1) {
834 Usage("--dex-file should not be used with --zip-fd");
835 }
836
837 if (!dex_filenames_.empty() && !zip_location_.empty()) {
838 Usage("--dex-file should not be used with --zip-location");
839 }
840
841 if (dex_locations_.empty()) {
842 for (const char* dex_file_name : dex_filenames_) {
843 dex_locations_.push_back(dex_file_name);
844 }
845 } else if (dex_locations_.size() != dex_filenames_.size()) {
846 Usage("--dex-location arguments do not match --dex-file arguments");
847 }
848
849 if (zip_fd_ != -1 && zip_location_.empty()) {
850 Usage("--zip-location should be supplied with --zip-fd");
851 }
852
853 if (boot_image_option_.empty()) {
854 if (image_base_ == 0) {
855 Usage("Non-zero --base not specified");
856 }
857 }
858
859 oat_stripped_ = oat_filename_;
860 if (!oat_symbols.empty()) {
861 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800863 oat_unstripped_ = oat_filename_;
864 }
865
866 // If no instruction set feature was given, use the default one for the target
867 // instruction set.
868 if (instruction_set_features_.get() == nullptr) {
869 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800870 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
871 if (instruction_set_features_.get() == nullptr) {
872 Usage("Problem initializing default instruction set features variant: %s",
873 error_msg.c_str());
874 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800875 }
876
877 if (instruction_set_ == kRuntimeISA) {
878 std::unique_ptr<const InstructionSetFeatures> runtime_features(
879 InstructionSetFeatures::FromCppDefines());
880 if (!instruction_set_features_->Equals(runtime_features.get())) {
881 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
882 << *instruction_set_features_ << ") and those of dex2oat executable ("
883 << *runtime_features <<") for the command line:\n"
884 << CommandLine();
885 }
886 }
887
888 if (compiler_filter_string == nullptr) {
Douglas Leung027f0ff2015-02-27 19:05:03 -0800889 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800890 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100891
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800892 CHECK(compiler_filter_string != nullptr);
893 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
894 if (strcmp(compiler_filter_string, "verify-none") == 0) {
895 compiler_filter = CompilerOptions::kVerifyNone;
896 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
897 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700898 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
899 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800900 } else if (strcmp(compiler_filter_string, "space") == 0) {
901 compiler_filter = CompilerOptions::kSpace;
902 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
903 compiler_filter = CompilerOptions::kBalanced;
904 } else if (strcmp(compiler_filter_string, "speed") == 0) {
905 compiler_filter = CompilerOptions::kSpeed;
906 } else if (strcmp(compiler_filter_string, "everything") == 0) {
907 compiler_filter = CompilerOptions::kEverything;
908 } else if (strcmp(compiler_filter_string, "time") == 0) {
909 compiler_filter = CompilerOptions::kTime;
910 } else {
911 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
912 }
913
914 // Checks are all explicit until we know the architecture.
915 bool implicit_null_checks = false;
916 bool implicit_so_checks = false;
917 bool implicit_suspend_checks = false;
918 // Set the compilation target's implicit checks options.
919 switch (instruction_set_) {
920 case kArm:
921 case kThumb2:
922 case kArm64:
923 case kX86:
924 case kX86_64:
925 implicit_null_checks = true;
926 implicit_so_checks = true;
927 break;
928
929 default:
930 // Defaults are correct.
931 break;
932 }
933
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800934 if (debuggable) {
935 // TODO: Consider adding CFI info and symbols here.
936 }
937
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800938 compiler_options_.reset(new CompilerOptions(compiler_filter,
939 huge_method_threshold,
940 large_method_threshold,
941 small_method_threshold,
942 tiny_method_threshold,
943 num_dex_methods_threshold,
944 generate_gdb_information,
945 include_patch_information,
946 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800947 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800948 include_debug_symbols,
949 implicit_null_checks,
950 implicit_so_checks,
951 implicit_suspend_checks,
952 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800953 verbose_methods_.empty() ?
954 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800955 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800956 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800957 init_failure_output_.get(),
958 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800959
960 // Done with usage checks, enable watchdog if requested
961 if (watch_dog_enabled) {
962 watchdog_.reset(new WatchDog(true));
963 }
964
965 // Fill some values into the key-value store for the oat header.
966 key_value_store_.reset(new SafeMap<std::string, std::string>());
967
968 // Insert some compiler things.
969 {
970 std::ostringstream oss;
971 for (int i = 0; i < argc; ++i) {
972 if (i > 0) {
973 oss << ' ';
974 }
975 oss << argv[i];
976 }
977 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
978 oss.str(""); // Reset.
979 oss << kRuntimeISA;
980 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
981 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
982 }
983 }
984
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800985 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
986 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800987 bool OpenFile() {
988 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
989 if (create_file) {
990 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
991 if (oat_location_.empty()) {
992 oat_location_ = oat_filename_;
993 }
994 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800995 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800996 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800997 if (oat_file_->SetLength(0) != 0) {
998 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
999 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001000 }
1001 if (oat_file_.get() == nullptr) {
1002 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1003 return false;
1004 }
1005 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1006 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001007 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001008 return false;
1009 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001010
1011 // Swap file handling.
1012 //
1013 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1014 // that we can use for swap.
1015 //
1016 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1017 // will immediately unlink to satisfy the swap fd assumption.
1018 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1019 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1020 if (swap_file.get() == nullptr) {
1021 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1022 return false;
1023 }
1024 swap_fd_ = swap_file->Fd();
1025 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1026 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1027 // released immediately.
1028 unlink(swap_file_name_.c_str());
1029 }
1030
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001031 return true;
1032 }
1033
Andreas Gampea650e702014-12-03 14:28:02 -08001034 void EraseOatFile() {
1035 DCHECK(oat_file_.get() != nullptr);
1036 oat_file_->Erase();
1037 oat_file_.reset();
1038 }
1039
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001040 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1041 // boot class path.
1042 bool Setup() {
1043 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1044 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001045 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1046 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001047 std::string boot_class_path = "-Xbootclasspath:";
1048 boot_class_path += Join(dex_filenames_, ':');
1049 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1050 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1051 boot_class_path_locations += Join(dex_locations_, ':');
1052 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001053 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001054 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001055 }
1056 for (size_t i = 0; i < runtime_args_.size(); i++) {
1057 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001058 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001059
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001060 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1061 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1062 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1063 runtime_options.push_back(
1064 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1065
Andreas Gampe1d00add2015-02-27 19:35:46 -08001066 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1067 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1068 // have been stripped in preopting, anyways).
1069 if (!image_) {
1070 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1071 }
1072
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001073 if (!CreateRuntime(runtime_options)) {
1074 return false;
1075 }
1076
1077 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1078 // Runtime::Start, give it away now so that we don't starve GC.
1079 Thread* self = Thread::Current();
1080 self->TransitionFromRunnableToSuspended(kNative);
1081 // If we're doing the image, override the compiler filter to force full compilation. Must be
1082 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1083 // compilation of class initializers.
1084 // Whilst we're in native take the opportunity to initialize well known classes.
1085 WellKnownClasses::Init(self->GetJniEnv());
1086
1087 // If --image-classes was specified, calculate the full list of classes to include in the image
1088 if (image_classes_filename_ != nullptr) {
1089 std::string error_msg;
1090 if (image_classes_zip_filename_ != nullptr) {
1091 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1092 image_classes_filename_,
1093 &error_msg));
1094 } else {
1095 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1096 }
1097 if (image_classes_.get() == nullptr) {
1098 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1099 "': " << error_msg;
1100 return false;
1101 }
1102 } else if (image_) {
1103 image_classes_.reset(new std::set<std::string>);
1104 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001105 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1106 // image.
1107 if (compiled_classes_filename_ != nullptr) {
1108 std::string error_msg;
1109 if (compiled_classes_zip_filename_ != nullptr) {
1110 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1111 compiled_classes_filename_,
1112 &error_msg));
1113 } else {
1114 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1115 }
1116 if (compiled_classes_.get() == nullptr) {
1117 LOG(ERROR) << "Failed to create list of compiled classes from '"
1118 << compiled_classes_filename_ << "': " << error_msg;
1119 return false;
1120 }
1121 } else if (image_) {
1122 compiled_classes_.reset(nullptr); // By default compile everything.
1123 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001124
1125 if (boot_image_option_.empty()) {
1126 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1127 } else {
1128 if (dex_filenames_.empty()) {
1129 ATRACE_BEGIN("Opening zip archive from file descriptor");
1130 std::string error_msg;
1131 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1132 zip_location_.c_str(),
1133 &error_msg));
1134 if (zip_archive.get() == nullptr) {
1135 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1136 << error_msg;
1137 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001138 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001139 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1141 << "': " << error_msg;
1142 return false;
1143 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001144 for (auto& dex_file : opened_dex_files_) {
1145 dex_files_.push_back(dex_file.get());
1146 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001147 ATRACE_END();
1148 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001149 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001150 if (failure_count > 0) {
1151 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1152 return false;
1153 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001154 for (auto& dex_file : opened_dex_files_) {
1155 dex_files_.push_back(dex_file.get());
1156 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001157 }
1158
1159 constexpr bool kSaveDexInput = false;
1160 if (kSaveDexInput) {
1161 for (size_t i = 0; i < dex_files_.size(); ++i) {
1162 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001163 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1164 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001165 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1166 if (tmp_file.get() == nullptr) {
1167 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1168 << ". Try: adb shell chmod 777 /data/local/tmp";
1169 continue;
1170 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001171 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1172 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1173 UNUSED(tmp_file->Flush());
1174 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001175 LOG(INFO) << "Wrote input to " << tmp_file_name;
1176 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001177 }
1178 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001179 // Ensure opened dex files are writable for dex-to-dex transformations.
1180 for (const auto& dex_file : dex_files_) {
1181 if (!dex_file->EnableWrite()) {
1182 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001183 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001184 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001185
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001186 // If we use a swap file, ensure we are above the threshold to make it necessary.
1187 if (swap_fd_ != -1) {
1188 if (!UseSwap(image_, dex_files_)) {
1189 close(swap_fd_);
1190 swap_fd_ = -1;
1191 LOG(INFO) << "Decided to run without swap.";
1192 } else {
1193 LOG(INFO) << "Accepted running with swap.";
1194 }
1195 }
1196 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1197
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001198 /*
1199 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1200 * Don't bother to check if we're doing the image.
1201 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001202 if (!image_ &&
1203 compiler_options_->IsCompilationEnabled() &&
1204 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001205 size_t num_methods = 0;
1206 for (size_t i = 0; i != dex_files_.size(); ++i) {
1207 const DexFile* dex_file = dex_files_[i];
1208 CHECK(dex_file != nullptr);
1209 num_methods += dex_file->NumMethodIds();
1210 }
1211 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1212 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1213 VLOG(compiler) << "Below method threshold, compiling anyways";
1214 }
1215 }
1216
1217 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001218 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001219
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001220 // Create and invoke the compiler driver. This will compile all the dex files.
1221 void Compile() {
1222 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1223 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001224
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001225 // Handle and ClassLoader creation needs to come after Runtime::Create
1226 jobject class_loader = nullptr;
1227 Thread* self = Thread::Current();
1228 if (!boot_image_option_.empty()) {
1229 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001230 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001231 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001232 std::vector<const DexFile*> class_path_files(dex_files_);
1233 for (auto& class_path_file : class_path_files_) {
1234 class_path_files.push_back(class_path_file.get());
1235 }
1236
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001237 for (size_t i = 0; i < class_path_files.size(); i++) {
1238 class_linker->RegisterDexFile(*class_path_files[i]);
1239 }
1240 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1241 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1242 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1243 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1244 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1245 }
1246
1247 driver_.reset(new CompilerDriver(compiler_options_.get(),
1248 verification_results_.get(),
1249 &method_inliner_map_,
1250 compiler_kind_,
1251 instruction_set_,
1252 instruction_set_features_.get(),
1253 image_,
1254 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001255 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001256 thread_count_,
1257 dump_stats_,
1258 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001259 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001260 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001261 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001262 profile_file_));
1263
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001264 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001265 }
1266
Brian Carlstrom7940e442013-07-12 13:46:57 -07001267 // Notes on the interleaving of creating the image and oat file to
1268 // ensure the references between the two are correct.
1269 //
1270 // Currently we have a memory layout that looks something like this:
1271 //
1272 // +--------------+
1273 // | image |
1274 // +--------------+
1275 // | boot oat |
1276 // +--------------+
1277 // | alloc spaces |
1278 // +--------------+
1279 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001280 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001281 //
1282 // 1. The image is expected to be loaded at an absolute address and
1283 // contains Objects with absolute pointers within the image.
1284 //
1285 // 2. There are absolute pointers from Methods in the image to their
1286 // code in the oat.
1287 //
1288 // 3. There are absolute pointers from the code in the oat to Methods
1289 // in the image.
1290 //
1291 // 4. There are absolute pointers from code in the oat to other code
1292 // in the oat.
1293 //
1294 // To get this all correct, we go through several steps.
1295 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001296 // 1. We prepare offsets for all data in the oat file and calculate
1297 // the oat data size and code size. During this stage, we also set
1298 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001299 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001300 // 2. We prepare offsets for the objects in the image and calculate
1301 // the image size.
1302 //
1303 // 3. We create the oat file. Originally this was just our own proprietary
1304 // file but now it is contained within an ELF dynamic object (aka an .so
1305 // file). Since we know the image size and oat data size and code size we
1306 // can prepare the ELF headers and we then know the ELF memory segment
1307 // layout and we can now resolve all references. The compiler provides
1308 // LinkerPatch information in each CompiledMethod and we resolve these,
1309 // using the layout information and image object locations provided by
1310 // image writer, as we're writing the method code.
1311 //
1312 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001313 // will be loaded after itself. Originally when oat file was simply
1314 // memory mapped so we could predict where its contents were based
1315 // on the file size. Now that it is an ELF file, we need to inspect
1316 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001317 // where the oat header is located within.
1318 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001319 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001320 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001321 // load the .so at the desired location at runtime by offsetting the
1322 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001323 // TODO: Do this in step 3. We already know the layout there.
1324 //
1325 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1326 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001327
1328
1329 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1330 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001331 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1332 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001333 bool CreateOatFile() {
1334 CHECK(key_value_store_.get() != nullptr);
1335
1336 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1337
1338 std::unique_ptr<OatWriter> oat_writer;
1339 {
1340 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1341 std::string image_file_location;
1342 uint32_t image_file_location_oat_checksum = 0;
1343 uintptr_t image_file_location_oat_data_begin = 0;
1344 int32_t image_patch_delta = 0;
1345 if (image_) {
1346 PrepareImageWriter(image_base_);
1347 } else {
1348 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1349 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1350 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1351 image_file_location_oat_data_begin =
1352 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1353 image_file_location = image_space->GetImageFilename();
1354 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1355 }
1356
1357 if (!image_file_location.empty()) {
1358 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1359 }
1360
1361 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1362 image_file_location_oat_data_begin,
1363 image_patch_delta,
1364 driver_.get(),
1365 image_writer_.get(),
1366 timings_,
1367 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001368 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001369
1370 if (image_) {
1371 // The OatWriter constructor has already updated offsets in methods and we need to
1372 // prepare method offsets in the image address space for direct method patching.
1373 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1374 if (!image_writer_->PrepareImageAddressSpace()) {
1375 LOG(ERROR) << "Failed to prepare image address space.";
1376 return false;
1377 }
1378 }
1379
1380 {
1381 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1382 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1383 oat_file_.get())) {
1384 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1385 return false;
1386 }
1387 }
1388
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001389 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1390 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001391 }
1392
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393 // If we are compiling an image, invoke the image creation routine. Else just skip.
1394 bool HandleImage() {
1395 if (image_) {
1396 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1397 if (!CreateImageFile()) {
1398 return false;
1399 }
1400 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001401 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001402 return true;
1403 }
1404
Andreas Gampe10e477d2014-11-19 12:57:42 -08001405 // Create a copy from unstripped to stripped.
1406 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001407 // If we don't want to strip in place, copy from unstripped location to stripped location.
1408 // We need to strip after image creation because FixupElf needs to use .strtab.
1409 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001410 // If the oat file is still open, flush it.
1411 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1412 if (!FlushCloseOatFile()) {
1413 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001414 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001415 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001416
1417 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001418 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1419 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1420 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001421 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001422 while (true) {
1423 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1424 if (bytes_read <= 0) {
1425 break;
1426 }
1427 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1428 CHECK(write_ok);
1429 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001430 if (out->FlushCloseOrErase() != 0) {
1431 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1432 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001433 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001434 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001435 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001436 return true;
1437 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001438
Andreas Gampe10e477d2014-11-19 12:57:42 -08001439 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001440 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001441 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1442 if (oat_file_->Flush() != 0) {
1443 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1444 << oat_filename_;
1445 oat_file_->Erase();
1446 return false;
1447 }
1448 }
1449 return true;
1450 }
1451
1452 bool FlushCloseOatFile() {
1453 if (oat_file_.get() != nullptr) {
1454 std::unique_ptr<File> tmp(oat_file_.release());
1455 if (tmp->FlushCloseOrErase() != 0) {
1456 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1457 << oat_filename_;
1458 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001459 }
1460 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001461 return true;
1462 }
1463
1464 void DumpTiming() {
1465 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1466 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1467 }
1468 if (dump_passes_) {
1469 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1470 }
1471 }
1472
1473 CompilerOptions* GetCompilerOptions() const {
1474 return compiler_options_.get();
1475 }
1476
Andreas Gampe10e477d2014-11-19 12:57:42 -08001477 bool IsImage() const {
1478 return image_;
1479 }
1480
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001481 bool IsHost() const {
1482 return is_host_;
1483 }
1484
1485 private:
1486 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1487 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001488 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1489 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001490 size_t failure_count = 0;
1491 for (size_t i = 0; i < dex_filenames.size(); i++) {
1492 const char* dex_filename = dex_filenames[i];
1493 const char* dex_location = dex_locations[i];
1494 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1495 std::string error_msg;
1496 if (!OS::FileExists(dex_filename)) {
1497 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1498 continue;
1499 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001500 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001501 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1502 ++failure_count;
1503 }
1504 ATRACE_END();
1505 }
1506 return failure_count;
1507 }
1508
1509 // Returns true if dex_files has a dex with the named location.
1510 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1511 const std::string& location) {
1512 for (size_t i = 0; i < dex_files.size(); ++i) {
1513 if (dex_files[i]->GetLocation() == location) {
1514 return true;
1515 }
1516 }
1517 return false;
1518 }
1519
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001520 // Appends to opened_dex_files any elements of class_path that dex_files
1521 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001522 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001523 std::vector<const DexFile*> dex_files,
1524 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1525 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001526 std::vector<std::string> parsed;
1527 Split(class_path, ':', &parsed);
1528 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1529 ScopedObjectAccess soa(Thread::Current());
1530 for (size_t i = 0; i < parsed.size(); ++i) {
1531 if (DexFilesContains(dex_files, parsed[i])) {
1532 continue;
1533 }
1534 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001535 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001536 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1537 }
1538 }
1539 }
1540
1541 // Create a runtime necessary for compilation.
1542 bool CreateRuntime(const RuntimeOptions& runtime_options)
1543 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1544 if (!Runtime::Create(runtime_options, false)) {
1545 LOG(ERROR) << "Failed to create runtime";
1546 return false;
1547 }
1548 Runtime* runtime = Runtime::Current();
1549 runtime->SetInstructionSet(instruction_set_);
1550 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1551 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1552 if (!runtime->HasCalleeSaveMethod(type)) {
1553 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1554 }
1555 }
1556 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001557
1558 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1559 // set up.
1560 interpreter::UnstartedRuntimeInitialize();
1561
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001562 runtime->GetClassLinker()->RunRootClinits();
1563 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001564
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001565 return true;
1566 }
1567
1568 void PrepareImageWriter(uintptr_t image_base) {
1569 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1570 }
1571
1572 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1573 bool CreateImageFile()
1574 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1575 CHECK(image_writer_ != nullptr);
1576 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1577 LOG(ERROR) << "Failed to create image file " << image_filename_;
1578 return false;
1579 }
1580 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1581
1582 // Destroy ImageWriter before doing FixupElf.
1583 image_writer_.reset();
1584
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001585 // Do not fix up the ELF file if we are --compile-pic
1586 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001587 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1588 if (oat_file.get() == nullptr) {
1589 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1590 return false;
1591 }
1592
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001593 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001594 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001595 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1596 return false;
1597 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001598
1599 if (oat_file->FlushCloseOrErase()) {
1600 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1601 return false;
1602 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603 }
1604
1605 return true;
1606 }
1607
1608 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1609 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1610 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1611 std::ifstream::in));
1612 if (image_classes_file.get() == nullptr) {
1613 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1614 return nullptr;
1615 }
1616 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1617 image_classes_file->close();
1618 return result.release();
1619 }
1620
1621 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1622 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1623 while (image_classes_stream.good()) {
1624 std::string dot;
1625 std::getline(image_classes_stream, dot);
1626 if (StartsWith(dot, "#") || dot.empty()) {
1627 continue;
1628 }
1629 std::string descriptor(DotToDescriptor(dot.c_str()));
1630 image_classes->insert(descriptor);
1631 }
1632 return image_classes.release();
1633 }
1634
1635 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1636 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1637 const char* image_classes_filename,
1638 std::string* error_msg) {
1639 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1640 if (zip_archive.get() == nullptr) {
1641 return nullptr;
1642 }
1643 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1644 if (zip_entry.get() == nullptr) {
1645 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1646 zip_filename, error_msg->c_str());
1647 return nullptr;
1648 }
1649 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1650 image_classes_filename,
1651 error_msg));
1652 if (image_classes_file.get() == nullptr) {
1653 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1654 zip_filename, error_msg->c_str());
1655 return nullptr;
1656 }
1657 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1658 image_classes_file->Size());
1659 std::istringstream image_classes_stream(image_classes_string);
1660 return ReadImageClasses(image_classes_stream);
1661 }
1662
Mathieu Chartier49285c52014-12-02 15:43:48 -08001663 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001664 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1665 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001666 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001667 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001668 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001669 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001670 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1671 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001672 }
1673
1674 std::unique_ptr<CompilerOptions> compiler_options_;
1675 Compiler::Kind compiler_kind_;
1676
1677 InstructionSet instruction_set_;
1678 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1679
1680 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1681
1682 std::unique_ptr<VerificationResults> verification_results_;
1683 DexFileToMethodInlinerMap method_inliner_map_;
1684 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1685
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001686 // Ownership for the class path files.
1687 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1688
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001689 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1690 // in an orderly fashion. The destructor takes care of deleting this.
1691 Runtime* runtime_;
1692
1693 size_t thread_count_;
1694 uint64_t start_ns_;
1695 std::unique_ptr<WatchDog> watchdog_;
1696 std::unique_ptr<File> oat_file_;
1697 std::string oat_stripped_;
1698 std::string oat_unstripped_;
1699 std::string oat_location_;
1700 std::string oat_filename_;
1701 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001702 std::vector<const char*> dex_filenames_;
1703 std::vector<const char*> dex_locations_;
1704 int zip_fd_;
1705 std::string zip_location_;
1706 std::string boot_image_option_;
1707 std::vector<const char*> runtime_args_;
1708 std::string image_filename_;
1709 uintptr_t image_base_;
1710 const char* image_classes_zip_filename_;
1711 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001712 const char* compiled_classes_zip_filename_;
1713 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001714 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001715 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001716 bool image_;
1717 std::unique_ptr<ImageWriter> image_writer_;
1718 bool is_host_;
1719 std::string android_root_;
1720 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001721 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001722 std::unique_ptr<CompilerDriver> driver_;
1723 std::vector<std::string> verbose_methods_;
1724 bool dump_stats_;
1725 bool dump_passes_;
1726 bool dump_timing_;
1727 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001728 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001729 std::string swap_file_name_;
1730 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001731 std::string profile_file_; // Profile file to use
1732 TimingLogger* timings_;
1733 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001734 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001735
1736 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1737};
1738
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001739const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1740
1741static void b13564922() {
1742#if defined(__linux__) && defined(__arm__)
1743 int major, minor;
1744 struct utsname uts;
1745 if (uname(&uts) != -1 &&
1746 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1747 ((major < 3) || ((major == 3) && (minor < 4)))) {
1748 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1749 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1750 int old_personality = personality(0xffffffff);
1751 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1752 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1753 if (new_personality == -1) {
1754 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1755 }
1756 }
1757 }
1758#endif
1759}
1760
Andreas Gampe10e477d2014-11-19 12:57:42 -08001761static int CompileImage(Dex2Oat& dex2oat) {
1762 dex2oat.Compile();
1763
1764 // Create the boot.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 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1771 // re-opened from the unstripped name.
1772 if (!dex2oat.FlushCloseOatFile()) {
1773 return EXIT_FAILURE;
1774 }
1775
1776 // Creates the boot.art and patches the boot.oat.
1777 if (!dex2oat.HandleImage()) {
1778 return EXIT_FAILURE;
1779 }
1780
1781 // When given --host, finish early without stripping.
1782 if (dex2oat.IsHost()) {
1783 dex2oat.DumpTiming();
1784 return EXIT_SUCCESS;
1785 }
1786
1787 // Copy unstripped to stripped location, if necessary.
1788 if (!dex2oat.CopyUnstrippedToStripped()) {
1789 return EXIT_FAILURE;
1790 }
1791
Andreas Gampe10e477d2014-11-19 12:57:42 -08001792 // FlushClose again, as stripping might have re-opened the oat file.
1793 if (!dex2oat.FlushCloseOatFile()) {
1794 return EXIT_FAILURE;
1795 }
1796
1797 dex2oat.DumpTiming();
1798 return EXIT_SUCCESS;
1799}
1800
1801static int CompileApp(Dex2Oat& dex2oat) {
1802 dex2oat.Compile();
1803
1804 // Create the app oat.
1805 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001806 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001807 return EXIT_FAILURE;
1808 }
1809
1810 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1811 // which we would lose.
1812 if (!dex2oat.FlushOatFile()) {
1813 return EXIT_FAILURE;
1814 }
1815
1816 // When given --host, finish early without stripping.
1817 if (dex2oat.IsHost()) {
1818 if (!dex2oat.FlushCloseOatFile()) {
1819 return EXIT_FAILURE;
1820 }
1821
1822 dex2oat.DumpTiming();
1823 return EXIT_SUCCESS;
1824 }
1825
1826 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1827 // unstripped version. If this is given, we expect to be able to open writable files by name.
1828 if (!dex2oat.CopyUnstrippedToStripped()) {
1829 return EXIT_FAILURE;
1830 }
1831
Andreas Gampe10e477d2014-11-19 12:57:42 -08001832 // Flush and close the file.
1833 if (!dex2oat.FlushCloseOatFile()) {
1834 return EXIT_FAILURE;
1835 }
1836
1837 dex2oat.DumpTiming();
1838 return EXIT_SUCCESS;
1839}
1840
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001841static int dex2oat(int argc, char** argv) {
1842 b13564922();
1843
1844 TimingLogger timings("compiler", false, false);
1845
1846 Dex2Oat dex2oat(&timings);
1847
1848 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1849 dex2oat.ParseArgs(argc, argv);
1850
1851 // Check early that the result of compilation can be written
1852 if (!dex2oat.OpenFile()) {
1853 return EXIT_FAILURE;
1854 }
1855
1856 LOG(INFO) << CommandLine();
1857
1858 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001859 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001860 return EXIT_FAILURE;
1861 }
1862
Andreas Gampe10e477d2014-11-19 12:57:42 -08001863 if (dex2oat.IsImage()) {
1864 return CompileImage(dex2oat);
1865 } else {
1866 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001867 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001868}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001869} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001870
1871int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001872 int result = art::dex2oat(argc, argv);
1873 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1874 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1875 // should not destruct the runtime in this case.
1876 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1877 exit(result);
1878 }
1879 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001880}