blob: 70b4213d56c7c21d0aa9b743f9d85fc70dff4e8c [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>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070026#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070027#include <vector>
28
Vladimir Markof94b7812014-06-05 15:48:04 +010029#if defined(__linux__) && defined(__arm__)
30#include <sys/personality.h>
31#include <sys/utsname.h>
32#endif
33
Ian Rogerscf7f1912014-10-22 22:06:39 -070034#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080035#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070036
Ian Rogersd582fa42014-11-05 23:46:43 -080037#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080038#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070039#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080040#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "base/stl_util.h"
42#include "base/stringpiece.h"
43#include "base/timing_logger.h"
44#include "base/unix_file/fd_file.h"
45#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000046#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000047#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080049#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000050#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070051#include "dex/quick_compiler_callbacks.h"
52#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080054#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080055#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070056#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "gc/space/image_space.h"
58#include "gc/space/space-inl.h"
59#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070060#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070062#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/class-inl.h"
64#include "mirror/class_loader.h"
65#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
67#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "os.h"
69#include "runtime.h"
70#include "ScopedLocalRef.h"
71#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070072#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "vector_output_stream.h"
74#include "well_known_classes.h"
75#include "zip_archive.h"
76
77namespace art {
78
Brian Carlstrom6449c622014-02-10 23:48:36 -080079static int original_argc;
80static char** original_argv;
81
82static std::string CommandLine() {
83 std::vector<std::string> command;
84 for (int i = 0; i < original_argc; ++i) {
85 command.push_back(original_argv[i]);
86 }
87 return Join(command, ' ');
88}
89
Brian Carlstrom7940e442013-07-12 13:46:57 -070090static void UsageErrorV(const char* fmt, va_list ap) {
91 std::string error;
92 StringAppendV(&error, fmt, ap);
93 LOG(ERROR) << error;
94}
95
96static void UsageError(const char* fmt, ...) {
97 va_list ap;
98 va_start(ap, fmt);
99 UsageErrorV(fmt, ap);
100 va_end(ap);
101}
102
Andreas Gampe794ad762015-02-23 08:12:24 -0800103NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700104 va_list ap;
105 va_start(ap, fmt);
106 UsageErrorV(fmt, ap);
107 va_end(ap);
108
Brian Carlstrom6449c622014-02-10 23:48:36 -0800109 UsageError("Command: %s", CommandLine().c_str());
110
Brian Carlstrom7940e442013-07-12 13:46:57 -0700111 UsageError("Usage: dex2oat [options]...");
112 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100113 UsageError(" -j<number>: specifies the number of threads used for compilation.");
114 UsageError(" Default is the number of detected hardware threads available on the");
115 UsageError(" host system.");
116 UsageError(" Example: -j12");
117 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700118 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700119 UsageError(" Example: --dex-file=/system/framework/core.jar");
120 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700121 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
122 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
123 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
124 UsageError(" --dex-location=/system/framework/core.jar");
125 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700126 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
127 UsageError(" containing a classes.dex file to compile.");
128 UsageError(" Example: --zip-fd=5");
129 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700130 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
131 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700132 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
133 UsageError("");
134 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
135 UsageError(" Example: --oat-file=/system/framework/boot.oat");
136 UsageError("");
137 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900138 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700139 UsageError("");
140 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
141 UsageError(" to the file descriptor specified by --oat-fd.");
142 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
143 UsageError("");
144 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
145 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
146 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError(" --image=<file.art>: specifies the output image filename.");
148 UsageError(" Example: --image=/system/framework/boot.art");
149 UsageError("");
150 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
151 UsageError(" Example: --image=frameworks/base/preloaded-classes");
152 UsageError("");
153 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
154 UsageError(" Example: --base=0x50000000");
155 UsageError("");
156 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
157 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000158 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159 UsageError("");
160 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
161 UsageError(" Example: --android-root=out/host/linux-x86");
162 UsageError(" Default: $ANDROID_ROOT");
163 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800164 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700165 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 UsageError(" Example: --instruction-set=x86");
167 UsageError(" Default: arm");
168 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700169 UsageError(" --instruction-set-features=...,: Specify instruction set features");
170 UsageError(" Example: --instruction-set-features=div");
171 UsageError(" Default: default");
172 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700173 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
174 UsageError(" Default: disabled");
175 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800176 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700177 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800178 UsageError(" Example: --compiler-backend=Optimizing");
179 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000180 UsageError(" Default: Optimizing");
181 } else {
182 UsageError(" Default: Quick");
183 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700184 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100185 UsageError(" --compiler-filter="
186 "(verify-none"
187 "|interpret-only"
188 "|space"
189 "|balanced"
190 "|speed"
191 "|everything"
192 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700193 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800194 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800195 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800196 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800197 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
198 UsageError(" method for compiler filter tuning.");
199 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
200 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
201 UsageError("");
202 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
203 UsageError(" method for compiler filter tuning.");
204 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
205 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
206 UsageError("");
207 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
208 UsageError(" method for compiler filter tuning.");
209 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
210 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
211 UsageError("");
212 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
213 UsageError(" method for compiler filter tuning.");
214 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
215 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
216 UsageError("");
217 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
218 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700219 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
220 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800221 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
222 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
223 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700224 UsageError(" --dump-timing: display a breakdown of where time was spent");
225 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700226 UsageError(" --include-patch-information: Include patching information so the generated code");
227 UsageError(" can have its base address moved without full recompilation.");
228 UsageError("");
229 UsageError(" --no-include-patch-information: Do not include patching information.");
230 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700231 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
232 UsageError("");
233 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
234 UsageError("");
David Srbecky8dc73242015-04-12 11:40:39 +0100235 UsageError(" --include-cfi: Include call frame information in the .eh_frame section.");
236 UsageError(" The --include-debug-symbols option implies --include-cfi.");
237 UsageError("");
238 UsageError(" --no-include-cfi: Do not include call frame information in the .eh_frame section.");
239 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
241 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
242 UsageError(" Use a separate --runtime-arg switch for each argument.");
243 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700244 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000245 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700247 UsageError(" --print-pass-names: print a list of pass names");
248 UsageError("");
249 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
250 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
251 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700252 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
253 "with the setting.");
254 UsageError(" Will print default if no overridden setting exists.");
255 UsageError("");
256 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
257 "Pass2Name:Pass2OptionName:Pass2Option#");
258 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
259 UsageError(" Separator used between options is a comma.");
260 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800261 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
262 UsageError(" Example: --swap-file=/data/tmp/swap.001");
263 UsageError("");
264 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
265 UsageError(" Example: --swap-fd=10");
266 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267 std::cerr << "See log for usage error information\n";
268 exit(EXIT_FAILURE);
269}
270
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271// The primary goal of the watchdog is to prevent stuck build servers
272// during development when fatal aborts lead to a cascade of failures
273// that result in a deadlock.
274class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800275// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276#undef CHECK_PTHREAD_CALL
277#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
278 do { \
279 int rc = call args; \
280 if (rc != 0) { \
281 errno = rc; \
282 std::string message(# call); \
283 message += " failed for "; \
284 message += reason; \
285 Fatal(message); \
286 } \
287 } while (false)
288
289 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700290 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 is_watch_dog_enabled_ = is_watch_dog_enabled;
292 if (!is_watch_dog_enabled_) {
293 return;
294 }
295 shutting_down_ = false;
296 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700297 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
302 }
303 ~WatchDog() {
304 if (!is_watch_dog_enabled_) {
305 return;
306 }
307 const char* reason = "dex2oat watch dog thread shutdown";
308 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
309 shutting_down_ = true;
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
311 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
312
Kenny Root51316382014-05-13 14:59:37 -0700313 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700314
315 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
316 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
317 }
318
319 private:
320 static void* CallBack(void* arg) {
321 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
322 ::art::SetThreadName("dex2oat watch dog");
323 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700324 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 }
326
327 static void Message(char severity, const std::string& message) {
328 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
329 // cases.
330 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
331 kIsDebugBuild ? "d" : "",
332 severity,
333 getpid(),
334 GetTid(),
335 message.c_str());
336 }
337
Andreas Gampe794ad762015-02-23 08:12:24 -0800338 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 Message('F', message);
340 exit(1);
341 }
342
343 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
345 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800346 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 timespec timeout_ts;
348 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
349 const char* reason = "dex2oat watch dog thread waiting";
350 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
351 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800352 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700353 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800354 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355 } else if (rc != 0) {
356 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
357 strerror(errno)));
358 Fatal(message.c_str());
359 }
360 }
361 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
362 }
363
364 // 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 -0700365 // Debug builds are slower so they have larger timeouts.
366 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800367
Elliott Hughes956af0f2014-12-11 14:34:28 -0800368 // 6 minutes scaled by kSlowdownFactor.
369 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370
371 bool is_watch_dog_enabled_;
372 bool shutting_down_;
373 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
374 pthread_mutex_t mutex_;
375 pthread_cond_t cond_;
376 pthread_attr_t attr_;
377 pthread_t pthread_;
378};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800380static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100381 std::string::size_type colon = s.find(c);
382 if (colon == std::string::npos) {
383 Usage("Missing char %c in option %s\n", c, s.c_str());
384 }
385 // Add one to remove the char we were trimming until.
386 *parsed_value = s.substr(colon + 1);
387}
388
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800389static void ParseDouble(const std::string& option, char after_char, double min, double max,
390 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100391 std::string substring;
392 ParseStringAfterChar(option, after_char, &substring);
393 bool sane_val = true;
394 double value;
395 if (false) {
396 // TODO: this doesn't seem to work on the emulator. b/15114595
397 std::stringstream iss(substring);
398 iss >> value;
399 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
400 sane_val = iss.eof() && (value >= min) && (value <= max);
401 } else {
402 char* end = nullptr;
403 value = strtod(substring.c_str(), &end);
404 sane_val = *end == '\0' && value >= min && value <= max;
405 }
406 if (!sane_val) {
407 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
408 }
409 *parsed_value = value;
410}
411
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800412static constexpr size_t kMinDexFilesForSwap = 2;
413static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
414
415static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
416 if (is_image) {
417 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
418 return false;
419 }
420 if (dex_files.size() < kMinDexFilesForSwap) {
421 // If there are less dex files than the threshold, assume it's gonna be fine.
422 return false;
423 }
424 size_t dex_files_size = 0;
425 for (const auto* dex_file : dex_files) {
426 dex_files_size += dex_file->GetHeader().file_size_;
427 }
428 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
429}
430
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800431class Dex2Oat FINAL {
432 public:
433 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800434 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800435 instruction_set_(kRuntimeISA),
436 // Take the default set of instruction features from the build.
437 method_inliner_map_(),
438 runtime_(nullptr),
439 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
440 start_ns_(NanoTime()),
441 oat_fd_(-1),
442 zip_fd_(-1),
443 image_base_(0U),
444 image_classes_zip_filename_(nullptr),
445 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800446 compiled_classes_zip_filename_(nullptr),
447 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800448 image_(false),
449 is_host_(false),
450 dump_stats_(false),
451 dump_passes_(false),
452 dump_timing_(false),
453 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800454 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455 timings_(timings) {}
456
457 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800458 // Free opened dex files before deleting the runtime_, because ~DexFile
459 // uses MemMap, which is shut down by ~Runtime.
460 class_path_files_.clear();
461 opened_dex_files_.clear();
462
463 // Log completion time before deleting the runtime_, because this accesses
464 // the runtime.
465 LogCompletionTime();
466
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
468 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100469 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700470 }
471
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472 // Parse the arguments from the command line. In case of an unrecognized option or impossible
473 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
474 // returns, arguments have been successfully parsed.
475 void ParseArgs(int argc, char** argv) {
476 original_argc = argc;
477 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700478
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800479 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700480
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800481 // Skip over argv[0].
482 argv++;
483 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700484
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800485 if (argc == 0) {
486 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700487 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800488
489 std::string oat_symbols;
490 std::string boot_image_filename;
491 const char* compiler_filter_string = nullptr;
492 bool compile_pic = false;
493 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
494 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
495 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
496 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
497 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
498
499 // Profile file to use
500 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
501
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800502 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800503 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
504 bool include_debug_symbols = kIsDebugBuild;
David Srbecky8dc73242015-04-12 11:40:39 +0100505 bool include_cfi = kIsDebugBuild;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 bool watch_dog_enabled = true;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800507 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000508 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800510 PassManagerOptions pass_manager_options;
511
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800512 std::string error_msg;
513
514 for (int i = 0; i < argc; i++) {
515 const StringPiece option(argv[i]);
516 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 if (log_options) {
518 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
519 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800520 if (option.starts_with("--dex-file=")) {
521 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
522 } else if (option.starts_with("--dex-location=")) {
523 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
524 } else if (option.starts_with("--zip-fd=")) {
525 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
526 if (!ParseInt(zip_fd_str, &zip_fd_)) {
527 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
528 }
529 if (zip_fd_ < 0) {
530 Usage("--zip-fd passed a negative value %d", zip_fd_);
531 }
532 } else if (option.starts_with("--zip-location=")) {
533 zip_location_ = option.substr(strlen("--zip-location=")).data();
534 } else if (option.starts_with("--oat-file=")) {
535 oat_filename_ = option.substr(strlen("--oat-file=")).data();
536 } else if (option.starts_with("--oat-symbols=")) {
537 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
538 } else if (option.starts_with("--oat-fd=")) {
539 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
540 if (!ParseInt(oat_fd_str, &oat_fd_)) {
541 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
542 }
543 if (oat_fd_ < 0) {
544 Usage("--oat-fd passed a negative value %d", oat_fd_);
545 }
546 } else if (option == "--watch-dog") {
547 watch_dog_enabled = true;
548 } else if (option == "--no-watch-dog") {
549 watch_dog_enabled = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800550 } else if (option.starts_with("-j")) {
551 const char* thread_count_str = option.substr(strlen("-j")).data();
552 if (!ParseUint(thread_count_str, &thread_count_)) {
553 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
554 }
555 } else if (option.starts_with("--oat-location=")) {
556 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800557 } else if (option.starts_with("--image=")) {
558 image_filename_ = option.substr(strlen("--image=")).data();
559 } else if (option.starts_with("--image-classes=")) {
560 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
561 } else if (option.starts_with("--image-classes-zip=")) {
562 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800563 } else if (option.starts_with("--compiled-classes=")) {
564 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
565 } else if (option.starts_with("--compiled-classes-zip=")) {
566 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800567 } else if (option.starts_with("--base=")) {
568 const char* image_base_str = option.substr(strlen("--base=")).data();
569 char* end;
570 image_base_ = strtoul(image_base_str, &end, 16);
571 if (end == image_base_str || *end != '\0') {
572 Usage("Failed to parse hexadecimal value for option %s", option.data());
573 }
574 } else if (option.starts_with("--boot-image=")) {
575 boot_image_filename = option.substr(strlen("--boot-image=")).data();
576 } else if (option.starts_with("--android-root=")) {
577 android_root_ = option.substr(strlen("--android-root=")).data();
578 } else if (option.starts_with("--instruction-set=")) {
579 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
580 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800581 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800582 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
583 buf.get()[instruction_set_str.length()] = 0;
584 instruction_set_ = GetInstructionSetFromString(buf.get());
585 // arm actually means thumb2.
586 if (instruction_set_ == InstructionSet::kArm) {
587 instruction_set_ = InstructionSet::kThumb2;
588 }
589 } else if (option.starts_with("--instruction-set-variant=")) {
590 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
591 instruction_set_features_.reset(
592 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
593 if (instruction_set_features_.get() == nullptr) {
594 Usage("%s", error_msg.c_str());
595 }
596 } else if (option.starts_with("--instruction-set-features=")) {
597 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800598 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800599 instruction_set_features_.reset(
600 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
601 if (instruction_set_features_.get() == nullptr) {
602 Usage("Problem initializing default instruction set features variant: %s",
603 error_msg.c_str());
604 }
605 }
606 instruction_set_features_.reset(
607 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
608 if (instruction_set_features_.get() == nullptr) {
609 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800610 }
611 } else if (option.starts_with("--compiler-backend=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000612 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800613 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
614 if (backend_str == "Quick") {
615 compiler_kind_ = Compiler::kQuick;
616 } else if (backend_str == "Optimizing") {
617 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800618 } else {
619 Usage("Unknown compiler backend: %s", backend_str.data());
620 }
621 } else if (option.starts_with("--compiler-filter=")) {
622 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
623 } else if (option == "--compile-pic") {
624 compile_pic = true;
625 } else if (option.starts_with("--huge-method-max=")) {
626 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
627 if (!ParseInt(threshold, &huge_method_threshold)) {
628 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
629 }
630 if (huge_method_threshold < 0) {
631 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
632 }
633 } else if (option.starts_with("--large-method-max=")) {
634 const char* threshold = option.substr(strlen("--large-method-max=")).data();
635 if (!ParseInt(threshold, &large_method_threshold)) {
636 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
637 }
638 if (large_method_threshold < 0) {
639 Usage("--large-method-max passed a negative value %s", large_method_threshold);
640 }
641 } else if (option.starts_with("--small-method-max=")) {
642 const char* threshold = option.substr(strlen("--small-method-max=")).data();
643 if (!ParseInt(threshold, &small_method_threshold)) {
644 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
645 }
646 if (small_method_threshold < 0) {
647 Usage("--small-method-max passed a negative value %s", small_method_threshold);
648 }
649 } else if (option.starts_with("--tiny-method-max=")) {
650 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
651 if (!ParseInt(threshold, &tiny_method_threshold)) {
652 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
653 }
654 if (tiny_method_threshold < 0) {
655 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
656 }
657 } else if (option.starts_with("--num-dex-methods=")) {
658 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
659 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
660 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
661 }
662 if (num_dex_methods_threshold < 0) {
663 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
664 }
665 } else if (option == "--host") {
666 is_host_ = true;
667 } else if (option == "--runtime-arg") {
668 if (++i >= argc) {
669 Usage("Missing required argument for --runtime-arg");
670 }
671 if (log_options) {
672 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
673 }
674 runtime_args_.push_back(argv[i]);
675 } else if (option == "--dump-timing") {
676 dump_timing_ = true;
677 } else if (option == "--dump-passes") {
678 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000679 } else if (option.starts_with("--dump-cfg=")) {
680 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800681 } else if (option == "--dump-stats") {
682 dump_stats_ = true;
683 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
684 include_debug_symbols = true;
685 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
686 include_debug_symbols = false;
David Srbecky8dc73242015-04-12 11:40:39 +0100687 } else if (option == "--include-cfi") {
688 include_cfi = true;
689 } else if (option == "--no-include-cfi") {
690 include_cfi = false;
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800691 } else if (option == "--debuggable") {
692 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800693 } else if (option.starts_with("--profile-file=")) {
694 profile_file_ = option.substr(strlen("--profile-file=")).data();
695 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
696 } else if (option == "--no-profile-file") {
697 // No profile
698 } else if (option.starts_with("--top-k-profile-threshold=")) {
699 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
700 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800701 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800702 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800703 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
704 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800706 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
707 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800709 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800711 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
712 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800713 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800714 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800715 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800716 const std::string options = option.substr(strlen("--pass-options=")).data();
717 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800718 } else if (option == "--include-patch-information") {
719 include_patch_information = true;
720 } else if (option == "--no-include-patch-information") {
721 include_patch_information = false;
722 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800723 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
724 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800725 gLogVerbosity.compiler = false;
726 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800727 } else if (option.starts_with("--dump-init-failures=")) {
728 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
729 init_failure_output_.reset(new std::ofstream(file_name));
730 if (init_failure_output_.get() == nullptr) {
731 LOG(ERROR) << "Failed to allocate ofstream";
732 } else if (init_failure_output_->fail()) {
733 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
734 << "failures.";
735 init_failure_output_.reset();
736 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800737 } else if (option.starts_with("--swap-file=")) {
738 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
739 } else if (option.starts_with("--swap-fd=")) {
740 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
741 if (!ParseInt(swap_fd_str, &swap_fd_)) {
742 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
743 }
744 if (swap_fd_ < 0) {
745 Usage("--swap-fd passed a negative value %d", swap_fd_);
746 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800747 } else if (option == "--abort-on-hard-verifier-error") {
748 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800749 } else {
750 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800752 }
753
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000754 image_ = (!image_filename_.empty());
755 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
756 // If no specific compiler is requested, the current behavior is
757 // to compile the boot image with Quick, and the rest with Optimizing.
758 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
759 }
760
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000761 if (compiler_kind_ == Compiler::kOptimizing) {
762 // Optimizing only supports PIC mode.
763 compile_pic = true;
764 }
765
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800766 if (oat_filename_.empty() && oat_fd_ == -1) {
767 Usage("Output must be supplied with either --oat-file or --oat-fd");
768 }
769
770 if (!oat_filename_.empty() && oat_fd_ != -1) {
771 Usage("--oat-file should not be used with --oat-fd");
772 }
773
774 if (!oat_symbols.empty() && oat_fd_ != -1) {
775 Usage("--oat-symbols should not be used with --oat-fd");
776 }
777
778 if (!oat_symbols.empty() && is_host_) {
779 Usage("--oat-symbols should not be used with --host");
780 }
781
782 if (oat_fd_ != -1 && !image_filename_.empty()) {
783 Usage("--oat-fd should not be used with --image");
784 }
785
786 if (android_root_.empty()) {
787 const char* android_root_env_var = getenv("ANDROID_ROOT");
788 if (android_root_env_var == nullptr) {
789 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800791 android_root_ += android_root_env_var;
792 }
793
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800794 if (!image_ && boot_image_filename.empty()) {
795 boot_image_filename += android_root_;
796 boot_image_filename += "/framework/boot.art";
797 }
798 if (!boot_image_filename.empty()) {
799 boot_image_option_ += "-Ximage:";
800 boot_image_option_ += boot_image_filename;
801 }
802
803 if (image_classes_filename_ != nullptr && !image_) {
804 Usage("--image-classes should only be used with --image");
805 }
806
807 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
808 Usage("--image-classes should not be used with --boot-image");
809 }
810
811 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
812 Usage("--image-classes-zip should be used with --image-classes");
813 }
814
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800815 if (compiled_classes_filename_ != nullptr && !image_) {
816 Usage("--compiled-classes should only be used with --image");
817 }
818
819 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
820 Usage("--compiled-classes should not be used with --boot-image");
821 }
822
823 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
824 Usage("--compiled-classes-zip should be used with --compiled-classes");
825 }
826
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800827 if (dex_filenames_.empty() && zip_fd_ == -1) {
828 Usage("Input must be supplied with either --dex-file or --zip-fd");
829 }
830
831 if (!dex_filenames_.empty() && zip_fd_ != -1) {
832 Usage("--dex-file should not be used with --zip-fd");
833 }
834
835 if (!dex_filenames_.empty() && !zip_location_.empty()) {
836 Usage("--dex-file should not be used with --zip-location");
837 }
838
839 if (dex_locations_.empty()) {
840 for (const char* dex_file_name : dex_filenames_) {
841 dex_locations_.push_back(dex_file_name);
842 }
843 } else if (dex_locations_.size() != dex_filenames_.size()) {
844 Usage("--dex-location arguments do not match --dex-file arguments");
845 }
846
847 if (zip_fd_ != -1 && zip_location_.empty()) {
848 Usage("--zip-location should be supplied with --zip-fd");
849 }
850
851 if (boot_image_option_.empty()) {
852 if (image_base_ == 0) {
853 Usage("Non-zero --base not specified");
854 }
855 }
856
857 oat_stripped_ = oat_filename_;
858 if (!oat_symbols.empty()) {
859 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700860 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800861 oat_unstripped_ = oat_filename_;
862 }
863
864 // If no instruction set feature was given, use the default one for the target
865 // instruction set.
866 if (instruction_set_features_.get() == nullptr) {
867 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800868 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
869 if (instruction_set_features_.get() == nullptr) {
870 Usage("Problem initializing default instruction set features variant: %s",
871 error_msg.c_str());
872 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800873 }
874
875 if (instruction_set_ == kRuntimeISA) {
876 std::unique_ptr<const InstructionSetFeatures> runtime_features(
877 InstructionSetFeatures::FromCppDefines());
878 if (!instruction_set_features_->Equals(runtime_features.get())) {
879 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
880 << *instruction_set_features_ << ") and those of dex2oat executable ("
881 << *runtime_features <<") for the command line:\n"
882 << CommandLine();
883 }
884 }
885
886 if (compiler_filter_string == nullptr) {
Douglas Leung027f0ff2015-02-27 19:05:03 -0800887 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800888 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100889
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800890 CHECK(compiler_filter_string != nullptr);
891 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
892 if (strcmp(compiler_filter_string, "verify-none") == 0) {
893 compiler_filter = CompilerOptions::kVerifyNone;
894 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
895 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700896 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
897 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800898 } else if (strcmp(compiler_filter_string, "space") == 0) {
899 compiler_filter = CompilerOptions::kSpace;
900 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
901 compiler_filter = CompilerOptions::kBalanced;
902 } else if (strcmp(compiler_filter_string, "speed") == 0) {
903 compiler_filter = CompilerOptions::kSpeed;
904 } else if (strcmp(compiler_filter_string, "everything") == 0) {
905 compiler_filter = CompilerOptions::kEverything;
906 } else if (strcmp(compiler_filter_string, "time") == 0) {
907 compiler_filter = CompilerOptions::kTime;
908 } else {
909 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
910 }
911
912 // Checks are all explicit until we know the architecture.
913 bool implicit_null_checks = false;
914 bool implicit_so_checks = false;
915 bool implicit_suspend_checks = false;
916 // Set the compilation target's implicit checks options.
917 switch (instruction_set_) {
918 case kArm:
919 case kThumb2:
920 case kArm64:
921 case kX86:
922 case kX86_64:
923 implicit_null_checks = true;
924 implicit_so_checks = true;
925 break;
926
927 default:
928 // Defaults are correct.
929 break;
930 }
931
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800932 if (debuggable) {
933 // TODO: Consider adding CFI info and symbols here.
934 }
935
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800936 compiler_options_.reset(new CompilerOptions(compiler_filter,
937 huge_method_threshold,
938 large_method_threshold,
939 small_method_threshold,
940 tiny_method_threshold,
941 num_dex_methods_threshold,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800942 include_patch_information,
943 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800944 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945 include_debug_symbols,
David Srbecky8dc73242015-04-12 11:40:39 +0100946 include_cfi,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800947 implicit_null_checks,
948 implicit_so_checks,
949 implicit_suspend_checks,
950 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800951 verbose_methods_.empty() ?
952 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800953 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800954 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800955 init_failure_output_.get(),
956 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800957
958 // Done with usage checks, enable watchdog if requested
959 if (watch_dog_enabled) {
960 watchdog_.reset(new WatchDog(true));
961 }
962
963 // Fill some values into the key-value store for the oat header.
964 key_value_store_.reset(new SafeMap<std::string, std::string>());
965
966 // Insert some compiler things.
967 {
968 std::ostringstream oss;
969 for (int i = 0; i < argc; ++i) {
970 if (i > 0) {
971 oss << ' ';
972 }
973 oss << argv[i];
974 }
975 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
976 oss.str(""); // Reset.
977 oss << kRuntimeISA;
978 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
979 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
980 }
981 }
982
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800983 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
984 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800985 bool OpenFile() {
986 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
987 if (create_file) {
988 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
989 if (oat_location_.empty()) {
990 oat_location_ = oat_filename_;
991 }
992 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800993 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800994 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800995 if (oat_file_->SetLength(0) != 0) {
996 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
997 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800998 }
999 if (oat_file_.get() == nullptr) {
1000 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1001 return false;
1002 }
1003 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1004 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001005 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001006 return false;
1007 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001008
1009 // Swap file handling.
1010 //
1011 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1012 // that we can use for swap.
1013 //
1014 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1015 // will immediately unlink to satisfy the swap fd assumption.
1016 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1017 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1018 if (swap_file.get() == nullptr) {
1019 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1020 return false;
1021 }
1022 swap_fd_ = swap_file->Fd();
1023 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1024 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1025 // released immediately.
1026 unlink(swap_file_name_.c_str());
1027 }
1028
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001029 return true;
1030 }
1031
Andreas Gampea650e702014-12-03 14:28:02 -08001032 void EraseOatFile() {
1033 DCHECK(oat_file_.get() != nullptr);
1034 oat_file_->Erase();
1035 oat_file_.reset();
1036 }
1037
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001038 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1039 // boot class path.
1040 bool Setup() {
1041 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1042 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001043 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1044 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001045 std::string boot_class_path = "-Xbootclasspath:";
1046 boot_class_path += Join(dex_filenames_, ':');
1047 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1048 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1049 boot_class_path_locations += Join(dex_locations_, ':');
1050 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001051 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001052 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001053 }
1054 for (size_t i = 0; i < runtime_args_.size(); i++) {
1055 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001056 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001057
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001058 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001059 callbacks_.reset(new QuickCompilerCallbacks(
1060 verification_results_.get(),
1061 &method_inliner_map_,
1062 image_ ?
1063 CompilerCallbacks::CallbackMode::kCompileBootImage :
1064 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001065 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1066 runtime_options.push_back(
1067 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1068
Andreas Gampe1d00add2015-02-27 19:35:46 -08001069 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1070 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1071 // have been stripped in preopting, anyways).
1072 if (!image_) {
1073 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1074 }
1075
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001076 if (!CreateRuntime(runtime_options)) {
1077 return false;
1078 }
1079
1080 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1081 // Runtime::Start, give it away now so that we don't starve GC.
1082 Thread* self = Thread::Current();
1083 self->TransitionFromRunnableToSuspended(kNative);
1084 // If we're doing the image, override the compiler filter to force full compilation. Must be
1085 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1086 // compilation of class initializers.
1087 // Whilst we're in native take the opportunity to initialize well known classes.
1088 WellKnownClasses::Init(self->GetJniEnv());
1089
1090 // If --image-classes was specified, calculate the full list of classes to include in the image
1091 if (image_classes_filename_ != nullptr) {
1092 std::string error_msg;
1093 if (image_classes_zip_filename_ != nullptr) {
1094 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1095 image_classes_filename_,
1096 &error_msg));
1097 } else {
1098 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1099 }
1100 if (image_classes_.get() == nullptr) {
1101 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1102 "': " << error_msg;
1103 return false;
1104 }
1105 } else if (image_) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001106 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001107 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001108 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1109 // image.
1110 if (compiled_classes_filename_ != nullptr) {
1111 std::string error_msg;
1112 if (compiled_classes_zip_filename_ != nullptr) {
1113 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1114 compiled_classes_filename_,
1115 &error_msg));
1116 } else {
1117 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1118 }
1119 if (compiled_classes_.get() == nullptr) {
1120 LOG(ERROR) << "Failed to create list of compiled classes from '"
1121 << compiled_classes_filename_ << "': " << error_msg;
1122 return false;
1123 }
1124 } else if (image_) {
1125 compiled_classes_.reset(nullptr); // By default compile everything.
1126 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001127
1128 if (boot_image_option_.empty()) {
1129 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1130 } else {
1131 if (dex_filenames_.empty()) {
1132 ATRACE_BEGIN("Opening zip archive from file descriptor");
1133 std::string error_msg;
1134 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1135 zip_location_.c_str(),
1136 &error_msg));
1137 if (zip_archive.get() == nullptr) {
1138 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1139 << error_msg;
1140 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001141 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001142 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001143 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1144 << "': " << error_msg;
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 ATRACE_END();
1151 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001152 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001153 if (failure_count > 0) {
1154 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1155 return false;
1156 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001157 for (auto& dex_file : opened_dex_files_) {
1158 dex_files_.push_back(dex_file.get());
1159 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001160 }
1161
1162 constexpr bool kSaveDexInput = false;
1163 if (kSaveDexInput) {
1164 for (size_t i = 0; i < dex_files_.size(); ++i) {
1165 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001166 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1167 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1169 if (tmp_file.get() == nullptr) {
1170 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1171 << ". Try: adb shell chmod 777 /data/local/tmp";
1172 continue;
1173 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001174 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1175 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1176 UNUSED(tmp_file->Flush());
1177 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178 LOG(INFO) << "Wrote input to " << tmp_file_name;
1179 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001180 }
1181 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001182 // Ensure opened dex files are writable for dex-to-dex transformations.
1183 for (const auto& dex_file : dex_files_) {
1184 if (!dex_file->EnableWrite()) {
1185 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001186 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001187 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001188
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001189 // If we use a swap file, ensure we are above the threshold to make it necessary.
1190 if (swap_fd_ != -1) {
1191 if (!UseSwap(image_, dex_files_)) {
1192 close(swap_fd_);
1193 swap_fd_ = -1;
1194 LOG(INFO) << "Decided to run without swap.";
1195 } else {
1196 LOG(INFO) << "Accepted running with swap.";
1197 }
1198 }
1199 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1200
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001201 /*
1202 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1203 * Don't bother to check if we're doing the image.
1204 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001205 if (!image_ &&
1206 compiler_options_->IsCompilationEnabled() &&
1207 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 size_t num_methods = 0;
1209 for (size_t i = 0; i != dex_files_.size(); ++i) {
1210 const DexFile* dex_file = dex_files_[i];
1211 CHECK(dex_file != nullptr);
1212 num_methods += dex_file->NumMethodIds();
1213 }
1214 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1215 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1216 VLOG(compiler) << "Below method threshold, compiling anyways";
1217 }
1218 }
1219
1220 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001221 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001222
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001223 // Create and invoke the compiler driver. This will compile all the dex files.
1224 void Compile() {
1225 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1226 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001227
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001228 // Handle and ClassLoader creation needs to come after Runtime::Create
1229 jobject class_loader = nullptr;
1230 Thread* self = Thread::Current();
1231 if (!boot_image_option_.empty()) {
1232 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001233 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001234 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001235
1236 // Classpath: first the class-path given.
1237 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001238 for (auto& class_path_file : class_path_files_) {
1239 class_path_files.push_back(class_path_file.get());
1240 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001241
1242 // Store the classpath we have right now.
1243 key_value_store_->Put(OatHeader::kClassPathKey,
1244 OatFile::EncodeDexFileDependencies(class_path_files));
1245
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001246 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1247 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001248
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001249 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 }
1251
1252 driver_.reset(new CompilerDriver(compiler_options_.get(),
1253 verification_results_.get(),
1254 &method_inliner_map_,
1255 compiler_kind_,
1256 instruction_set_,
1257 instruction_set_features_.get(),
1258 image_,
1259 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001260 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001261 thread_count_,
1262 dump_stats_,
1263 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001264 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001265 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001266 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001267 profile_file_));
1268
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001269 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001270 }
1271
Brian Carlstrom7940e442013-07-12 13:46:57 -07001272 // Notes on the interleaving of creating the image and oat file to
1273 // ensure the references between the two are correct.
1274 //
1275 // Currently we have a memory layout that looks something like this:
1276 //
1277 // +--------------+
1278 // | image |
1279 // +--------------+
1280 // | boot oat |
1281 // +--------------+
1282 // | alloc spaces |
1283 // +--------------+
1284 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001285 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001286 //
1287 // 1. The image is expected to be loaded at an absolute address and
1288 // contains Objects with absolute pointers within the image.
1289 //
1290 // 2. There are absolute pointers from Methods in the image to their
1291 // code in the oat.
1292 //
1293 // 3. There are absolute pointers from the code in the oat to Methods
1294 // in the image.
1295 //
1296 // 4. There are absolute pointers from code in the oat to other code
1297 // in the oat.
1298 //
1299 // To get this all correct, we go through several steps.
1300 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001301 // 1. We prepare offsets for all data in the oat file and calculate
1302 // the oat data size and code size. During this stage, we also set
1303 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001304 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001305 // 2. We prepare offsets for the objects in the image and calculate
1306 // the image size.
1307 //
1308 // 3. We create the oat file. Originally this was just our own proprietary
1309 // file but now it is contained within an ELF dynamic object (aka an .so
1310 // file). Since we know the image size and oat data size and code size we
1311 // can prepare the ELF headers and we then know the ELF memory segment
1312 // layout and we can now resolve all references. The compiler provides
1313 // LinkerPatch information in each CompiledMethod and we resolve these,
1314 // using the layout information and image object locations provided by
1315 // image writer, as we're writing the method code.
1316 //
1317 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001318 // will be loaded after itself. Originally when oat file was simply
1319 // memory mapped so we could predict where its contents were based
1320 // on the file size. Now that it is an ELF file, we need to inspect
1321 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001322 // where the oat header is located within.
1323 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001324 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001325 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326 // load the .so at the desired location at runtime by offsetting the
1327 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001328 // TODO: Do this in step 3. We already know the layout there.
1329 //
1330 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1331 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001332
1333
1334 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1335 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001336 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1337 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001338 bool CreateOatFile() {
1339 CHECK(key_value_store_.get() != nullptr);
1340
1341 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1342
1343 std::unique_ptr<OatWriter> oat_writer;
1344 {
1345 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1346 std::string image_file_location;
1347 uint32_t image_file_location_oat_checksum = 0;
1348 uintptr_t image_file_location_oat_data_begin = 0;
1349 int32_t image_patch_delta = 0;
1350 if (image_) {
1351 PrepareImageWriter(image_base_);
1352 } else {
1353 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1354 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1355 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1356 image_file_location_oat_data_begin =
1357 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1358 image_file_location = image_space->GetImageFilename();
1359 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1360 }
1361
1362 if (!image_file_location.empty()) {
1363 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1364 }
1365
1366 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1367 image_file_location_oat_data_begin,
1368 image_patch_delta,
1369 driver_.get(),
1370 image_writer_.get(),
1371 timings_,
1372 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001373 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001374
1375 if (image_) {
1376 // The OatWriter constructor has already updated offsets in methods and we need to
1377 // prepare method offsets in the image address space for direct method patching.
1378 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1379 if (!image_writer_->PrepareImageAddressSpace()) {
1380 LOG(ERROR) << "Failed to prepare image address space.";
1381 return false;
1382 }
1383 }
1384
1385 {
1386 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1387 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1388 oat_file_.get())) {
1389 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1390 return false;
1391 }
1392 }
1393
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001394 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1395 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 }
1397
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001398 // If we are compiling an image, invoke the image creation routine. Else just skip.
1399 bool HandleImage() {
1400 if (image_) {
1401 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1402 if (!CreateImageFile()) {
1403 return false;
1404 }
1405 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001406 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001407 return true;
1408 }
1409
Andreas Gampe10e477d2014-11-19 12:57:42 -08001410 // Create a copy from unstripped to stripped.
1411 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001412 // If we don't want to strip in place, copy from unstripped location to stripped location.
1413 // We need to strip after image creation because FixupElf needs to use .strtab.
1414 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001415 // If the oat file is still open, flush it.
1416 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1417 if (!FlushCloseOatFile()) {
1418 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001419 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001420 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001421
1422 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001423 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1424 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1425 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001426 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001427 while (true) {
1428 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1429 if (bytes_read <= 0) {
1430 break;
1431 }
1432 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1433 CHECK(write_ok);
1434 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001435 if (out->FlushCloseOrErase() != 0) {
1436 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1437 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001438 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001439 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001440 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001441 return true;
1442 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001443
Andreas Gampe10e477d2014-11-19 12:57:42 -08001444 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001445 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001446 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1447 if (oat_file_->Flush() != 0) {
1448 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1449 << oat_filename_;
1450 oat_file_->Erase();
1451 return false;
1452 }
1453 }
1454 return true;
1455 }
1456
1457 bool FlushCloseOatFile() {
1458 if (oat_file_.get() != nullptr) {
1459 std::unique_ptr<File> tmp(oat_file_.release());
1460 if (tmp->FlushCloseOrErase() != 0) {
1461 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1462 << oat_filename_;
1463 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001464 }
1465 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001466 return true;
1467 }
1468
1469 void DumpTiming() {
1470 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1471 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1472 }
1473 if (dump_passes_) {
1474 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1475 }
1476 }
1477
1478 CompilerOptions* GetCompilerOptions() const {
1479 return compiler_options_.get();
1480 }
1481
Andreas Gampe10e477d2014-11-19 12:57:42 -08001482 bool IsImage() const {
1483 return image_;
1484 }
1485
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001486 bool IsHost() const {
1487 return is_host_;
1488 }
1489
1490 private:
1491 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1492 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001493 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1494 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001495 size_t failure_count = 0;
1496 for (size_t i = 0; i < dex_filenames.size(); i++) {
1497 const char* dex_filename = dex_filenames[i];
1498 const char* dex_location = dex_locations[i];
1499 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1500 std::string error_msg;
1501 if (!OS::FileExists(dex_filename)) {
1502 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1503 continue;
1504 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001505 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001506 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1507 ++failure_count;
1508 }
1509 ATRACE_END();
1510 }
1511 return failure_count;
1512 }
1513
Andreas Gampee3712d02015-04-09 14:46:31 -07001514 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1515 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1516 // efficient, but under normal circumstances the list is neither large nor is this part too
1517 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001518 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1519 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001520 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001521 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001522 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1523 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001524 return true;
1525 }
1526 }
1527 return false;
1528 }
1529
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001530 // Appends to opened_dex_files any elements of class_path that dex_files
1531 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001532 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001533 std::vector<const DexFile*> dex_files,
1534 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1535 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001536 std::vector<std::string> parsed;
1537 Split(class_path, ':', &parsed);
1538 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1539 ScopedObjectAccess soa(Thread::Current());
1540 for (size_t i = 0; i < parsed.size(); ++i) {
1541 if (DexFilesContains(dex_files, parsed[i])) {
1542 continue;
1543 }
1544 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001545 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001546 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1547 }
1548 }
1549 }
1550
1551 // Create a runtime necessary for compilation.
1552 bool CreateRuntime(const RuntimeOptions& runtime_options)
1553 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1554 if (!Runtime::Create(runtime_options, false)) {
1555 LOG(ERROR) << "Failed to create runtime";
1556 return false;
1557 }
1558 Runtime* runtime = Runtime::Current();
1559 runtime->SetInstructionSet(instruction_set_);
1560 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1561 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1562 if (!runtime->HasCalleeSaveMethod(type)) {
1563 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1564 }
1565 }
1566 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001567
1568 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1569 // set up.
1570 interpreter::UnstartedRuntimeInitialize();
1571
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001572 runtime->GetClassLinker()->RunRootClinits();
1573 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001574
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001575 return true;
1576 }
1577
1578 void PrepareImageWriter(uintptr_t image_base) {
1579 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1580 }
1581
1582 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1583 bool CreateImageFile()
1584 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1585 CHECK(image_writer_ != nullptr);
1586 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1587 LOG(ERROR) << "Failed to create image file " << image_filename_;
1588 return false;
1589 }
1590 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1591
1592 // Destroy ImageWriter before doing FixupElf.
1593 image_writer_.reset();
1594
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001595 // Do not fix up the ELF file if we are --compile-pic
1596 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001597 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1598 if (oat_file.get() == nullptr) {
1599 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1600 return false;
1601 }
1602
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001604 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001605 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1606 return false;
1607 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001608
1609 if (oat_file->FlushCloseOrErase()) {
1610 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1611 return false;
1612 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001613 }
1614
1615 return true;
1616 }
1617
1618 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001619 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1620 const char* image_classes_filename) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001621 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1622 std::ifstream::in));
1623 if (image_classes_file.get() == nullptr) {
1624 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1625 return nullptr;
1626 }
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001627 std::unique_ptr<std::unordered_set<std::string>> result(ReadImageClasses(*image_classes_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001628 image_classes_file->close();
1629 return result.release();
1630 }
1631
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001632 static std::unordered_set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1633 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1634 new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001635 while (image_classes_stream.good()) {
1636 std::string dot;
1637 std::getline(image_classes_stream, dot);
1638 if (StartsWith(dot, "#") || dot.empty()) {
1639 continue;
1640 }
1641 std::string descriptor(DotToDescriptor(dot.c_str()));
1642 image_classes->insert(descriptor);
1643 }
1644 return image_classes.release();
1645 }
1646
1647 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001648 static std::unordered_set<std::string>* ReadImageClassesFromZip(
1649 const char* zip_filename,
1650 const char* image_classes_filename,
1651 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001652 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1653 if (zip_archive.get() == nullptr) {
1654 return nullptr;
1655 }
1656 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1657 if (zip_entry.get() == nullptr) {
1658 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1659 zip_filename, error_msg->c_str());
1660 return nullptr;
1661 }
1662 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1663 image_classes_filename,
1664 error_msg));
1665 if (image_classes_file.get() == nullptr) {
1666 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1667 zip_filename, error_msg->c_str());
1668 return nullptr;
1669 }
1670 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1671 image_classes_file->Size());
1672 std::istringstream image_classes_stream(image_classes_string);
1673 return ReadImageClasses(image_classes_stream);
1674 }
1675
Mathieu Chartier49285c52014-12-02 15:43:48 -08001676 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001677 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1678 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001679 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001680 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001681 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001682 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001683 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1684 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001685 }
1686
1687 std::unique_ptr<CompilerOptions> compiler_options_;
1688 Compiler::Kind compiler_kind_;
1689
1690 InstructionSet instruction_set_;
1691 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1692
1693 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1694
1695 std::unique_ptr<VerificationResults> verification_results_;
1696 DexFileToMethodInlinerMap method_inliner_map_;
1697 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1698
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001699 // Ownership for the class path files.
1700 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1701
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001702 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1703 // in an orderly fashion. The destructor takes care of deleting this.
1704 Runtime* runtime_;
1705
1706 size_t thread_count_;
1707 uint64_t start_ns_;
1708 std::unique_ptr<WatchDog> watchdog_;
1709 std::unique_ptr<File> oat_file_;
1710 std::string oat_stripped_;
1711 std::string oat_unstripped_;
1712 std::string oat_location_;
1713 std::string oat_filename_;
1714 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 std::vector<const char*> dex_filenames_;
1716 std::vector<const char*> dex_locations_;
1717 int zip_fd_;
1718 std::string zip_location_;
1719 std::string boot_image_option_;
1720 std::vector<const char*> runtime_args_;
1721 std::string image_filename_;
1722 uintptr_t image_base_;
1723 const char* image_classes_zip_filename_;
1724 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001725 const char* compiled_classes_zip_filename_;
1726 const char* compiled_classes_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001727 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1728 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001729 bool image_;
1730 std::unique_ptr<ImageWriter> image_writer_;
1731 bool is_host_;
1732 std::string android_root_;
1733 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001734 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001735 std::unique_ptr<CompilerDriver> driver_;
1736 std::vector<std::string> verbose_methods_;
1737 bool dump_stats_;
1738 bool dump_passes_;
1739 bool dump_timing_;
1740 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001741 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001742 std::string swap_file_name_;
1743 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001744 std::string profile_file_; // Profile file to use
1745 TimingLogger* timings_;
1746 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001747 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001748
1749 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1750};
1751
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001752const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1753
1754static void b13564922() {
1755#if defined(__linux__) && defined(__arm__)
1756 int major, minor;
1757 struct utsname uts;
1758 if (uname(&uts) != -1 &&
1759 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1760 ((major < 3) || ((major == 3) && (minor < 4)))) {
1761 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1762 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1763 int old_personality = personality(0xffffffff);
1764 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1765 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1766 if (new_personality == -1) {
1767 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1768 }
1769 }
1770 }
1771#endif
1772}
1773
Andreas Gampe10e477d2014-11-19 12:57:42 -08001774static int CompileImage(Dex2Oat& dex2oat) {
1775 dex2oat.Compile();
1776
1777 // Create the boot.oat.
1778 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001779 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001780 return EXIT_FAILURE;
1781 }
1782
1783 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1784 // re-opened from the unstripped name.
1785 if (!dex2oat.FlushCloseOatFile()) {
1786 return EXIT_FAILURE;
1787 }
1788
1789 // Creates the boot.art and patches the boot.oat.
1790 if (!dex2oat.HandleImage()) {
1791 return EXIT_FAILURE;
1792 }
1793
1794 // When given --host, finish early without stripping.
1795 if (dex2oat.IsHost()) {
1796 dex2oat.DumpTiming();
1797 return EXIT_SUCCESS;
1798 }
1799
1800 // Copy unstripped to stripped location, if necessary.
1801 if (!dex2oat.CopyUnstrippedToStripped()) {
1802 return EXIT_FAILURE;
1803 }
1804
Andreas Gampe10e477d2014-11-19 12:57:42 -08001805 // FlushClose again, as stripping might have re-opened the oat file.
1806 if (!dex2oat.FlushCloseOatFile()) {
1807 return EXIT_FAILURE;
1808 }
1809
1810 dex2oat.DumpTiming();
1811 return EXIT_SUCCESS;
1812}
1813
1814static int CompileApp(Dex2Oat& dex2oat) {
1815 dex2oat.Compile();
1816
1817 // Create the app oat.
1818 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001819 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001820 return EXIT_FAILURE;
1821 }
1822
1823 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1824 // which we would lose.
1825 if (!dex2oat.FlushOatFile()) {
1826 return EXIT_FAILURE;
1827 }
1828
1829 // When given --host, finish early without stripping.
1830 if (dex2oat.IsHost()) {
1831 if (!dex2oat.FlushCloseOatFile()) {
1832 return EXIT_FAILURE;
1833 }
1834
1835 dex2oat.DumpTiming();
1836 return EXIT_SUCCESS;
1837 }
1838
1839 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1840 // unstripped version. If this is given, we expect to be able to open writable files by name.
1841 if (!dex2oat.CopyUnstrippedToStripped()) {
1842 return EXIT_FAILURE;
1843 }
1844
Andreas Gampe10e477d2014-11-19 12:57:42 -08001845 // Flush and close the file.
1846 if (!dex2oat.FlushCloseOatFile()) {
1847 return EXIT_FAILURE;
1848 }
1849
1850 dex2oat.DumpTiming();
1851 return EXIT_SUCCESS;
1852}
1853
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001854static int dex2oat(int argc, char** argv) {
1855 b13564922();
1856
1857 TimingLogger timings("compiler", false, false);
1858
1859 Dex2Oat dex2oat(&timings);
1860
1861 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1862 dex2oat.ParseArgs(argc, argv);
1863
1864 // Check early that the result of compilation can be written
1865 if (!dex2oat.OpenFile()) {
1866 return EXIT_FAILURE;
1867 }
1868
1869 LOG(INFO) << CommandLine();
1870
1871 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001872 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001873 return EXIT_FAILURE;
1874 }
1875
Andreas Gampe10e477d2014-11-19 12:57:42 -08001876 if (dex2oat.IsImage()) {
1877 return CompileImage(dex2oat);
1878 } else {
1879 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001880 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001881}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001882} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001883
1884int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001885 int result = art::dex2oat(argc, argv);
1886 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1887 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1888 // should not destruct the runtime in this case.
1889 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1890 exit(result);
1891 }
1892 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001893}