blob: abfd2b09bfeff47ced38055cca1d82459b021ae5 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
Vladimir Markof94b7812014-06-05 15:48:04 +010028#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
Ian Rogerscf7f1912014-10-22 22:06:39 -070033#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080034#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070035
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include "arch/instruction_set_features.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070037#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000043#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000044#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070046#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000047#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070048#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080051#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080052#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070053#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070058#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070068#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
Brian Carlstrom6449c622014-02-10 23:48:36 -080075static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79 std::vector<std::string> command;
80 for (int i = 0; i < original_argc; ++i) {
81 command.push_back(original_argv[i]);
82 }
83 return Join(command, ' ');
84}
85
Brian Carlstrom7940e442013-07-12 13:46:57 -070086static void UsageErrorV(const char* fmt, va_list ap) {
87 std::string error;
88 StringAppendV(&error, fmt, ap);
89 LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93 va_list ap;
94 va_start(ap, fmt);
95 UsageErrorV(fmt, ap);
96 va_end(ap);
97}
98
Ian Rogers7223d442014-10-10 20:05:39 -070099[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700100 va_list ap;
101 va_start(ap, fmt);
102 UsageErrorV(fmt, ap);
103 va_end(ap);
104
Brian Carlstrom6449c622014-02-10 23:48:36 -0800105 UsageError("Command: %s", CommandLine().c_str());
106
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 UsageError("Usage: dex2oat [options]...");
108 UsageError("");
109 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
110 UsageError(" Example: --dex-file=/system/framework/core.jar");
111 UsageError("");
112 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113 UsageError(" containing a classes.dex file to compile.");
114 UsageError(" Example: --zip-fd=5");
115 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700116 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
117 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
119 UsageError("");
120 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121 UsageError(" Example: --oat-file=/system/framework/boot.oat");
122 UsageError("");
123 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900124 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 UsageError("");
126 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127 UsageError(" to the file descriptor specified by --oat-fd.");
128 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129 UsageError("");
130 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
132 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 UsageError(" --image=<file.art>: specifies the output image filename.");
134 UsageError(" Example: --image=/system/framework/boot.art");
135 UsageError("");
136 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
137 UsageError(" Example: --image=frameworks/base/preloaded-classes");
138 UsageError("");
139 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
140 UsageError(" Example: --base=0x50000000");
141 UsageError("");
142 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
143 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000144 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145 UsageError("");
146 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
147 UsageError(" Example: --android-root=out/host/linux-x86");
148 UsageError(" Default: $ANDROID_ROOT");
149 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700150 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
151 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 UsageError(" Example: --instruction-set=x86");
153 UsageError(" Default: arm");
154 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700155 UsageError(" --instruction-set-features=...,: Specify instruction set features");
156 UsageError(" Example: --instruction-set-features=div");
157 UsageError(" Default: default");
158 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700159 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
160 UsageError(" Default: disabled");
161 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800162 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800164 UsageError(" Example: --compiler-backend=Optimizing");
165 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000166 UsageError(" Default: Optimizing");
167 } else {
168 UsageError(" Default: Quick");
169 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100171 UsageError(" --compiler-filter="
172 "(verify-none"
173 "|interpret-only"
174 "|space"
175 "|balanced"
176 "|speed"
177 "|everything"
178 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700179 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800180 UsageError(" Example: --compiler-filter=everything");
181#if ART_SMALL_MODE
182 UsageError(" Default: interpret-only");
183#else
184 UsageError(" Default: speed");
185#endif
186 UsageError("");
187 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
188 UsageError(" method for compiler filter tuning.");
189 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
190 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
191 UsageError("");
192 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
193 UsageError(" method for compiler filter tuning.");
194 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
196 UsageError("");
197 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
198 UsageError(" method for compiler filter tuning.");
199 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
200 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
201 UsageError("");
202 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
203 UsageError(" method for compiler filter tuning.");
204 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
205 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
206 UsageError("");
207 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
208 UsageError(" method for compiler filter tuning.");
209 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
210 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
211 UsageError("");
212 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
213 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700214 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
215 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800216 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
218 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700219 UsageError(" --dump-timing: display a breakdown of where time was spent");
220 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700221 UsageError(" --include-patch-information: Include patching information so the generated code");
222 UsageError(" can have its base address moved without full recompilation.");
223 UsageError("");
224 UsageError(" --no-include-patch-information: Do not include patching information.");
225 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700226 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
227 UsageError("");
228 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
229 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
231 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
232 UsageError(" Use a separate --runtime-arg switch for each argument.");
233 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700234 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000235 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700237 UsageError(" --print-pass-names: print a list of pass names");
238 UsageError("");
239 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
240 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
241 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700242 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
243 "with the setting.");
244 UsageError(" Will print default if no overridden setting exists.");
245 UsageError("");
246 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
247 "Pass2Name:Pass2OptionName:Pass2Option#");
248 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
249 UsageError(" Separator used between options is a comma.");
250 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 std::cerr << "See log for usage error information\n";
252 exit(EXIT_FAILURE);
253}
254
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255// The primary goal of the watchdog is to prevent stuck build servers
256// during development when fatal aborts lead to a cascade of failures
257// that result in a deadlock.
258class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800259// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260#undef CHECK_PTHREAD_CALL
261#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
262 do { \
263 int rc = call args; \
264 if (rc != 0) { \
265 errno = rc; \
266 std::string message(# call); \
267 message += " failed for "; \
268 message += reason; \
269 Fatal(message); \
270 } \
271 } while (false)
272
273 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700274 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700275 is_watch_dog_enabled_ = is_watch_dog_enabled;
276 if (!is_watch_dog_enabled_) {
277 return;
278 }
279 shutting_down_ = false;
280 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700281 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
282 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700283 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
284 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
285 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
286 }
287 ~WatchDog() {
288 if (!is_watch_dog_enabled_) {
289 return;
290 }
291 const char* reason = "dex2oat watch dog thread shutdown";
292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
293 shutting_down_ = true;
294 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
295 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
296
Kenny Root51316382014-05-13 14:59:37 -0700297 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
301 }
302
303 private:
304 static void* CallBack(void* arg) {
305 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
306 ::art::SetThreadName("dex2oat watch dog");
307 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700308 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700309 }
310
311 static void Message(char severity, const std::string& message) {
312 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
313 // cases.
314 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
315 kIsDebugBuild ? "d" : "",
316 severity,
317 getpid(),
318 GetTid(),
319 message.c_str());
320 }
321
Ian Rogers7223d442014-10-10 20:05:39 -0700322 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700323 Message('F', message);
324 exit(1);
325 }
326
327 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
329 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800330 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 timespec timeout_ts;
332 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
333 const char* reason = "dex2oat watch dog thread waiting";
334 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
335 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800336 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800338 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 } else if (rc != 0) {
340 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
341 strerror(errno)));
342 Fatal(message.c_str());
343 }
344 }
345 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
346 }
347
348 // 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 -0700349 // Debug builds are slower so they have larger timeouts.
350 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800351
Elliott Hughes956af0f2014-12-11 14:34:28 -0800352 // 6 minutes scaled by kSlowdownFactor.
353 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700354
355 bool is_watch_dog_enabled_;
356 bool shutting_down_;
357 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
358 pthread_mutex_t mutex_;
359 pthread_cond_t cond_;
360 pthread_attr_t attr_;
361 pthread_t pthread_;
362};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800364static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100365 std::string::size_type colon = s.find(c);
366 if (colon == std::string::npos) {
367 Usage("Missing char %c in option %s\n", c, s.c_str());
368 }
369 // Add one to remove the char we were trimming until.
370 *parsed_value = s.substr(colon + 1);
371}
372
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800373static void ParseDouble(const std::string& option, char after_char, double min, double max,
374 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100375 std::string substring;
376 ParseStringAfterChar(option, after_char, &substring);
377 bool sane_val = true;
378 double value;
379 if (false) {
380 // TODO: this doesn't seem to work on the emulator. b/15114595
381 std::stringstream iss(substring);
382 iss >> value;
383 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
384 sane_val = iss.eof() && (value >= min) && (value <= max);
385 } else {
386 char* end = nullptr;
387 value = strtod(substring.c_str(), &end);
388 sane_val = *end == '\0' && value >= min && value <= max;
389 }
390 if (!sane_val) {
391 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
392 }
393 *parsed_value = value;
394}
395
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800396class Dex2Oat FINAL {
397 public:
398 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800399 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800400 instruction_set_(kRuntimeISA),
401 // Take the default set of instruction features from the build.
402 method_inliner_map_(),
403 runtime_(nullptr),
404 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
405 start_ns_(NanoTime()),
406 oat_fd_(-1),
407 zip_fd_(-1),
408 image_base_(0U),
409 image_classes_zip_filename_(nullptr),
410 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800411 compiled_classes_zip_filename_(nullptr),
412 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800413 image_(false),
414 is_host_(false),
415 dump_stats_(false),
416 dump_passes_(false),
417 dump_timing_(false),
418 dump_slow_timing_(kIsDebugBuild),
419 timings_(timings) {}
420
421 ~Dex2Oat() {
Mathieu Chartier49285c52014-12-02 15:43:48 -0800422 LogCompletionTime(); // Needs to be before since it accesses the runtime.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800423 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
424 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100425 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426 }
427
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800428 // Parse the arguments from the command line. In case of an unrecognized option or impossible
429 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
430 // returns, arguments have been successfully parsed.
431 void ParseArgs(int argc, char** argv) {
432 original_argc = argc;
433 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700434
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800435 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700436
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800437 // Skip over argv[0].
438 argv++;
439 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700440
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800441 if (argc == 0) {
442 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800444
445 std::string oat_symbols;
446 std::string boot_image_filename;
447 const char* compiler_filter_string = nullptr;
448 bool compile_pic = false;
449 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
450 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
451 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
452 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
453 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
454
455 // Profile file to use
456 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
457
458 bool print_pass_options = false;
459 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
460 bool include_debug_symbols = kIsDebugBuild;
461 bool watch_dog_enabled = true;
462 bool generate_gdb_information = kIsDebugBuild;
463
464 std::string error_msg;
465
466 for (int i = 0; i < argc; i++) {
467 const StringPiece option(argv[i]);
468 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 if (log_options) {
470 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
471 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472 if (option.starts_with("--dex-file=")) {
473 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
474 } else if (option.starts_with("--dex-location=")) {
475 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
476 } else if (option.starts_with("--zip-fd=")) {
477 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
478 if (!ParseInt(zip_fd_str, &zip_fd_)) {
479 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
480 }
481 if (zip_fd_ < 0) {
482 Usage("--zip-fd passed a negative value %d", zip_fd_);
483 }
484 } else if (option.starts_with("--zip-location=")) {
485 zip_location_ = option.substr(strlen("--zip-location=")).data();
486 } else if (option.starts_with("--oat-file=")) {
487 oat_filename_ = option.substr(strlen("--oat-file=")).data();
488 } else if (option.starts_with("--oat-symbols=")) {
489 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
490 } else if (option.starts_with("--oat-fd=")) {
491 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
492 if (!ParseInt(oat_fd_str, &oat_fd_)) {
493 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
494 }
495 if (oat_fd_ < 0) {
496 Usage("--oat-fd passed a negative value %d", oat_fd_);
497 }
498 } else if (option == "--watch-dog") {
499 watch_dog_enabled = true;
500 } else if (option == "--no-watch-dog") {
501 watch_dog_enabled = false;
502 } else if (option == "--gen-gdb-info") {
503 generate_gdb_information = true;
504 // Debug symbols are needed for gdb information.
505 include_debug_symbols = true;
506 } else if (option == "--no-gen-gdb-info") {
507 generate_gdb_information = false;
508 } else if (option.starts_with("-j")) {
509 const char* thread_count_str = option.substr(strlen("-j")).data();
510 if (!ParseUint(thread_count_str, &thread_count_)) {
511 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
512 }
513 } else if (option.starts_with("--oat-location=")) {
514 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800515 } else if (option.starts_with("--image=")) {
516 image_filename_ = option.substr(strlen("--image=")).data();
517 } else if (option.starts_with("--image-classes=")) {
518 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
519 } else if (option.starts_with("--image-classes-zip=")) {
520 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800521 } else if (option.starts_with("--compiled-classes=")) {
522 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
523 } else if (option.starts_with("--compiled-classes-zip=")) {
524 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800525 } else if (option.starts_with("--base=")) {
526 const char* image_base_str = option.substr(strlen("--base=")).data();
527 char* end;
528 image_base_ = strtoul(image_base_str, &end, 16);
529 if (end == image_base_str || *end != '\0') {
530 Usage("Failed to parse hexadecimal value for option %s", option.data());
531 }
532 } else if (option.starts_with("--boot-image=")) {
533 boot_image_filename = option.substr(strlen("--boot-image=")).data();
534 } else if (option.starts_with("--android-root=")) {
535 android_root_ = option.substr(strlen("--android-root=")).data();
536 } else if (option.starts_with("--instruction-set=")) {
537 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
538 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
539 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
540 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
541 buf.get()[instruction_set_str.length()] = 0;
542 instruction_set_ = GetInstructionSetFromString(buf.get());
543 // arm actually means thumb2.
544 if (instruction_set_ == InstructionSet::kArm) {
545 instruction_set_ = InstructionSet::kThumb2;
546 }
547 } else if (option.starts_with("--instruction-set-variant=")) {
548 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
549 instruction_set_features_.reset(
550 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
551 if (instruction_set_features_.get() == nullptr) {
552 Usage("%s", error_msg.c_str());
553 }
554 } else if (option.starts_with("--instruction-set-features=")) {
555 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800557 instruction_set_features_.reset(
558 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
559 if (instruction_set_features_.get() == nullptr) {
560 Usage("Problem initializing default instruction set features variant: %s",
561 error_msg.c_str());
562 }
563 }
564 instruction_set_features_.reset(
565 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
566 if (instruction_set_features_.get() == nullptr) {
567 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800568 }
569 } else if (option.starts_with("--compiler-backend=")) {
570 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
571 if (backend_str == "Quick") {
572 compiler_kind_ = Compiler::kQuick;
573 } else if (backend_str == "Optimizing") {
574 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800575 } else {
576 Usage("Unknown compiler backend: %s", backend_str.data());
577 }
578 } else if (option.starts_with("--compiler-filter=")) {
579 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
580 } else if (option == "--compile-pic") {
581 compile_pic = true;
582 } else if (option.starts_with("--huge-method-max=")) {
583 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
584 if (!ParseInt(threshold, &huge_method_threshold)) {
585 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
586 }
587 if (huge_method_threshold < 0) {
588 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
589 }
590 } else if (option.starts_with("--large-method-max=")) {
591 const char* threshold = option.substr(strlen("--large-method-max=")).data();
592 if (!ParseInt(threshold, &large_method_threshold)) {
593 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
594 }
595 if (large_method_threshold < 0) {
596 Usage("--large-method-max passed a negative value %s", large_method_threshold);
597 }
598 } else if (option.starts_with("--small-method-max=")) {
599 const char* threshold = option.substr(strlen("--small-method-max=")).data();
600 if (!ParseInt(threshold, &small_method_threshold)) {
601 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
602 }
603 if (small_method_threshold < 0) {
604 Usage("--small-method-max passed a negative value %s", small_method_threshold);
605 }
606 } else if (option.starts_with("--tiny-method-max=")) {
607 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
608 if (!ParseInt(threshold, &tiny_method_threshold)) {
609 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
610 }
611 if (tiny_method_threshold < 0) {
612 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
613 }
614 } else if (option.starts_with("--num-dex-methods=")) {
615 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
616 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
617 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
618 }
619 if (num_dex_methods_threshold < 0) {
620 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
621 }
622 } else if (option == "--host") {
623 is_host_ = true;
624 } else if (option == "--runtime-arg") {
625 if (++i >= argc) {
626 Usage("Missing required argument for --runtime-arg");
627 }
628 if (log_options) {
629 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
630 }
631 runtime_args_.push_back(argv[i]);
632 } else if (option == "--dump-timing") {
633 dump_timing_ = true;
634 } else if (option == "--dump-passes") {
635 dump_passes_ = true;
636 } else if (option == "--dump-stats") {
637 dump_stats_ = true;
638 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
639 include_debug_symbols = true;
640 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
641 include_debug_symbols = false;
642 generate_gdb_information = false; // Depends on debug symbols, see above.
643 } else if (option.starts_with("--profile-file=")) {
644 profile_file_ = option.substr(strlen("--profile-file=")).data();
645 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
646 } else if (option == "--no-profile-file") {
647 // No profile
648 } else if (option.starts_with("--top-k-profile-threshold=")) {
649 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
650 } else if (option == "--print-pass-names") {
651 PassDriverMEOpts::PrintPassNames();
652 } else if (option.starts_with("--disable-passes=")) {
653 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
654 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
655 } else if (option.starts_with("--print-passes=")) {
656 std::string print_passes = option.substr(strlen("--print-passes=")).data();
657 PassDriverMEOpts::SetPrintPassList(print_passes);
658 } else if (option == "--print-all-passes") {
659 PassDriverMEOpts::SetPrintAllPasses();
660 } else if (option.starts_with("--dump-cfg-passes=")) {
661 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
662 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
663 } else if (option == "--print-pass-options") {
664 print_pass_options = true;
665 } else if (option.starts_with("--pass-options=")) {
666 std::string options = option.substr(strlen("--pass-options=")).data();
667 PassDriverMEOpts::SetOverriddenPassOptions(options);
668 } else if (option == "--include-patch-information") {
669 include_patch_information = true;
670 } else if (option == "--no-include-patch-information") {
671 include_patch_information = false;
672 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800673 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
674 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800675 gLogVerbosity.compiler = false;
676 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800677 } else if (option.starts_with("--dump-init-failures=")) {
678 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
679 init_failure_output_.reset(new std::ofstream(file_name));
680 if (init_failure_output_.get() == nullptr) {
681 LOG(ERROR) << "Failed to allocate ofstream";
682 } else if (init_failure_output_->fail()) {
683 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
684 << "failures.";
685 init_failure_output_.reset();
686 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800687 } else {
688 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 }
691
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000692 if (compiler_kind_ == Compiler::kOptimizing) {
693 // Optimizing only supports PIC mode.
694 compile_pic = true;
695 }
696
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 if (oat_filename_.empty() && oat_fd_ == -1) {
698 Usage("Output must be supplied with either --oat-file or --oat-fd");
699 }
700
701 if (!oat_filename_.empty() && oat_fd_ != -1) {
702 Usage("--oat-file should not be used with --oat-fd");
703 }
704
705 if (!oat_symbols.empty() && oat_fd_ != -1) {
706 Usage("--oat-symbols should not be used with --oat-fd");
707 }
708
709 if (!oat_symbols.empty() && is_host_) {
710 Usage("--oat-symbols should not be used with --host");
711 }
712
713 if (oat_fd_ != -1 && !image_filename_.empty()) {
714 Usage("--oat-fd should not be used with --image");
715 }
716
717 if (android_root_.empty()) {
718 const char* android_root_env_var = getenv("ANDROID_ROOT");
719 if (android_root_env_var == nullptr) {
720 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700721 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 android_root_ += android_root_env_var;
723 }
724
725 image_ = (!image_filename_.empty());
726 if (!image_ && boot_image_filename.empty()) {
727 boot_image_filename += android_root_;
728 boot_image_filename += "/framework/boot.art";
729 }
730 if (!boot_image_filename.empty()) {
731 boot_image_option_ += "-Ximage:";
732 boot_image_option_ += boot_image_filename;
733 }
734
735 if (image_classes_filename_ != nullptr && !image_) {
736 Usage("--image-classes should only be used with --image");
737 }
738
739 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
740 Usage("--image-classes should not be used with --boot-image");
741 }
742
743 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
744 Usage("--image-classes-zip should be used with --image-classes");
745 }
746
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800747 if (compiled_classes_filename_ != nullptr && !image_) {
748 Usage("--compiled-classes should only be used with --image");
749 }
750
751 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
752 Usage("--compiled-classes should not be used with --boot-image");
753 }
754
755 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
756 Usage("--compiled-classes-zip should be used with --compiled-classes");
757 }
758
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800759 if (dex_filenames_.empty() && zip_fd_ == -1) {
760 Usage("Input must be supplied with either --dex-file or --zip-fd");
761 }
762
763 if (!dex_filenames_.empty() && zip_fd_ != -1) {
764 Usage("--dex-file should not be used with --zip-fd");
765 }
766
767 if (!dex_filenames_.empty() && !zip_location_.empty()) {
768 Usage("--dex-file should not be used with --zip-location");
769 }
770
771 if (dex_locations_.empty()) {
772 for (const char* dex_file_name : dex_filenames_) {
773 dex_locations_.push_back(dex_file_name);
774 }
775 } else if (dex_locations_.size() != dex_filenames_.size()) {
776 Usage("--dex-location arguments do not match --dex-file arguments");
777 }
778
779 if (zip_fd_ != -1 && zip_location_.empty()) {
780 Usage("--zip-location should be supplied with --zip-fd");
781 }
782
783 if (boot_image_option_.empty()) {
784 if (image_base_ == 0) {
785 Usage("Non-zero --base not specified");
786 }
787 }
788
789 oat_stripped_ = oat_filename_;
790 if (!oat_symbols.empty()) {
791 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800793 oat_unstripped_ = oat_filename_;
794 }
795
796 // If no instruction set feature was given, use the default one for the target
797 // instruction set.
798 if (instruction_set_features_.get() == nullptr) {
799 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800800 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
801 if (instruction_set_features_.get() == nullptr) {
802 Usage("Problem initializing default instruction set features variant: %s",
803 error_msg.c_str());
804 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800805 }
806
807 if (instruction_set_ == kRuntimeISA) {
808 std::unique_ptr<const InstructionSetFeatures> runtime_features(
809 InstructionSetFeatures::FromCppDefines());
810 if (!instruction_set_features_->Equals(runtime_features.get())) {
811 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
812 << *instruction_set_features_ << ") and those of dex2oat executable ("
813 << *runtime_features <<") for the command line:\n"
814 << CommandLine();
815 }
816 }
817
818 if (compiler_filter_string == nullptr) {
819 if (instruction_set_ == kMips64) {
820 // TODO: fix compiler for Mips64.
821 compiler_filter_string = "interpret-only";
822 } else if (image_) {
823 compiler_filter_string = "speed";
824 } else {
825 // TODO: Migrate SMALL mode to command line option.
826 #if ART_SMALL_MODE
827 compiler_filter_string = "interpret-only";
828 #else
829 compiler_filter_string = "speed";
830 #endif
831 }
832 }
833 CHECK(compiler_filter_string != nullptr);
834 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
835 if (strcmp(compiler_filter_string, "verify-none") == 0) {
836 compiler_filter = CompilerOptions::kVerifyNone;
837 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
838 compiler_filter = CompilerOptions::kInterpretOnly;
839 } else if (strcmp(compiler_filter_string, "space") == 0) {
840 compiler_filter = CompilerOptions::kSpace;
841 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
842 compiler_filter = CompilerOptions::kBalanced;
843 } else if (strcmp(compiler_filter_string, "speed") == 0) {
844 compiler_filter = CompilerOptions::kSpeed;
845 } else if (strcmp(compiler_filter_string, "everything") == 0) {
846 compiler_filter = CompilerOptions::kEverything;
847 } else if (strcmp(compiler_filter_string, "time") == 0) {
848 compiler_filter = CompilerOptions::kTime;
849 } else {
850 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
851 }
852
853 // Checks are all explicit until we know the architecture.
854 bool implicit_null_checks = false;
855 bool implicit_so_checks = false;
856 bool implicit_suspend_checks = false;
857 // Set the compilation target's implicit checks options.
858 switch (instruction_set_) {
859 case kArm:
860 case kThumb2:
861 case kArm64:
862 case kX86:
863 case kX86_64:
864 implicit_null_checks = true;
865 implicit_so_checks = true;
866 break;
867
868 default:
869 // Defaults are correct.
870 break;
871 }
872
873 if (print_pass_options) {
874 PassDriverMEOpts::PrintPassOptions();
875 }
876
877 compiler_options_.reset(new CompilerOptions(compiler_filter,
878 huge_method_threshold,
879 large_method_threshold,
880 small_method_threshold,
881 tiny_method_threshold,
882 num_dex_methods_threshold,
883 generate_gdb_information,
884 include_patch_information,
885 top_k_profile_threshold,
886 include_debug_symbols,
887 implicit_null_checks,
888 implicit_so_checks,
889 implicit_suspend_checks,
890 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800891 verbose_methods_.empty() ?
892 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800893 &verbose_methods_,
894 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800895
896 // Done with usage checks, enable watchdog if requested
897 if (watch_dog_enabled) {
898 watchdog_.reset(new WatchDog(true));
899 }
900
901 // Fill some values into the key-value store for the oat header.
902 key_value_store_.reset(new SafeMap<std::string, std::string>());
903
904 // Insert some compiler things.
905 {
906 std::ostringstream oss;
907 for (int i = 0; i < argc; ++i) {
908 if (i > 0) {
909 oss << ' ';
910 }
911 oss << argv[i];
912 }
913 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
914 oss.str(""); // Reset.
915 oss << kRuntimeISA;
916 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
917 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
918 }
919 }
920
921 // Check whether the oat output file is writable, and open it for later.
922 bool OpenFile() {
923 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
924 if (create_file) {
925 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
926 if (oat_location_.empty()) {
927 oat_location_ = oat_filename_;
928 }
929 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800930 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800931 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800932 if (oat_file_->SetLength(0) != 0) {
933 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
934 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800935 }
936 if (oat_file_.get() == nullptr) {
937 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
938 return false;
939 }
940 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
941 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800942 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800943 return false;
944 }
945 return true;
946 }
947
Andreas Gampea650e702014-12-03 14:28:02 -0800948 void EraseOatFile() {
949 DCHECK(oat_file_.get() != nullptr);
950 oat_file_->Erase();
951 oat_file_.reset();
952 }
953
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800954 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
955 // boot class path.
956 bool Setup() {
957 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
958 RuntimeOptions runtime_options;
959 std::vector<const DexFile*> boot_class_path;
960 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
961 if (boot_image_option_.empty()) {
962 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800963 if (failure_count > 0) {
964 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800965 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800966 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800967 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
968 } else {
969 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
970 }
971 for (size_t i = 0; i < runtime_args_.size(); i++) {
972 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700974
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800975 verification_results_.reset(new VerificationResults(compiler_options_.get()));
976 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
977 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
978 runtime_options.push_back(
979 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
980
981 if (!CreateRuntime(runtime_options)) {
982 return false;
983 }
984
985 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
986 // Runtime::Start, give it away now so that we don't starve GC.
987 Thread* self = Thread::Current();
988 self->TransitionFromRunnableToSuspended(kNative);
989 // If we're doing the image, override the compiler filter to force full compilation. Must be
990 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
991 // compilation of class initializers.
992 // Whilst we're in native take the opportunity to initialize well known classes.
993 WellKnownClasses::Init(self->GetJniEnv());
994
995 // If --image-classes was specified, calculate the full list of classes to include in the image
996 if (image_classes_filename_ != nullptr) {
997 std::string error_msg;
998 if (image_classes_zip_filename_ != nullptr) {
999 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1000 image_classes_filename_,
1001 &error_msg));
1002 } else {
1003 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1004 }
1005 if (image_classes_.get() == nullptr) {
1006 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1007 "': " << error_msg;
1008 return false;
1009 }
1010 } else if (image_) {
1011 image_classes_.reset(new std::set<std::string>);
1012 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001013 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1014 // image.
1015 if (compiled_classes_filename_ != nullptr) {
1016 std::string error_msg;
1017 if (compiled_classes_zip_filename_ != nullptr) {
1018 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1019 compiled_classes_filename_,
1020 &error_msg));
1021 } else {
1022 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1023 }
1024 if (compiled_classes_.get() == nullptr) {
1025 LOG(ERROR) << "Failed to create list of compiled classes from '"
1026 << compiled_classes_filename_ << "': " << error_msg;
1027 return false;
1028 }
1029 } else if (image_) {
1030 compiled_classes_.reset(nullptr); // By default compile everything.
1031 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001032
1033 if (boot_image_option_.empty()) {
1034 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1035 } else {
1036 if (dex_filenames_.empty()) {
1037 ATRACE_BEGIN("Opening zip archive from file descriptor");
1038 std::string error_msg;
1039 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1040 zip_location_.c_str(),
1041 &error_msg));
1042 if (zip_archive.get() == nullptr) {
1043 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1044 << error_msg;
1045 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001046 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001047 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1048 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1049 << "': " << error_msg;
1050 return false;
1051 }
1052 ATRACE_END();
1053 } else {
1054 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1055 if (failure_count > 0) {
1056 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1057 return false;
1058 }
1059 }
1060
1061 constexpr bool kSaveDexInput = false;
1062 if (kSaveDexInput) {
1063 for (size_t i = 0; i < dex_files_.size(); ++i) {
1064 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001065 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1066 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001067 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1068 if (tmp_file.get() == nullptr) {
1069 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1070 << ". Try: adb shell chmod 777 /data/local/tmp";
1071 continue;
1072 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001073 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1074 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1075 UNUSED(tmp_file->Flush());
1076 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001077 LOG(INFO) << "Wrote input to " << tmp_file_name;
1078 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001079 }
1080 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001081 // Ensure opened dex files are writable for dex-to-dex transformations.
1082 for (const auto& dex_file : dex_files_) {
1083 if (!dex_file->EnableWrite()) {
1084 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001085 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001086 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001087
1088 /*
1089 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1090 * Don't bother to check if we're doing the image.
1091 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001092 if (!image_ &&
1093 compiler_options_->IsCompilationEnabled() &&
1094 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001095 size_t num_methods = 0;
1096 for (size_t i = 0; i != dex_files_.size(); ++i) {
1097 const DexFile* dex_file = dex_files_[i];
1098 CHECK(dex_file != nullptr);
1099 num_methods += dex_file->NumMethodIds();
1100 }
1101 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1102 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1103 VLOG(compiler) << "Below method threshold, compiling anyways";
1104 }
1105 }
1106
1107 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001108 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001109
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001110 // Create and invoke the compiler driver. This will compile all the dex files.
1111 void Compile() {
1112 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1113 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001114
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001115 // Handle and ClassLoader creation needs to come after Runtime::Create
1116 jobject class_loader = nullptr;
1117 Thread* self = Thread::Current();
1118 if (!boot_image_option_.empty()) {
1119 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1120 std::vector<const DexFile*> class_path_files(dex_files_);
1121 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1122 ScopedObjectAccess soa(self);
1123 for (size_t i = 0; i < class_path_files.size(); i++) {
1124 class_linker->RegisterDexFile(*class_path_files[i]);
1125 }
1126 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1127 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1128 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1129 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1130 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1131 }
1132
1133 driver_.reset(new CompilerDriver(compiler_options_.get(),
1134 verification_results_.get(),
1135 &method_inliner_map_,
1136 compiler_kind_,
1137 instruction_set_,
1138 instruction_set_features_.get(),
1139 image_,
1140 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001141 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001142 thread_count_,
1143 dump_stats_,
1144 dump_passes_,
1145 compiler_phases_timings_.get(),
1146 profile_file_));
1147
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001148 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001149 }
1150
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151 // Notes on the interleaving of creating the image and oat file to
1152 // ensure the references between the two are correct.
1153 //
1154 // Currently we have a memory layout that looks something like this:
1155 //
1156 // +--------------+
1157 // | image |
1158 // +--------------+
1159 // | boot oat |
1160 // +--------------+
1161 // | alloc spaces |
1162 // +--------------+
1163 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001164 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001165 //
1166 // 1. The image is expected to be loaded at an absolute address and
1167 // contains Objects with absolute pointers within the image.
1168 //
1169 // 2. There are absolute pointers from Methods in the image to their
1170 // code in the oat.
1171 //
1172 // 3. There are absolute pointers from the code in the oat to Methods
1173 // in the image.
1174 //
1175 // 4. There are absolute pointers from code in the oat to other code
1176 // in the oat.
1177 //
1178 // To get this all correct, we go through several steps.
1179 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001180 // 1. We prepare offsets for all data in the oat file and calculate
1181 // the oat data size and code size. During this stage, we also set
1182 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001183 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 // 2. We prepare offsets for the objects in the image and calculate
1185 // the image size.
1186 //
1187 // 3. We create the oat file. Originally this was just our own proprietary
1188 // file but now it is contained within an ELF dynamic object (aka an .so
1189 // file). Since we know the image size and oat data size and code size we
1190 // can prepare the ELF headers and we then know the ELF memory segment
1191 // layout and we can now resolve all references. The compiler provides
1192 // LinkerPatch information in each CompiledMethod and we resolve these,
1193 // using the layout information and image object locations provided by
1194 // image writer, as we're writing the method code.
1195 //
1196 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 // will be loaded after itself. Originally when oat file was simply
1198 // memory mapped so we could predict where its contents were based
1199 // on the file size. Now that it is an ELF file, we need to inspect
1200 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001201 // where the oat header is located within.
1202 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001203 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001204 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001205 // load the .so at the desired location at runtime by offsetting the
1206 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001207 // TODO: Do this in step 3. We already know the layout there.
1208 //
1209 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1210 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211
1212
1213 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1214 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001215 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1216 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001217 bool CreateOatFile() {
1218 CHECK(key_value_store_.get() != nullptr);
1219
1220 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1221
1222 std::unique_ptr<OatWriter> oat_writer;
1223 {
1224 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1225 std::string image_file_location;
1226 uint32_t image_file_location_oat_checksum = 0;
1227 uintptr_t image_file_location_oat_data_begin = 0;
1228 int32_t image_patch_delta = 0;
1229 if (image_) {
1230 PrepareImageWriter(image_base_);
1231 } else {
1232 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1233 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1234 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1235 image_file_location_oat_data_begin =
1236 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1237 image_file_location = image_space->GetImageFilename();
1238 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1239 }
1240
1241 if (!image_file_location.empty()) {
1242 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1243 }
1244
1245 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1246 image_file_location_oat_data_begin,
1247 image_patch_delta,
1248 driver_.get(),
1249 image_writer_.get(),
1250 timings_,
1251 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001252 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253
1254 if (image_) {
1255 // The OatWriter constructor has already updated offsets in methods and we need to
1256 // prepare method offsets in the image address space for direct method patching.
1257 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1258 if (!image_writer_->PrepareImageAddressSpace()) {
1259 LOG(ERROR) << "Failed to prepare image address space.";
1260 return false;
1261 }
1262 }
1263
1264 {
1265 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1266 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1267 oat_file_.get())) {
1268 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1269 return false;
1270 }
1271 }
1272
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001273 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1274 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001275 }
1276
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001277 // If we are compiling an image, invoke the image creation routine. Else just skip.
1278 bool HandleImage() {
1279 if (image_) {
1280 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1281 if (!CreateImageFile()) {
1282 return false;
1283 }
1284 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001285 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001286 return true;
1287 }
1288
Andreas Gampe10e477d2014-11-19 12:57:42 -08001289 // Create a copy from unstripped to stripped.
1290 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001291 // If we don't want to strip in place, copy from unstripped location to stripped location.
1292 // We need to strip after image creation because FixupElf needs to use .strtab.
1293 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001294 // If the oat file is still open, flush it.
1295 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1296 if (!FlushCloseOatFile()) {
1297 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001298 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001299 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001300
1301 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001302 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1303 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1304 size_t buffer_size = 8192;
1305 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1306 while (true) {
1307 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1308 if (bytes_read <= 0) {
1309 break;
1310 }
1311 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1312 CHECK(write_ok);
1313 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001314 if (out->FlushCloseOrErase() != 0) {
1315 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1316 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001317 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001318 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001319 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001320 return true;
1321 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001322
Andreas Gampe10e477d2014-11-19 12:57:42 -08001323 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001324 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001325 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1326 if (oat_file_->Flush() != 0) {
1327 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1328 << oat_filename_;
1329 oat_file_->Erase();
1330 return false;
1331 }
1332 }
1333 return true;
1334 }
1335
1336 bool FlushCloseOatFile() {
1337 if (oat_file_.get() != nullptr) {
1338 std::unique_ptr<File> tmp(oat_file_.release());
1339 if (tmp->FlushCloseOrErase() != 0) {
1340 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1341 << oat_filename_;
1342 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001343 }
1344 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001345 return true;
1346 }
1347
1348 void DumpTiming() {
1349 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1350 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1351 }
1352 if (dump_passes_) {
1353 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1354 }
1355 }
1356
1357 CompilerOptions* GetCompilerOptions() const {
1358 return compiler_options_.get();
1359 }
1360
Andreas Gampe10e477d2014-11-19 12:57:42 -08001361 bool IsImage() const {
1362 return image_;
1363 }
1364
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 bool IsHost() const {
1366 return is_host_;
1367 }
1368
1369 private:
1370 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1371 const std::vector<const char*>& dex_locations,
1372 std::vector<const DexFile*>& dex_files) {
1373 size_t failure_count = 0;
1374 for (size_t i = 0; i < dex_filenames.size(); i++) {
1375 const char* dex_filename = dex_filenames[i];
1376 const char* dex_location = dex_locations[i];
1377 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1378 std::string error_msg;
1379 if (!OS::FileExists(dex_filename)) {
1380 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1381 continue;
1382 }
1383 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1384 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1385 ++failure_count;
1386 }
1387 ATRACE_END();
1388 }
1389 return failure_count;
1390 }
1391
1392 // Returns true if dex_files has a dex with the named location.
1393 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1394 const std::string& location) {
1395 for (size_t i = 0; i < dex_files.size(); ++i) {
1396 if (dex_files[i]->GetLocation() == location) {
1397 return true;
1398 }
1399 }
1400 return false;
1401 }
1402
1403 // Appends to dex_files any elements of class_path that it doesn't already
1404 // contain. This will open those dex files as necessary.
1405 static void OpenClassPathFiles(const std::string& class_path,
1406 std::vector<const DexFile*>& dex_files) {
1407 std::vector<std::string> parsed;
1408 Split(class_path, ':', &parsed);
1409 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1410 ScopedObjectAccess soa(Thread::Current());
1411 for (size_t i = 0; i < parsed.size(); ++i) {
1412 if (DexFilesContains(dex_files, parsed[i])) {
1413 continue;
1414 }
1415 std::string error_msg;
1416 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1417 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1418 }
1419 }
1420 }
1421
1422 // Create a runtime necessary for compilation.
1423 bool CreateRuntime(const RuntimeOptions& runtime_options)
1424 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1425 if (!Runtime::Create(runtime_options, false)) {
1426 LOG(ERROR) << "Failed to create runtime";
1427 return false;
1428 }
1429 Runtime* runtime = Runtime::Current();
1430 runtime->SetInstructionSet(instruction_set_);
1431 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1432 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1433 if (!runtime->HasCalleeSaveMethod(type)) {
1434 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1435 }
1436 }
1437 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1438 runtime->GetClassLinker()->RunRootClinits();
1439 runtime_ = runtime;
1440 return true;
1441 }
1442
1443 void PrepareImageWriter(uintptr_t image_base) {
1444 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1445 }
1446
1447 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1448 bool CreateImageFile()
1449 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1450 CHECK(image_writer_ != nullptr);
1451 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1452 LOG(ERROR) << "Failed to create image file " << image_filename_;
1453 return false;
1454 }
1455 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1456
1457 // Destroy ImageWriter before doing FixupElf.
1458 image_writer_.reset();
1459
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001460 // Do not fix up the ELF file if we are --compile-pic
1461 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001462 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1463 if (oat_file.get() == nullptr) {
1464 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1465 return false;
1466 }
1467
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001468 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001469 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001470 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1471 return false;
1472 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001473
1474 if (oat_file->FlushCloseOrErase()) {
1475 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1476 return false;
1477 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001478 }
1479
1480 return true;
1481 }
1482
1483 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1484 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1485 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1486 std::ifstream::in));
1487 if (image_classes_file.get() == nullptr) {
1488 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1489 return nullptr;
1490 }
1491 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1492 image_classes_file->close();
1493 return result.release();
1494 }
1495
1496 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1497 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1498 while (image_classes_stream.good()) {
1499 std::string dot;
1500 std::getline(image_classes_stream, dot);
1501 if (StartsWith(dot, "#") || dot.empty()) {
1502 continue;
1503 }
1504 std::string descriptor(DotToDescriptor(dot.c_str()));
1505 image_classes->insert(descriptor);
1506 }
1507 return image_classes.release();
1508 }
1509
1510 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1511 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1512 const char* image_classes_filename,
1513 std::string* error_msg) {
1514 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1515 if (zip_archive.get() == nullptr) {
1516 return nullptr;
1517 }
1518 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1519 if (zip_entry.get() == nullptr) {
1520 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1521 zip_filename, error_msg->c_str());
1522 return nullptr;
1523 }
1524 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1525 image_classes_filename,
1526 error_msg));
1527 if (image_classes_file.get() == nullptr) {
1528 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1529 zip_filename, error_msg->c_str());
1530 return nullptr;
1531 }
1532 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1533 image_classes_file->Size());
1534 std::istringstream image_classes_stream(image_classes_string);
1535 return ReadImageClasses(image_classes_stream);
1536 }
1537
Mathieu Chartier49285c52014-12-02 15:43:48 -08001538 void LogCompletionTime() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001539 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001540 << " (threads: " << thread_count_ << ") "
1541 << driver_->GetMemoryUsageString();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001542 }
1543
1544 std::unique_ptr<CompilerOptions> compiler_options_;
1545 Compiler::Kind compiler_kind_;
1546
1547 InstructionSet instruction_set_;
1548 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1549
1550 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1551
1552 std::unique_ptr<VerificationResults> verification_results_;
1553 DexFileToMethodInlinerMap method_inliner_map_;
1554 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1555
1556 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1557 // in an orderly fashion. The destructor takes care of deleting this.
1558 Runtime* runtime_;
1559
1560 size_t thread_count_;
1561 uint64_t start_ns_;
1562 std::unique_ptr<WatchDog> watchdog_;
1563 std::unique_ptr<File> oat_file_;
1564 std::string oat_stripped_;
1565 std::string oat_unstripped_;
1566 std::string oat_location_;
1567 std::string oat_filename_;
1568 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001569 std::vector<const char*> dex_filenames_;
1570 std::vector<const char*> dex_locations_;
1571 int zip_fd_;
1572 std::string zip_location_;
1573 std::string boot_image_option_;
1574 std::vector<const char*> runtime_args_;
1575 std::string image_filename_;
1576 uintptr_t image_base_;
1577 const char* image_classes_zip_filename_;
1578 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001579 const char* compiled_classes_zip_filename_;
1580 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001581 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001582 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001583 bool image_;
1584 std::unique_ptr<ImageWriter> image_writer_;
1585 bool is_host_;
1586 std::string android_root_;
1587 std::vector<const DexFile*> dex_files_;
1588 std::unique_ptr<CompilerDriver> driver_;
1589 std::vector<std::string> verbose_methods_;
1590 bool dump_stats_;
1591 bool dump_passes_;
1592 bool dump_timing_;
1593 bool dump_slow_timing_;
1594 std::string profile_file_; // Profile file to use
1595 TimingLogger* timings_;
1596 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001597 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001598
1599 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1600};
1601
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001602const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1603
1604static void b13564922() {
1605#if defined(__linux__) && defined(__arm__)
1606 int major, minor;
1607 struct utsname uts;
1608 if (uname(&uts) != -1 &&
1609 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1610 ((major < 3) || ((major == 3) && (minor < 4)))) {
1611 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1612 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1613 int old_personality = personality(0xffffffff);
1614 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1615 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1616 if (new_personality == -1) {
1617 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1618 }
1619 }
1620 }
1621#endif
1622}
1623
Andreas Gampe10e477d2014-11-19 12:57:42 -08001624static int CompileImage(Dex2Oat& dex2oat) {
1625 dex2oat.Compile();
1626
1627 // Create the boot.oat.
1628 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001629 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001630 return EXIT_FAILURE;
1631 }
1632
1633 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1634 // re-opened from the unstripped name.
1635 if (!dex2oat.FlushCloseOatFile()) {
1636 return EXIT_FAILURE;
1637 }
1638
1639 // Creates the boot.art and patches the boot.oat.
1640 if (!dex2oat.HandleImage()) {
1641 return EXIT_FAILURE;
1642 }
1643
1644 // When given --host, finish early without stripping.
1645 if (dex2oat.IsHost()) {
1646 dex2oat.DumpTiming();
1647 return EXIT_SUCCESS;
1648 }
1649
1650 // Copy unstripped to stripped location, if necessary.
1651 if (!dex2oat.CopyUnstrippedToStripped()) {
1652 return EXIT_FAILURE;
1653 }
1654
Andreas Gampe10e477d2014-11-19 12:57:42 -08001655 // FlushClose again, as stripping might have re-opened the oat file.
1656 if (!dex2oat.FlushCloseOatFile()) {
1657 return EXIT_FAILURE;
1658 }
1659
1660 dex2oat.DumpTiming();
1661 return EXIT_SUCCESS;
1662}
1663
1664static int CompileApp(Dex2Oat& dex2oat) {
1665 dex2oat.Compile();
1666
1667 // Create the app oat.
1668 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001669 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001670 return EXIT_FAILURE;
1671 }
1672
1673 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1674 // which we would lose.
1675 if (!dex2oat.FlushOatFile()) {
1676 return EXIT_FAILURE;
1677 }
1678
1679 // When given --host, finish early without stripping.
1680 if (dex2oat.IsHost()) {
1681 if (!dex2oat.FlushCloseOatFile()) {
1682 return EXIT_FAILURE;
1683 }
1684
1685 dex2oat.DumpTiming();
1686 return EXIT_SUCCESS;
1687 }
1688
1689 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1690 // unstripped version. If this is given, we expect to be able to open writable files by name.
1691 if (!dex2oat.CopyUnstrippedToStripped()) {
1692 return EXIT_FAILURE;
1693 }
1694
Andreas Gampe10e477d2014-11-19 12:57:42 -08001695 // Flush and close the file.
1696 if (!dex2oat.FlushCloseOatFile()) {
1697 return EXIT_FAILURE;
1698 }
1699
1700 dex2oat.DumpTiming();
1701 return EXIT_SUCCESS;
1702}
1703
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001704static int dex2oat(int argc, char** argv) {
1705 b13564922();
1706
1707 TimingLogger timings("compiler", false, false);
1708
1709 Dex2Oat dex2oat(&timings);
1710
1711 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1712 dex2oat.ParseArgs(argc, argv);
1713
1714 // Check early that the result of compilation can be written
1715 if (!dex2oat.OpenFile()) {
1716 return EXIT_FAILURE;
1717 }
1718
1719 LOG(INFO) << CommandLine();
1720
1721 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001722 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001723 return EXIT_FAILURE;
1724 }
1725
Andreas Gampe10e477d2014-11-19 12:57:42 -08001726 if (dex2oat.IsImage()) {
1727 return CompileImage(dex2oat);
1728 } else {
1729 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001730 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001731}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001732} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001733
1734int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001735 int result = art::dex2oat(argc, argv);
1736 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1737 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1738 // should not destruct the runtime in this case.
1739 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1740 exit(result);
1741 }
1742 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001743}