blob: 8512554c08a2a40ef64c71802e85e81aa613f478 [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("");
Richard Uhlere934df22015-03-17 11:26:16 -0700112 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700113 UsageError(" Example: --dex-file=/system/framework/core.jar");
114 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700115 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
116 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
117 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
118 UsageError(" --dex-location=/system/framework/core.jar");
119 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
121 UsageError(" containing a classes.dex file to compile.");
122 UsageError(" Example: --zip-fd=5");
123 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700124 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
125 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700126 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
127 UsageError("");
128 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
129 UsageError(" Example: --oat-file=/system/framework/boot.oat");
130 UsageError("");
131 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900132 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 UsageError("");
134 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
135 UsageError(" to the file descriptor specified by --oat-fd.");
136 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
137 UsageError("");
138 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
139 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
140 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 UsageError(" --image=<file.art>: specifies the output image filename.");
142 UsageError(" Example: --image=/system/framework/boot.art");
143 UsageError("");
144 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
145 UsageError(" Example: --image=frameworks/base/preloaded-classes");
146 UsageError("");
147 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
148 UsageError(" Example: --base=0x50000000");
149 UsageError("");
150 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
151 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000152 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700153 UsageError("");
154 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
155 UsageError(" Example: --android-root=out/host/linux-x86");
156 UsageError(" Default: $ANDROID_ROOT");
157 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800158 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700159 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160 UsageError(" Example: --instruction-set=x86");
161 UsageError(" Default: arm");
162 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700163 UsageError(" --instruction-set-features=...,: Specify instruction set features");
164 UsageError(" Example: --instruction-set-features=div");
165 UsageError(" Default: default");
166 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700167 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
168 UsageError(" Default: disabled");
169 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800170 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800172 UsageError(" Example: --compiler-backend=Optimizing");
173 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000174 UsageError(" Default: Optimizing");
175 } else {
176 UsageError(" Default: Quick");
177 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100179 UsageError(" --compiler-filter="
180 "(verify-none"
181 "|interpret-only"
182 "|space"
183 "|balanced"
184 "|speed"
185 "|everything"
186 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700187 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800188 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800189 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800190 UsageError("");
191 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
192 UsageError(" method for compiler filter tuning.");
193 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError("");
196 UsageError(" --huge-method-max=<method-instruction-count>: 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(" --large-method-max=<method-instruction-count>: threshold size for a large");
202 UsageError(" method for compiler filter tuning.");
203 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
204 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
205 UsageError("");
206 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
207 UsageError(" method for compiler filter tuning.");
208 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
209 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
210 UsageError("");
211 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
212 UsageError(" method for compiler filter tuning.");
213 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
214 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
215 UsageError("");
216 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
217 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700218 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
219 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800220 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
221 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
222 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700223 UsageError(" --dump-timing: display a breakdown of where time was spent");
224 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700225 UsageError(" --include-patch-information: Include patching information so the generated code");
226 UsageError(" can have its base address moved without full recompilation.");
227 UsageError("");
228 UsageError(" --no-include-patch-information: Do not include patching information.");
229 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700230 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
231 UsageError("");
232 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
233 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
235 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
236 UsageError(" Use a separate --runtime-arg switch for each argument.");
237 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700238 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000239 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700241 UsageError(" --print-pass-names: print a list of pass names");
242 UsageError("");
243 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
244 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
245 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700246 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
247 "with the setting.");
248 UsageError(" Will print default if no overridden setting exists.");
249 UsageError("");
250 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
251 "Pass2Name:Pass2OptionName:Pass2Option#");
252 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
253 UsageError(" Separator used between options is a comma.");
254 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800255 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
256 UsageError(" Example: --swap-file=/data/tmp/swap.001");
257 UsageError("");
258 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
259 UsageError(" Example: --swap-fd=10");
260 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 std::cerr << "See log for usage error information\n";
262 exit(EXIT_FAILURE);
263}
264
Brian Carlstrom7940e442013-07-12 13:46:57 -0700265// The primary goal of the watchdog is to prevent stuck build servers
266// during development when fatal aborts lead to a cascade of failures
267// that result in a deadlock.
268class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800269// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270#undef CHECK_PTHREAD_CALL
271#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
272 do { \
273 int rc = call args; \
274 if (rc != 0) { \
275 errno = rc; \
276 std::string message(# call); \
277 message += " failed for "; \
278 message += reason; \
279 Fatal(message); \
280 } \
281 } while (false)
282
283 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700284 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700285 is_watch_dog_enabled_ = is_watch_dog_enabled;
286 if (!is_watch_dog_enabled_) {
287 return;
288 }
289 shutting_down_ = false;
290 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
294 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
295 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
296 }
297 ~WatchDog() {
298 if (!is_watch_dog_enabled_) {
299 return;
300 }
301 const char* reason = "dex2oat watch dog thread shutdown";
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
303 shutting_down_ = true;
304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
306
Kenny Root51316382014-05-13 14:59:37 -0700307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700308
309 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
311 }
312
313 private:
314 static void* CallBack(void* arg) {
315 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
316 ::art::SetThreadName("dex2oat watch dog");
317 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700318 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700319 }
320
321 static void Message(char severity, const std::string& message) {
322 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
323 // cases.
324 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
325 kIsDebugBuild ? "d" : "",
326 severity,
327 getpid(),
328 GetTid(),
329 message.c_str());
330 }
331
Andreas Gampe794ad762015-02-23 08:12:24 -0800332 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700333 Message('F', message);
334 exit(1);
335 }
336
337 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
339 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800340 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 timespec timeout_ts;
342 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
343 const char* reason = "dex2oat watch dog thread waiting";
344 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
345 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800346 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800348 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700349 } else if (rc != 0) {
350 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
351 strerror(errno)));
352 Fatal(message.c_str());
353 }
354 }
355 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
356 }
357
358 // 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 -0700359 // Debug builds are slower so they have larger timeouts.
360 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800361
Elliott Hughes956af0f2014-12-11 14:34:28 -0800362 // 6 minutes scaled by kSlowdownFactor.
363 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700364
365 bool is_watch_dog_enabled_;
366 bool shutting_down_;
367 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
368 pthread_mutex_t mutex_;
369 pthread_cond_t cond_;
370 pthread_attr_t attr_;
371 pthread_t pthread_;
372};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800374static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100375 std::string::size_type colon = s.find(c);
376 if (colon == std::string::npos) {
377 Usage("Missing char %c in option %s\n", c, s.c_str());
378 }
379 // Add one to remove the char we were trimming until.
380 *parsed_value = s.substr(colon + 1);
381}
382
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800383static void ParseDouble(const std::string& option, char after_char, double min, double max,
384 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100385 std::string substring;
386 ParseStringAfterChar(option, after_char, &substring);
387 bool sane_val = true;
388 double value;
389 if (false) {
390 // TODO: this doesn't seem to work on the emulator. b/15114595
391 std::stringstream iss(substring);
392 iss >> value;
393 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
394 sane_val = iss.eof() && (value >= min) && (value <= max);
395 } else {
396 char* end = nullptr;
397 value = strtod(substring.c_str(), &end);
398 sane_val = *end == '\0' && value >= min && value <= max;
399 }
400 if (!sane_val) {
401 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
402 }
403 *parsed_value = value;
404}
405
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800406static constexpr size_t kMinDexFilesForSwap = 2;
407static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
408
409static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
410 if (is_image) {
411 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
412 return false;
413 }
414 if (dex_files.size() < kMinDexFilesForSwap) {
415 // If there are less dex files than the threshold, assume it's gonna be fine.
416 return false;
417 }
418 size_t dex_files_size = 0;
419 for (const auto* dex_file : dex_files) {
420 dex_files_size += dex_file->GetHeader().file_size_;
421 }
422 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
423}
424
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800425class Dex2Oat FINAL {
426 public:
427 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800428 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800429 instruction_set_(kRuntimeISA),
430 // Take the default set of instruction features from the build.
431 method_inliner_map_(),
432 runtime_(nullptr),
433 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
434 start_ns_(NanoTime()),
435 oat_fd_(-1),
436 zip_fd_(-1),
437 image_base_(0U),
438 image_classes_zip_filename_(nullptr),
439 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800440 compiled_classes_zip_filename_(nullptr),
441 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800442 image_(false),
443 is_host_(false),
444 dump_stats_(false),
445 dump_passes_(false),
446 dump_timing_(false),
447 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800448 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800449 timings_(timings) {}
450
451 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800452 // Free opened dex files before deleting the runtime_, because ~DexFile
453 // uses MemMap, which is shut down by ~Runtime.
454 class_path_files_.clear();
455 opened_dex_files_.clear();
456
457 // Log completion time before deleting the runtime_, because this accesses
458 // the runtime.
459 LogCompletionTime();
460
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800461 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
462 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100463 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700464 }
465
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800466 // Parse the arguments from the command line. In case of an unrecognized option or impossible
467 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
468 // returns, arguments have been successfully parsed.
469 void ParseArgs(int argc, char** argv) {
470 original_argc = argc;
471 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700472
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800473 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700474
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800475 // Skip over argv[0].
476 argv++;
477 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700478
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800479 if (argc == 0) {
480 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700481 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800482
483 std::string oat_symbols;
484 std::string boot_image_filename;
485 const char* compiler_filter_string = nullptr;
486 bool compile_pic = false;
487 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
488 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
489 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
490 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
491 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
492
493 // Profile file to use
494 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
495
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800496 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800497 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
498 bool include_debug_symbols = kIsDebugBuild;
499 bool watch_dog_enabled = true;
500 bool generate_gdb_information = kIsDebugBuild;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800501 bool abort_on_hard_verifier_error = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800502
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800503 PassManagerOptions pass_manager_options;
504
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505 std::string error_msg;
506
507 for (int i = 0; i < argc; i++) {
508 const StringPiece option(argv[i]);
509 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700510 if (log_options) {
511 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
512 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800513 if (option.starts_with("--dex-file=")) {
514 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
515 } else if (option.starts_with("--dex-location=")) {
516 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
517 } else if (option.starts_with("--zip-fd=")) {
518 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
519 if (!ParseInt(zip_fd_str, &zip_fd_)) {
520 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
521 }
522 if (zip_fd_ < 0) {
523 Usage("--zip-fd passed a negative value %d", zip_fd_);
524 }
525 } else if (option.starts_with("--zip-location=")) {
526 zip_location_ = option.substr(strlen("--zip-location=")).data();
527 } else if (option.starts_with("--oat-file=")) {
528 oat_filename_ = option.substr(strlen("--oat-file=")).data();
529 } else if (option.starts_with("--oat-symbols=")) {
530 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
531 } else if (option.starts_with("--oat-fd=")) {
532 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
533 if (!ParseInt(oat_fd_str, &oat_fd_)) {
534 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
535 }
536 if (oat_fd_ < 0) {
537 Usage("--oat-fd passed a negative value %d", oat_fd_);
538 }
539 } else if (option == "--watch-dog") {
540 watch_dog_enabled = true;
541 } else if (option == "--no-watch-dog") {
542 watch_dog_enabled = false;
543 } else if (option == "--gen-gdb-info") {
544 generate_gdb_information = true;
545 // Debug symbols are needed for gdb information.
546 include_debug_symbols = true;
547 } else if (option == "--no-gen-gdb-info") {
548 generate_gdb_information = false;
549 } else if (option.starts_with("-j")) {
550 const char* thread_count_str = option.substr(strlen("-j")).data();
551 if (!ParseUint(thread_count_str, &thread_count_)) {
552 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
553 }
554 } else if (option.starts_with("--oat-location=")) {
555 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556 } else if (option.starts_with("--image=")) {
557 image_filename_ = option.substr(strlen("--image=")).data();
558 } else if (option.starts_with("--image-classes=")) {
559 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
560 } else if (option.starts_with("--image-classes-zip=")) {
561 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800562 } else if (option.starts_with("--compiled-classes=")) {
563 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
564 } else if (option.starts_with("--compiled-classes-zip=")) {
565 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800566 } else if (option.starts_with("--base=")) {
567 const char* image_base_str = option.substr(strlen("--base=")).data();
568 char* end;
569 image_base_ = strtoul(image_base_str, &end, 16);
570 if (end == image_base_str || *end != '\0') {
571 Usage("Failed to parse hexadecimal value for option %s", option.data());
572 }
573 } else if (option.starts_with("--boot-image=")) {
574 boot_image_filename = option.substr(strlen("--boot-image=")).data();
575 } else if (option.starts_with("--android-root=")) {
576 android_root_ = option.substr(strlen("--android-root=")).data();
577 } else if (option.starts_with("--instruction-set=")) {
578 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
579 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800580 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800581 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
582 buf.get()[instruction_set_str.length()] = 0;
583 instruction_set_ = GetInstructionSetFromString(buf.get());
584 // arm actually means thumb2.
585 if (instruction_set_ == InstructionSet::kArm) {
586 instruction_set_ = InstructionSet::kThumb2;
587 }
588 } else if (option.starts_with("--instruction-set-variant=")) {
589 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
590 instruction_set_features_.reset(
591 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
592 if (instruction_set_features_.get() == nullptr) {
593 Usage("%s", error_msg.c_str());
594 }
595 } else if (option.starts_with("--instruction-set-features=")) {
596 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800597 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800598 instruction_set_features_.reset(
599 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
600 if (instruction_set_features_.get() == nullptr) {
601 Usage("Problem initializing default instruction set features variant: %s",
602 error_msg.c_str());
603 }
604 }
605 instruction_set_features_.reset(
606 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
607 if (instruction_set_features_.get() == nullptr) {
608 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800609 }
610 } else if (option.starts_with("--compiler-backend=")) {
611 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
612 if (backend_str == "Quick") {
613 compiler_kind_ = Compiler::kQuick;
614 } else if (backend_str == "Optimizing") {
615 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800616 } else {
617 Usage("Unknown compiler backend: %s", backend_str.data());
618 }
619 } else if (option.starts_with("--compiler-filter=")) {
620 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
621 } else if (option == "--compile-pic") {
622 compile_pic = true;
623 } else if (option.starts_with("--huge-method-max=")) {
624 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
625 if (!ParseInt(threshold, &huge_method_threshold)) {
626 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
627 }
628 if (huge_method_threshold < 0) {
629 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
630 }
631 } else if (option.starts_with("--large-method-max=")) {
632 const char* threshold = option.substr(strlen("--large-method-max=")).data();
633 if (!ParseInt(threshold, &large_method_threshold)) {
634 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
635 }
636 if (large_method_threshold < 0) {
637 Usage("--large-method-max passed a negative value %s", large_method_threshold);
638 }
639 } else if (option.starts_with("--small-method-max=")) {
640 const char* threshold = option.substr(strlen("--small-method-max=")).data();
641 if (!ParseInt(threshold, &small_method_threshold)) {
642 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
643 }
644 if (small_method_threshold < 0) {
645 Usage("--small-method-max passed a negative value %s", small_method_threshold);
646 }
647 } else if (option.starts_with("--tiny-method-max=")) {
648 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
649 if (!ParseInt(threshold, &tiny_method_threshold)) {
650 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
651 }
652 if (tiny_method_threshold < 0) {
653 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
654 }
655 } else if (option.starts_with("--num-dex-methods=")) {
656 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
657 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
658 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
659 }
660 if (num_dex_methods_threshold < 0) {
661 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
662 }
663 } else if (option == "--host") {
664 is_host_ = true;
665 } else if (option == "--runtime-arg") {
666 if (++i >= argc) {
667 Usage("Missing required argument for --runtime-arg");
668 }
669 if (log_options) {
670 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
671 }
672 runtime_args_.push_back(argv[i]);
673 } else if (option == "--dump-timing") {
674 dump_timing_ = true;
675 } else if (option == "--dump-passes") {
676 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000677 } else if (option.starts_with("--dump-cfg=")) {
678 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800679 } else if (option == "--dump-stats") {
680 dump_stats_ = true;
681 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
682 include_debug_symbols = true;
683 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
684 include_debug_symbols = false;
685 generate_gdb_information = false; // Depends on debug symbols, see above.
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800686 } else if (option == "--debuggable") {
687 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800688 } else if (option.starts_with("--profile-file=")) {
689 profile_file_ = option.substr(strlen("--profile-file=")).data();
690 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
691 } else if (option == "--no-profile-file") {
692 // No profile
693 } else if (option.starts_with("--top-k-profile-threshold=")) {
694 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
695 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800696 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800698 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
699 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800700 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800701 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
702 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800703 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800704 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800706 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
707 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800709 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800711 const std::string options = option.substr(strlen("--pass-options=")).data();
712 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800713 } else if (option == "--include-patch-information") {
714 include_patch_information = true;
715 } else if (option == "--no-include-patch-information") {
716 include_patch_information = false;
717 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800718 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
719 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 gLogVerbosity.compiler = false;
721 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800722 } else if (option.starts_with("--dump-init-failures=")) {
723 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
724 init_failure_output_.reset(new std::ofstream(file_name));
725 if (init_failure_output_.get() == nullptr) {
726 LOG(ERROR) << "Failed to allocate ofstream";
727 } else if (init_failure_output_->fail()) {
728 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
729 << "failures.";
730 init_failure_output_.reset();
731 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800732 } else if (option.starts_with("--swap-file=")) {
733 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
734 } else if (option.starts_with("--swap-fd=")) {
735 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
736 if (!ParseInt(swap_fd_str, &swap_fd_)) {
737 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
738 }
739 if (swap_fd_ < 0) {
740 Usage("--swap-fd passed a negative value %d", swap_fd_);
741 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800742 } else if (option == "--abort-on-hard-verifier-error") {
743 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800744 } else {
745 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800747 }
748
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000749 if (compiler_kind_ == Compiler::kOptimizing) {
750 // Optimizing only supports PIC mode.
751 compile_pic = true;
752 }
753
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 if (oat_filename_.empty() && oat_fd_ == -1) {
755 Usage("Output must be supplied with either --oat-file or --oat-fd");
756 }
757
758 if (!oat_filename_.empty() && oat_fd_ != -1) {
759 Usage("--oat-file should not be used with --oat-fd");
760 }
761
762 if (!oat_symbols.empty() && oat_fd_ != -1) {
763 Usage("--oat-symbols should not be used with --oat-fd");
764 }
765
766 if (!oat_symbols.empty() && is_host_) {
767 Usage("--oat-symbols should not be used with --host");
768 }
769
770 if (oat_fd_ != -1 && !image_filename_.empty()) {
771 Usage("--oat-fd should not be used with --image");
772 }
773
774 if (android_root_.empty()) {
775 const char* android_root_env_var = getenv("ANDROID_ROOT");
776 if (android_root_env_var == nullptr) {
777 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700778 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800779 android_root_ += android_root_env_var;
780 }
781
782 image_ = (!image_filename_.empty());
783 if (!image_ && boot_image_filename.empty()) {
784 boot_image_filename += android_root_;
785 boot_image_filename += "/framework/boot.art";
786 }
787 if (!boot_image_filename.empty()) {
788 boot_image_option_ += "-Ximage:";
789 boot_image_option_ += boot_image_filename;
790 }
791
792 if (image_classes_filename_ != nullptr && !image_) {
793 Usage("--image-classes should only be used with --image");
794 }
795
796 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
797 Usage("--image-classes should not be used with --boot-image");
798 }
799
800 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
801 Usage("--image-classes-zip should be used with --image-classes");
802 }
803
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800804 if (compiled_classes_filename_ != nullptr && !image_) {
805 Usage("--compiled-classes should only be used with --image");
806 }
807
808 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
809 Usage("--compiled-classes should not be used with --boot-image");
810 }
811
812 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
813 Usage("--compiled-classes-zip should be used with --compiled-classes");
814 }
815
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800816 if (dex_filenames_.empty() && zip_fd_ == -1) {
817 Usage("Input must be supplied with either --dex-file or --zip-fd");
818 }
819
820 if (!dex_filenames_.empty() && zip_fd_ != -1) {
821 Usage("--dex-file should not be used with --zip-fd");
822 }
823
824 if (!dex_filenames_.empty() && !zip_location_.empty()) {
825 Usage("--dex-file should not be used with --zip-location");
826 }
827
828 if (dex_locations_.empty()) {
829 for (const char* dex_file_name : dex_filenames_) {
830 dex_locations_.push_back(dex_file_name);
831 }
832 } else if (dex_locations_.size() != dex_filenames_.size()) {
833 Usage("--dex-location arguments do not match --dex-file arguments");
834 }
835
836 if (zip_fd_ != -1 && zip_location_.empty()) {
837 Usage("--zip-location should be supplied with --zip-fd");
838 }
839
840 if (boot_image_option_.empty()) {
841 if (image_base_ == 0) {
842 Usage("Non-zero --base not specified");
843 }
844 }
845
846 oat_stripped_ = oat_filename_;
847 if (!oat_symbols.empty()) {
848 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800850 oat_unstripped_ = oat_filename_;
851 }
852
853 // If no instruction set feature was given, use the default one for the target
854 // instruction set.
855 if (instruction_set_features_.get() == nullptr) {
856 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800857 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
858 if (instruction_set_features_.get() == nullptr) {
859 Usage("Problem initializing default instruction set features variant: %s",
860 error_msg.c_str());
861 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800862 }
863
864 if (instruction_set_ == kRuntimeISA) {
865 std::unique_ptr<const InstructionSetFeatures> runtime_features(
866 InstructionSetFeatures::FromCppDefines());
867 if (!instruction_set_features_->Equals(runtime_features.get())) {
868 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
869 << *instruction_set_features_ << ") and those of dex2oat executable ("
870 << *runtime_features <<") for the command line:\n"
871 << CommandLine();
872 }
873 }
874
875 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800876 if (instruction_set_ == kMips &&
877 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
878 IsR6()) {
879 // For R6, only interpreter mode is working.
880 // TODO: fix compiler for Mips32r6.
881 compiler_filter_string = "interpret-only";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800882 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800883 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800884 }
885 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100886
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800887 CHECK(compiler_filter_string != nullptr);
888 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
889 if (strcmp(compiler_filter_string, "verify-none") == 0) {
890 compiler_filter = CompilerOptions::kVerifyNone;
891 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
892 compiler_filter = CompilerOptions::kInterpretOnly;
893 } else if (strcmp(compiler_filter_string, "space") == 0) {
894 compiler_filter = CompilerOptions::kSpace;
895 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
896 compiler_filter = CompilerOptions::kBalanced;
897 } else if (strcmp(compiler_filter_string, "speed") == 0) {
898 compiler_filter = CompilerOptions::kSpeed;
899 } else if (strcmp(compiler_filter_string, "everything") == 0) {
900 compiler_filter = CompilerOptions::kEverything;
901 } else if (strcmp(compiler_filter_string, "time") == 0) {
902 compiler_filter = CompilerOptions::kTime;
903 } else {
904 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
905 }
906
907 // Checks are all explicit until we know the architecture.
908 bool implicit_null_checks = false;
909 bool implicit_so_checks = false;
910 bool implicit_suspend_checks = false;
911 // Set the compilation target's implicit checks options.
912 switch (instruction_set_) {
913 case kArm:
914 case kThumb2:
915 case kArm64:
916 case kX86:
917 case kX86_64:
918 implicit_null_checks = true;
919 implicit_so_checks = true;
920 break;
921
922 default:
923 // Defaults are correct.
924 break;
925 }
926
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800927 if (debuggable) {
928 // TODO: Consider adding CFI info and symbols here.
929 }
930
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800931 compiler_options_.reset(new CompilerOptions(compiler_filter,
932 huge_method_threshold,
933 large_method_threshold,
934 small_method_threshold,
935 tiny_method_threshold,
936 num_dex_methods_threshold,
937 generate_gdb_information,
938 include_patch_information,
939 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800940 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800941 include_debug_symbols,
942 implicit_null_checks,
943 implicit_so_checks,
944 implicit_suspend_checks,
945 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800946 verbose_methods_.empty() ?
947 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800948 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800949 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800950 init_failure_output_.get(),
951 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800952
953 // Done with usage checks, enable watchdog if requested
954 if (watch_dog_enabled) {
955 watchdog_.reset(new WatchDog(true));
956 }
957
958 // Fill some values into the key-value store for the oat header.
959 key_value_store_.reset(new SafeMap<std::string, std::string>());
960
961 // Insert some compiler things.
962 {
963 std::ostringstream oss;
964 for (int i = 0; i < argc; ++i) {
965 if (i > 0) {
966 oss << ' ';
967 }
968 oss << argv[i];
969 }
970 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
971 oss.str(""); // Reset.
972 oss << kRuntimeISA;
973 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
974 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
975 }
976 }
977
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800978 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
979 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800980 bool OpenFile() {
981 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
982 if (create_file) {
983 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
984 if (oat_location_.empty()) {
985 oat_location_ = oat_filename_;
986 }
987 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800988 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800989 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800990 if (oat_file_->SetLength(0) != 0) {
991 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
992 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800993 }
994 if (oat_file_.get() == nullptr) {
995 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
996 return false;
997 }
998 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
999 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001000 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001001 return false;
1002 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001003
1004 // Swap file handling.
1005 //
1006 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1007 // that we can use for swap.
1008 //
1009 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1010 // will immediately unlink to satisfy the swap fd assumption.
1011 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1012 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1013 if (swap_file.get() == nullptr) {
1014 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1015 return false;
1016 }
1017 swap_fd_ = swap_file->Fd();
1018 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1019 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1020 // released immediately.
1021 unlink(swap_file_name_.c_str());
1022 }
1023
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001024 return true;
1025 }
1026
Andreas Gampea650e702014-12-03 14:28:02 -08001027 void EraseOatFile() {
1028 DCHECK(oat_file_.get() != nullptr);
1029 oat_file_->Erase();
1030 oat_file_.reset();
1031 }
1032
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001033 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1034 // boot class path.
1035 bool Setup() {
1036 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1037 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001038 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1039 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001040 std::string boot_class_path = "-Xbootclasspath:";
1041 boot_class_path += Join(dex_filenames_, ':');
1042 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1043 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1044 boot_class_path_locations += Join(dex_locations_, ':');
1045 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001046 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001047 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001048 }
1049 for (size_t i = 0; i < runtime_args_.size(); i++) {
1050 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001052
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001053 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1054 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1055 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1056 runtime_options.push_back(
1057 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1058
Andreas Gampe1d00add2015-02-27 19:35:46 -08001059 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1060 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1061 // have been stripped in preopting, anyways).
1062 if (!image_) {
1063 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1064 }
1065
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001066 if (!CreateRuntime(runtime_options)) {
1067 return false;
1068 }
1069
1070 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1071 // Runtime::Start, give it away now so that we don't starve GC.
1072 Thread* self = Thread::Current();
1073 self->TransitionFromRunnableToSuspended(kNative);
1074 // If we're doing the image, override the compiler filter to force full compilation. Must be
1075 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1076 // compilation of class initializers.
1077 // Whilst we're in native take the opportunity to initialize well known classes.
1078 WellKnownClasses::Init(self->GetJniEnv());
1079
1080 // If --image-classes was specified, calculate the full list of classes to include in the image
1081 if (image_classes_filename_ != nullptr) {
1082 std::string error_msg;
1083 if (image_classes_zip_filename_ != nullptr) {
1084 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1085 image_classes_filename_,
1086 &error_msg));
1087 } else {
1088 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1089 }
1090 if (image_classes_.get() == nullptr) {
1091 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1092 "': " << error_msg;
1093 return false;
1094 }
1095 } else if (image_) {
1096 image_classes_.reset(new std::set<std::string>);
1097 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001098 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1099 // image.
1100 if (compiled_classes_filename_ != nullptr) {
1101 std::string error_msg;
1102 if (compiled_classes_zip_filename_ != nullptr) {
1103 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1104 compiled_classes_filename_,
1105 &error_msg));
1106 } else {
1107 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1108 }
1109 if (compiled_classes_.get() == nullptr) {
1110 LOG(ERROR) << "Failed to create list of compiled classes from '"
1111 << compiled_classes_filename_ << "': " << error_msg;
1112 return false;
1113 }
1114 } else if (image_) {
1115 compiled_classes_.reset(nullptr); // By default compile everything.
1116 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001117
1118 if (boot_image_option_.empty()) {
1119 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1120 } else {
1121 if (dex_filenames_.empty()) {
1122 ATRACE_BEGIN("Opening zip archive from file descriptor");
1123 std::string error_msg;
1124 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1125 zip_location_.c_str(),
1126 &error_msg));
1127 if (zip_archive.get() == nullptr) {
1128 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1129 << error_msg;
1130 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001131 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001132 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001133 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1134 << "': " << error_msg;
1135 return false;
1136 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001137 for (auto& dex_file : opened_dex_files_) {
1138 dex_files_.push_back(dex_file.get());
1139 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 ATRACE_END();
1141 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001142 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001143 if (failure_count > 0) {
1144 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1145 return false;
1146 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001147 for (auto& dex_file : opened_dex_files_) {
1148 dex_files_.push_back(dex_file.get());
1149 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001150 }
1151
1152 constexpr bool kSaveDexInput = false;
1153 if (kSaveDexInput) {
1154 for (size_t i = 0; i < dex_files_.size(); ++i) {
1155 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001156 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1157 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001158 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1159 if (tmp_file.get() == nullptr) {
1160 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1161 << ". Try: adb shell chmod 777 /data/local/tmp";
1162 continue;
1163 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001164 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1165 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1166 UNUSED(tmp_file->Flush());
1167 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168 LOG(INFO) << "Wrote input to " << tmp_file_name;
1169 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001170 }
1171 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172 // Ensure opened dex files are writable for dex-to-dex transformations.
1173 for (const auto& dex_file : dex_files_) {
1174 if (!dex_file->EnableWrite()) {
1175 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001176 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001177 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001179 // If we use a swap file, ensure we are above the threshold to make it necessary.
1180 if (swap_fd_ != -1) {
1181 if (!UseSwap(image_, dex_files_)) {
1182 close(swap_fd_);
1183 swap_fd_ = -1;
1184 LOG(INFO) << "Decided to run without swap.";
1185 } else {
1186 LOG(INFO) << "Accepted running with swap.";
1187 }
1188 }
1189 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1190
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001191 /*
1192 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1193 * Don't bother to check if we're doing the image.
1194 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001195 if (!image_ &&
1196 compiler_options_->IsCompilationEnabled() &&
1197 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001198 size_t num_methods = 0;
1199 for (size_t i = 0; i != dex_files_.size(); ++i) {
1200 const DexFile* dex_file = dex_files_[i];
1201 CHECK(dex_file != nullptr);
1202 num_methods += dex_file->NumMethodIds();
1203 }
1204 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1205 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1206 VLOG(compiler) << "Below method threshold, compiling anyways";
1207 }
1208 }
1209
1210 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001211 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001212
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001213 // Create and invoke the compiler driver. This will compile all the dex files.
1214 void Compile() {
1215 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1216 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001217
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001218 // Handle and ClassLoader creation needs to come after Runtime::Create
1219 jobject class_loader = nullptr;
1220 Thread* self = Thread::Current();
1221 if (!boot_image_option_.empty()) {
1222 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001223 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001224 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001225 std::vector<const DexFile*> class_path_files(dex_files_);
1226 for (auto& class_path_file : class_path_files_) {
1227 class_path_files.push_back(class_path_file.get());
1228 }
1229
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001230 for (size_t i = 0; i < class_path_files.size(); i++) {
1231 class_linker->RegisterDexFile(*class_path_files[i]);
1232 }
1233 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1234 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1235 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1236 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1237 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1238 }
1239
1240 driver_.reset(new CompilerDriver(compiler_options_.get(),
1241 verification_results_.get(),
1242 &method_inliner_map_,
1243 compiler_kind_,
1244 instruction_set_,
1245 instruction_set_features_.get(),
1246 image_,
1247 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001248 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001249 thread_count_,
1250 dump_stats_,
1251 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001252 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001254 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001255 profile_file_));
1256
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001257 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001258 }
1259
Brian Carlstrom7940e442013-07-12 13:46:57 -07001260 // Notes on the interleaving of creating the image and oat file to
1261 // ensure the references between the two are correct.
1262 //
1263 // Currently we have a memory layout that looks something like this:
1264 //
1265 // +--------------+
1266 // | image |
1267 // +--------------+
1268 // | boot oat |
1269 // +--------------+
1270 // | alloc spaces |
1271 // +--------------+
1272 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001273 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001274 //
1275 // 1. The image is expected to be loaded at an absolute address and
1276 // contains Objects with absolute pointers within the image.
1277 //
1278 // 2. There are absolute pointers from Methods in the image to their
1279 // code in the oat.
1280 //
1281 // 3. There are absolute pointers from the code in the oat to Methods
1282 // in the image.
1283 //
1284 // 4. There are absolute pointers from code in the oat to other code
1285 // in the oat.
1286 //
1287 // To get this all correct, we go through several steps.
1288 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001289 // 1. We prepare offsets for all data in the oat file and calculate
1290 // the oat data size and code size. During this stage, we also set
1291 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001293 // 2. We prepare offsets for the objects in the image and calculate
1294 // the image size.
1295 //
1296 // 3. We create the oat file. Originally this was just our own proprietary
1297 // file but now it is contained within an ELF dynamic object (aka an .so
1298 // file). Since we know the image size and oat data size and code size we
1299 // can prepare the ELF headers and we then know the ELF memory segment
1300 // layout and we can now resolve all references. The compiler provides
1301 // LinkerPatch information in each CompiledMethod and we resolve these,
1302 // using the layout information and image object locations provided by
1303 // image writer, as we're writing the method code.
1304 //
1305 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001306 // will be loaded after itself. Originally when oat file was simply
1307 // memory mapped so we could predict where its contents were based
1308 // on the file size. Now that it is an ELF file, we need to inspect
1309 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001310 // where the oat header is located within.
1311 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001313 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001314 // load the .so at the desired location at runtime by offsetting the
1315 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001316 // TODO: Do this in step 3. We already know the layout there.
1317 //
1318 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1319 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001320
1321
1322 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1323 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001324 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1325 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001326 bool CreateOatFile() {
1327 CHECK(key_value_store_.get() != nullptr);
1328
1329 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1330
1331 std::unique_ptr<OatWriter> oat_writer;
1332 {
1333 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1334 std::string image_file_location;
1335 uint32_t image_file_location_oat_checksum = 0;
1336 uintptr_t image_file_location_oat_data_begin = 0;
1337 int32_t image_patch_delta = 0;
1338 if (image_) {
1339 PrepareImageWriter(image_base_);
1340 } else {
1341 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1342 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1343 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1344 image_file_location_oat_data_begin =
1345 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1346 image_file_location = image_space->GetImageFilename();
1347 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1348 }
1349
1350 if (!image_file_location.empty()) {
1351 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1352 }
1353
1354 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1355 image_file_location_oat_data_begin,
1356 image_patch_delta,
1357 driver_.get(),
1358 image_writer_.get(),
1359 timings_,
1360 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001361 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001362
1363 if (image_) {
1364 // The OatWriter constructor has already updated offsets in methods and we need to
1365 // prepare method offsets in the image address space for direct method patching.
1366 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1367 if (!image_writer_->PrepareImageAddressSpace()) {
1368 LOG(ERROR) << "Failed to prepare image address space.";
1369 return false;
1370 }
1371 }
1372
1373 {
1374 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1375 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1376 oat_file_.get())) {
1377 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1378 return false;
1379 }
1380 }
1381
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001382 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1383 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001384 }
1385
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001386 // If we are compiling an image, invoke the image creation routine. Else just skip.
1387 bool HandleImage() {
1388 if (image_) {
1389 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1390 if (!CreateImageFile()) {
1391 return false;
1392 }
1393 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001394 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001395 return true;
1396 }
1397
Andreas Gampe10e477d2014-11-19 12:57:42 -08001398 // Create a copy from unstripped to stripped.
1399 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001400 // If we don't want to strip in place, copy from unstripped location to stripped location.
1401 // We need to strip after image creation because FixupElf needs to use .strtab.
1402 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001403 // If the oat file is still open, flush it.
1404 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1405 if (!FlushCloseOatFile()) {
1406 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001407 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001408 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001409
1410 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001411 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1412 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1413 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001414 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001415 while (true) {
1416 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1417 if (bytes_read <= 0) {
1418 break;
1419 }
1420 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1421 CHECK(write_ok);
1422 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001423 if (out->FlushCloseOrErase() != 0) {
1424 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1425 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001426 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001427 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001428 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001429 return true;
1430 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001431
Andreas Gampe10e477d2014-11-19 12:57:42 -08001432 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001433 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001434 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1435 if (oat_file_->Flush() != 0) {
1436 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1437 << oat_filename_;
1438 oat_file_->Erase();
1439 return false;
1440 }
1441 }
1442 return true;
1443 }
1444
1445 bool FlushCloseOatFile() {
1446 if (oat_file_.get() != nullptr) {
1447 std::unique_ptr<File> tmp(oat_file_.release());
1448 if (tmp->FlushCloseOrErase() != 0) {
1449 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1450 << oat_filename_;
1451 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001452 }
1453 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001454 return true;
1455 }
1456
1457 void DumpTiming() {
1458 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1459 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1460 }
1461 if (dump_passes_) {
1462 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1463 }
1464 }
1465
1466 CompilerOptions* GetCompilerOptions() const {
1467 return compiler_options_.get();
1468 }
1469
Andreas Gampe10e477d2014-11-19 12:57:42 -08001470 bool IsImage() const {
1471 return image_;
1472 }
1473
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001474 bool IsHost() const {
1475 return is_host_;
1476 }
1477
1478 private:
1479 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1480 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001481 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1482 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001483 size_t failure_count = 0;
1484 for (size_t i = 0; i < dex_filenames.size(); i++) {
1485 const char* dex_filename = dex_filenames[i];
1486 const char* dex_location = dex_locations[i];
1487 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1488 std::string error_msg;
1489 if (!OS::FileExists(dex_filename)) {
1490 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1491 continue;
1492 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001493 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1495 ++failure_count;
1496 }
1497 ATRACE_END();
1498 }
1499 return failure_count;
1500 }
1501
1502 // Returns true if dex_files has a dex with the named location.
1503 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1504 const std::string& location) {
1505 for (size_t i = 0; i < dex_files.size(); ++i) {
1506 if (dex_files[i]->GetLocation() == location) {
1507 return true;
1508 }
1509 }
1510 return false;
1511 }
1512
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001513 // Appends to opened_dex_files any elements of class_path that dex_files
1514 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001515 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001516 std::vector<const DexFile*> dex_files,
1517 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1518 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001519 std::vector<std::string> parsed;
1520 Split(class_path, ':', &parsed);
1521 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1522 ScopedObjectAccess soa(Thread::Current());
1523 for (size_t i = 0; i < parsed.size(); ++i) {
1524 if (DexFilesContains(dex_files, parsed[i])) {
1525 continue;
1526 }
1527 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001528 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001529 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1530 }
1531 }
1532 }
1533
1534 // Create a runtime necessary for compilation.
1535 bool CreateRuntime(const RuntimeOptions& runtime_options)
1536 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1537 if (!Runtime::Create(runtime_options, false)) {
1538 LOG(ERROR) << "Failed to create runtime";
1539 return false;
1540 }
1541 Runtime* runtime = Runtime::Current();
1542 runtime->SetInstructionSet(instruction_set_);
1543 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1544 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1545 if (!runtime->HasCalleeSaveMethod(type)) {
1546 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1547 }
1548 }
1549 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001550
1551 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1552 // set up.
1553 interpreter::UnstartedRuntimeInitialize();
1554
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001555 runtime->GetClassLinker()->RunRootClinits();
1556 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001557
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001558 return true;
1559 }
1560
1561 void PrepareImageWriter(uintptr_t image_base) {
1562 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1563 }
1564
1565 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1566 bool CreateImageFile()
1567 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1568 CHECK(image_writer_ != nullptr);
1569 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1570 LOG(ERROR) << "Failed to create image file " << image_filename_;
1571 return false;
1572 }
1573 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1574
1575 // Destroy ImageWriter before doing FixupElf.
1576 image_writer_.reset();
1577
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001578 // Do not fix up the ELF file if we are --compile-pic
1579 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001580 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1581 if (oat_file.get() == nullptr) {
1582 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1583 return false;
1584 }
1585
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001586 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001587 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001588 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1589 return false;
1590 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001591
1592 if (oat_file->FlushCloseOrErase()) {
1593 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1594 return false;
1595 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001596 }
1597
1598 return true;
1599 }
1600
1601 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1602 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1603 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1604 std::ifstream::in));
1605 if (image_classes_file.get() == nullptr) {
1606 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1607 return nullptr;
1608 }
1609 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1610 image_classes_file->close();
1611 return result.release();
1612 }
1613
1614 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1615 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1616 while (image_classes_stream.good()) {
1617 std::string dot;
1618 std::getline(image_classes_stream, dot);
1619 if (StartsWith(dot, "#") || dot.empty()) {
1620 continue;
1621 }
1622 std::string descriptor(DotToDescriptor(dot.c_str()));
1623 image_classes->insert(descriptor);
1624 }
1625 return image_classes.release();
1626 }
1627
1628 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1629 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1630 const char* image_classes_filename,
1631 std::string* error_msg) {
1632 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1633 if (zip_archive.get() == nullptr) {
1634 return nullptr;
1635 }
1636 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1637 if (zip_entry.get() == nullptr) {
1638 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1639 zip_filename, error_msg->c_str());
1640 return nullptr;
1641 }
1642 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1643 image_classes_filename,
1644 error_msg));
1645 if (image_classes_file.get() == nullptr) {
1646 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1647 zip_filename, error_msg->c_str());
1648 return nullptr;
1649 }
1650 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1651 image_classes_file->Size());
1652 std::istringstream image_classes_stream(image_classes_string);
1653 return ReadImageClasses(image_classes_stream);
1654 }
1655
Mathieu Chartier49285c52014-12-02 15:43:48 -08001656 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001657 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1658 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001659 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001660 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001661 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001662 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001663 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1664 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001665 }
1666
1667 std::unique_ptr<CompilerOptions> compiler_options_;
1668 Compiler::Kind compiler_kind_;
1669
1670 InstructionSet instruction_set_;
1671 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1672
1673 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1674
1675 std::unique_ptr<VerificationResults> verification_results_;
1676 DexFileToMethodInlinerMap method_inliner_map_;
1677 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1678
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001679 // Ownership for the class path files.
1680 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1681
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001682 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1683 // in an orderly fashion. The destructor takes care of deleting this.
1684 Runtime* runtime_;
1685
1686 size_t thread_count_;
1687 uint64_t start_ns_;
1688 std::unique_ptr<WatchDog> watchdog_;
1689 std::unique_ptr<File> oat_file_;
1690 std::string oat_stripped_;
1691 std::string oat_unstripped_;
1692 std::string oat_location_;
1693 std::string oat_filename_;
1694 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695 std::vector<const char*> dex_filenames_;
1696 std::vector<const char*> dex_locations_;
1697 int zip_fd_;
1698 std::string zip_location_;
1699 std::string boot_image_option_;
1700 std::vector<const char*> runtime_args_;
1701 std::string image_filename_;
1702 uintptr_t image_base_;
1703 const char* image_classes_zip_filename_;
1704 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001705 const char* compiled_classes_zip_filename_;
1706 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001707 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001708 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001709 bool image_;
1710 std::unique_ptr<ImageWriter> image_writer_;
1711 bool is_host_;
1712 std::string android_root_;
1713 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001714 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 std::unique_ptr<CompilerDriver> driver_;
1716 std::vector<std::string> verbose_methods_;
1717 bool dump_stats_;
1718 bool dump_passes_;
1719 bool dump_timing_;
1720 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001721 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001722 std::string swap_file_name_;
1723 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001724 std::string profile_file_; // Profile file to use
1725 TimingLogger* timings_;
1726 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001727 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001728
1729 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1730};
1731
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001732const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1733
1734static void b13564922() {
1735#if defined(__linux__) && defined(__arm__)
1736 int major, minor;
1737 struct utsname uts;
1738 if (uname(&uts) != -1 &&
1739 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1740 ((major < 3) || ((major == 3) && (minor < 4)))) {
1741 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1742 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1743 int old_personality = personality(0xffffffff);
1744 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1745 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1746 if (new_personality == -1) {
1747 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1748 }
1749 }
1750 }
1751#endif
1752}
1753
Andreas Gampe10e477d2014-11-19 12:57:42 -08001754static int CompileImage(Dex2Oat& dex2oat) {
1755 dex2oat.Compile();
1756
1757 // Create the boot.oat.
1758 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001759 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001760 return EXIT_FAILURE;
1761 }
1762
1763 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1764 // re-opened from the unstripped name.
1765 if (!dex2oat.FlushCloseOatFile()) {
1766 return EXIT_FAILURE;
1767 }
1768
1769 // Creates the boot.art and patches the boot.oat.
1770 if (!dex2oat.HandleImage()) {
1771 return EXIT_FAILURE;
1772 }
1773
1774 // When given --host, finish early without stripping.
1775 if (dex2oat.IsHost()) {
1776 dex2oat.DumpTiming();
1777 return EXIT_SUCCESS;
1778 }
1779
1780 // Copy unstripped to stripped location, if necessary.
1781 if (!dex2oat.CopyUnstrippedToStripped()) {
1782 return EXIT_FAILURE;
1783 }
1784
Andreas Gampe10e477d2014-11-19 12:57:42 -08001785 // FlushClose again, as stripping might have re-opened the oat file.
1786 if (!dex2oat.FlushCloseOatFile()) {
1787 return EXIT_FAILURE;
1788 }
1789
1790 dex2oat.DumpTiming();
1791 return EXIT_SUCCESS;
1792}
1793
1794static int CompileApp(Dex2Oat& dex2oat) {
1795 dex2oat.Compile();
1796
1797 // Create the app oat.
1798 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001799 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001800 return EXIT_FAILURE;
1801 }
1802
1803 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1804 // which we would lose.
1805 if (!dex2oat.FlushOatFile()) {
1806 return EXIT_FAILURE;
1807 }
1808
1809 // When given --host, finish early without stripping.
1810 if (dex2oat.IsHost()) {
1811 if (!dex2oat.FlushCloseOatFile()) {
1812 return EXIT_FAILURE;
1813 }
1814
1815 dex2oat.DumpTiming();
1816 return EXIT_SUCCESS;
1817 }
1818
1819 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1820 // unstripped version. If this is given, we expect to be able to open writable files by name.
1821 if (!dex2oat.CopyUnstrippedToStripped()) {
1822 return EXIT_FAILURE;
1823 }
1824
Andreas Gampe10e477d2014-11-19 12:57:42 -08001825 // Flush and close the file.
1826 if (!dex2oat.FlushCloseOatFile()) {
1827 return EXIT_FAILURE;
1828 }
1829
1830 dex2oat.DumpTiming();
1831 return EXIT_SUCCESS;
1832}
1833
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001834static int dex2oat(int argc, char** argv) {
1835 b13564922();
1836
1837 TimingLogger timings("compiler", false, false);
1838
1839 Dex2Oat dex2oat(&timings);
1840
1841 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1842 dex2oat.ParseArgs(argc, argv);
1843
1844 // Check early that the result of compilation can be written
1845 if (!dex2oat.OpenFile()) {
1846 return EXIT_FAILURE;
1847 }
1848
1849 LOG(INFO) << CommandLine();
1850
1851 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001852 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001853 return EXIT_FAILURE;
1854 }
1855
Andreas Gampe10e477d2014-11-19 12:57:42 -08001856 if (dex2oat.IsImage()) {
1857 return CompileImage(dex2oat);
1858 } else {
1859 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001860 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001861}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001862} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001863
1864int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001865 int result = art::dex2oat(argc, argv);
1866 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1867 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1868 // should not destruct the runtime in this case.
1869 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1870 exit(result);
1871 }
1872 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873}