blob: 47b492ae7c446117ce7403a59ec064dfccefeccd [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
34#include "cutils/trace.h"
35
Ian Rogersc7dd2952014-10-21 23:31:19 -070036#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "base/stl_util.h"
38#include "base/stringpiece.h"
39#include "base/timing_logger.h"
40#include "base/unix_file/fd_file.h"
41#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000042#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000043#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070045#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000046#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070047#include "dex/quick_compiler_callbacks.h"
48#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080050#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080051#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070052#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "gc/space/image_space.h"
54#include "gc/space/space-inl.h"
55#include "image_writer.h"
56#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070057#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/class-inl.h"
59#include "mirror/class_loader.h"
60#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
62#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "os.h"
64#include "runtime.h"
65#include "ScopedLocalRef.h"
66#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070067#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "vector_output_stream.h"
69#include "well_known_classes.h"
70#include "zip_archive.h"
71
72namespace art {
73
Brian Carlstrom6449c622014-02-10 23:48:36 -080074static int original_argc;
75static char** original_argv;
76
77static std::string CommandLine() {
78 std::vector<std::string> command;
79 for (int i = 0; i < original_argc; ++i) {
80 command.push_back(original_argv[i]);
81 }
82 return Join(command, ' ');
83}
84
Brian Carlstrom7940e442013-07-12 13:46:57 -070085static void UsageErrorV(const char* fmt, va_list ap) {
86 std::string error;
87 StringAppendV(&error, fmt, ap);
88 LOG(ERROR) << error;
89}
90
91static void UsageError(const char* fmt, ...) {
92 va_list ap;
93 va_start(ap, fmt);
94 UsageErrorV(fmt, ap);
95 va_end(ap);
96}
97
Ian Rogers7223d442014-10-10 20:05:39 -070098[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070099 va_list ap;
100 va_start(ap, fmt);
101 UsageErrorV(fmt, ap);
102 va_end(ap);
103
Brian Carlstrom6449c622014-02-10 23:48:36 -0800104 UsageError("Command: %s", CommandLine().c_str());
105
Brian Carlstrom7940e442013-07-12 13:46:57 -0700106 UsageError("Usage: dex2oat [options]...");
107 UsageError("");
108 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
109 UsageError(" Example: --dex-file=/system/framework/core.jar");
110 UsageError("");
111 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
112 UsageError(" containing a classes.dex file to compile.");
113 UsageError(" Example: --zip-fd=5");
114 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700115 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
116 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700117 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
118 UsageError("");
119 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
120 UsageError(" Example: --oat-file=/system/framework/boot.oat");
121 UsageError("");
122 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900123 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700124 UsageError("");
125 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
126 UsageError(" to the file descriptor specified by --oat-fd.");
127 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
128 UsageError("");
129 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
130 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
131 UsageError("");
132 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
133 UsageError(" Example: --bitcode=/system/framework/boot.bc");
134 UsageError("");
135 UsageError(" --image=<file.art>: specifies the output image filename.");
136 UsageError(" Example: --image=/system/framework/boot.art");
137 UsageError("");
138 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
139 UsageError(" Example: --image=frameworks/base/preloaded-classes");
140 UsageError("");
141 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
142 UsageError(" Example: --base=0x50000000");
143 UsageError("");
144 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
145 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000146 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError("");
148 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
149 UsageError(" Example: --android-root=out/host/linux-x86");
150 UsageError(" Default: $ANDROID_ROOT");
151 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700152 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
153 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 UsageError(" Example: --instruction-set=x86");
155 UsageError(" Default: arm");
156 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700157 UsageError(" --instruction-set-features=...,: Specify instruction set features");
158 UsageError(" Example: --instruction-set-features=div");
159 UsageError(" Default: default");
160 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700161 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
162 UsageError(" Default: disabled");
163 UsageError("");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000164 UsageError(" --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700166 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700167 UsageError(" Default: Quick");
168 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100169 UsageError(" --compiler-filter="
170 "(verify-none"
171 "|interpret-only"
172 "|space"
173 "|balanced"
174 "|speed"
175 "|everything"
176 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700177 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800178 UsageError(" Example: --compiler-filter=everything");
179#if ART_SMALL_MODE
180 UsageError(" Default: interpret-only");
181#else
182 UsageError(" Default: speed");
183#endif
184 UsageError("");
185 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
186 UsageError(" method for compiler filter tuning.");
187 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
188 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
189 UsageError("");
190 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
191 UsageError(" method for compiler filter tuning.");
192 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
193 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError("");
195 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
196 UsageError(" method for compiler filter tuning.");
197 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
198 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
199 UsageError("");
200 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
201 UsageError(" method for compiler filter tuning.");
202 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
203 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
204 UsageError("");
205 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
206 UsageError(" method for compiler filter tuning.");
207 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
208 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
209 UsageError("");
210 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
211 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700212 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
213 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800214 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
215 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError(" --host: used with Portable backend to link against host runtime libraries");
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 Carlstrom7940e442013-07-12 13:46:57 -0700259// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
260#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
322 static void Warn(const std::string& message) {
323 Message('W', message);
324 }
325
Ian Rogers7223d442014-10-10 20:05:39 -0700326 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 Message('F', message);
328 exit(1);
329 }
330
331 void Wait() {
332 bool warning = true;
333 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
334 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
335 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800336 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 timespec warning_ts;
338 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
339 timespec timeout_ts;
340 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
341 const char* reason = "dex2oat watch dog thread waiting";
342 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
343 while (!shutting_down_) {
344 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
345 warning ? &warning_ts
346 : &timeout_ts));
347 if (rc == ETIMEDOUT) {
348 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
349 warning ? kWatchDogWarningSeconds
350 : kWatchDogTimeoutSeconds));
351 if (warning) {
352 Warn(message.c_str());
353 warning = false;
354 } else {
355 Fatal(message.c_str());
356 }
357 } else if (rc != 0) {
358 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
359 strerror(errno)));
360 Fatal(message.c_str());
361 }
362 }
363 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
364 }
365
366 // 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 -0700367 // Debug builds are slower so they have larger timeouts.
368 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800369
370 static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
371 kSlowdownFactor * 2 * 60 : // 2 minutes scaled by kSlowdownFactor (portable).
372 kSlowdownFactor * 1 * 60; // 1 minute scaled by kSlowdownFactor (not-portable).
373 static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
374 kSlowdownFactor * 30 * 60 : // 30 minutes scaled by kSlowdownFactor (portable).
375 kSlowdownFactor * 6 * 60; // 6 minutes scaled by kSlowdownFactor (not-portable).
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376
377 bool is_watch_dog_enabled_;
378 bool shutting_down_;
379 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
380 pthread_mutex_t mutex_;
381 pthread_cond_t cond_;
382 pthread_attr_t attr_;
383 pthread_t pthread_;
384};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800386static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100387 std::string::size_type colon = s.find(c);
388 if (colon == std::string::npos) {
389 Usage("Missing char %c in option %s\n", c, s.c_str());
390 }
391 // Add one to remove the char we were trimming until.
392 *parsed_value = s.substr(colon + 1);
393}
394
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800395static void ParseDouble(const std::string& option, char after_char, double min, double max,
396 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100397 std::string substring;
398 ParseStringAfterChar(option, after_char, &substring);
399 bool sane_val = true;
400 double value;
401 if (false) {
402 // TODO: this doesn't seem to work on the emulator. b/15114595
403 std::stringstream iss(substring);
404 iss >> value;
405 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
406 sane_val = iss.eof() && (value >= min) && (value <= max);
407 } else {
408 char* end = nullptr;
409 value = strtod(substring.c_str(), &end);
410 sane_val = *end == '\0' && value >= min && value <= max;
411 }
412 if (!sane_val) {
413 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
414 }
415 *parsed_value = value;
416}
417
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800418class Dex2Oat FINAL {
419 public:
420 explicit Dex2Oat(TimingLogger* timings) :
421 compiler_kind_(kUsePortableCompiler ? Compiler::kPortable : Compiler::kQuick),
422 instruction_set_(kRuntimeISA),
423 // Take the default set of instruction features from the build.
424 method_inliner_map_(),
425 runtime_(nullptr),
426 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
427 start_ns_(NanoTime()),
428 oat_fd_(-1),
429 zip_fd_(-1),
430 image_base_(0U),
431 image_classes_zip_filename_(nullptr),
432 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800433 compiled_classes_zip_filename_(nullptr),
434 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800435 image_(false),
436 is_host_(false),
437 dump_stats_(false),
438 dump_passes_(false),
439 dump_timing_(false),
440 dump_slow_timing_(kIsDebugBuild),
441 timings_(timings) {}
442
443 ~Dex2Oat() {
444 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
445 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100446 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800447 LogCompletionTime();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 }
449
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800450 // Parse the arguments from the command line. In case of an unrecognized option or impossible
451 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
452 // returns, arguments have been successfully parsed.
453 void ParseArgs(int argc, char** argv) {
454 original_argc = argc;
455 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700456
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800457 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700458
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800459 // Skip over argv[0].
460 argv++;
461 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700462
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800463 if (argc == 0) {
464 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800466
467 std::string oat_symbols;
468 std::string boot_image_filename;
469 const char* compiler_filter_string = nullptr;
470 bool compile_pic = false;
471 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
472 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
473 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
474 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
475 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
476
477 // Profile file to use
478 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
479
480 bool print_pass_options = false;
481 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
482 bool include_debug_symbols = kIsDebugBuild;
483 bool watch_dog_enabled = true;
484 bool generate_gdb_information = kIsDebugBuild;
485
486 std::string error_msg;
487
488 for (int i = 0; i < argc; i++) {
489 const StringPiece option(argv[i]);
490 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491 if (log_options) {
492 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
493 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800494 if (option.starts_with("--dex-file=")) {
495 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
496 } else if (option.starts_with("--dex-location=")) {
497 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
498 } else if (option.starts_with("--zip-fd=")) {
499 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
500 if (!ParseInt(zip_fd_str, &zip_fd_)) {
501 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
502 }
503 if (zip_fd_ < 0) {
504 Usage("--zip-fd passed a negative value %d", zip_fd_);
505 }
506 } else if (option.starts_with("--zip-location=")) {
507 zip_location_ = option.substr(strlen("--zip-location=")).data();
508 } else if (option.starts_with("--oat-file=")) {
509 oat_filename_ = option.substr(strlen("--oat-file=")).data();
510 } else if (option.starts_with("--oat-symbols=")) {
511 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
512 } else if (option.starts_with("--oat-fd=")) {
513 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
514 if (!ParseInt(oat_fd_str, &oat_fd_)) {
515 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
516 }
517 if (oat_fd_ < 0) {
518 Usage("--oat-fd passed a negative value %d", oat_fd_);
519 }
520 } else if (option == "--watch-dog") {
521 watch_dog_enabled = true;
522 } else if (option == "--no-watch-dog") {
523 watch_dog_enabled = false;
524 } else if (option == "--gen-gdb-info") {
525 generate_gdb_information = true;
526 // Debug symbols are needed for gdb information.
527 include_debug_symbols = true;
528 } else if (option == "--no-gen-gdb-info") {
529 generate_gdb_information = false;
530 } else if (option.starts_with("-j")) {
531 const char* thread_count_str = option.substr(strlen("-j")).data();
532 if (!ParseUint(thread_count_str, &thread_count_)) {
533 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
534 }
535 } else if (option.starts_with("--oat-location=")) {
536 oat_location_ = option.substr(strlen("--oat-location=")).data();
537 } else if (option.starts_with("--bitcode=")) {
538 bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
539 } else if (option.starts_with("--image=")) {
540 image_filename_ = option.substr(strlen("--image=")).data();
541 } else if (option.starts_with("--image-classes=")) {
542 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
543 } else if (option.starts_with("--image-classes-zip=")) {
544 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800545 } else if (option.starts_with("--compiled-classes=")) {
546 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
547 } else if (option.starts_with("--compiled-classes-zip=")) {
548 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800549 } else if (option.starts_with("--base=")) {
550 const char* image_base_str = option.substr(strlen("--base=")).data();
551 char* end;
552 image_base_ = strtoul(image_base_str, &end, 16);
553 if (end == image_base_str || *end != '\0') {
554 Usage("Failed to parse hexadecimal value for option %s", option.data());
555 }
556 } else if (option.starts_with("--boot-image=")) {
557 boot_image_filename = option.substr(strlen("--boot-image=")).data();
558 } else if (option.starts_with("--android-root=")) {
559 android_root_ = option.substr(strlen("--android-root=")).data();
560 } else if (option.starts_with("--instruction-set=")) {
561 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
562 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
563 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
564 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
565 buf.get()[instruction_set_str.length()] = 0;
566 instruction_set_ = GetInstructionSetFromString(buf.get());
567 // arm actually means thumb2.
568 if (instruction_set_ == InstructionSet::kArm) {
569 instruction_set_ = InstructionSet::kThumb2;
570 }
571 } else if (option.starts_with("--instruction-set-variant=")) {
572 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
573 instruction_set_features_.reset(
574 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
575 if (instruction_set_features_.get() == nullptr) {
576 Usage("%s", error_msg.c_str());
577 }
578 } else if (option.starts_with("--instruction-set-features=")) {
579 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
580 instruction_set_features_.reset(
581 InstructionSetFeatures::FromFeatureString(instruction_set_, str.as_string(),
582 &error_msg));
583 if (instruction_set_features_.get() == nullptr) {
584 Usage("%s", error_msg.c_str());
585 }
586 } else if (option.starts_with("--compiler-backend=")) {
587 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
588 if (backend_str == "Quick") {
589 compiler_kind_ = Compiler::kQuick;
590 } else if (backend_str == "Optimizing") {
591 compiler_kind_ = Compiler::kOptimizing;
Nicolas Geoffray0d8db992014-11-11 14:40:10 +0000592 compile_pic = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800593 } else if (backend_str == "Portable") {
594 compiler_kind_ = Compiler::kPortable;
595 } else {
596 Usage("Unknown compiler backend: %s", backend_str.data());
597 }
598 } else if (option.starts_with("--compiler-filter=")) {
599 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
600 } else if (option == "--compile-pic") {
601 compile_pic = true;
602 } else if (option.starts_with("--huge-method-max=")) {
603 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
604 if (!ParseInt(threshold, &huge_method_threshold)) {
605 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
606 }
607 if (huge_method_threshold < 0) {
608 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
609 }
610 } else if (option.starts_with("--large-method-max=")) {
611 const char* threshold = option.substr(strlen("--large-method-max=")).data();
612 if (!ParseInt(threshold, &large_method_threshold)) {
613 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
614 }
615 if (large_method_threshold < 0) {
616 Usage("--large-method-max passed a negative value %s", large_method_threshold);
617 }
618 } else if (option.starts_with("--small-method-max=")) {
619 const char* threshold = option.substr(strlen("--small-method-max=")).data();
620 if (!ParseInt(threshold, &small_method_threshold)) {
621 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
622 }
623 if (small_method_threshold < 0) {
624 Usage("--small-method-max passed a negative value %s", small_method_threshold);
625 }
626 } else if (option.starts_with("--tiny-method-max=")) {
627 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
628 if (!ParseInt(threshold, &tiny_method_threshold)) {
629 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
630 }
631 if (tiny_method_threshold < 0) {
632 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
633 }
634 } else if (option.starts_with("--num-dex-methods=")) {
635 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
636 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
637 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
638 }
639 if (num_dex_methods_threshold < 0) {
640 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
641 }
642 } else if (option == "--host") {
643 is_host_ = true;
644 } else if (option == "--runtime-arg") {
645 if (++i >= argc) {
646 Usage("Missing required argument for --runtime-arg");
647 }
648 if (log_options) {
649 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
650 }
651 runtime_args_.push_back(argv[i]);
652 } else if (option == "--dump-timing") {
653 dump_timing_ = true;
654 } else if (option == "--dump-passes") {
655 dump_passes_ = true;
656 } else if (option == "--dump-stats") {
657 dump_stats_ = true;
658 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
659 include_debug_symbols = true;
660 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
661 include_debug_symbols = false;
662 generate_gdb_information = false; // Depends on debug symbols, see above.
663 } else if (option.starts_with("--profile-file=")) {
664 profile_file_ = option.substr(strlen("--profile-file=")).data();
665 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
666 } else if (option == "--no-profile-file") {
667 // No profile
668 } else if (option.starts_with("--top-k-profile-threshold=")) {
669 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
670 } else if (option == "--print-pass-names") {
671 PassDriverMEOpts::PrintPassNames();
672 } else if (option.starts_with("--disable-passes=")) {
673 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
674 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
675 } else if (option.starts_with("--print-passes=")) {
676 std::string print_passes = option.substr(strlen("--print-passes=")).data();
677 PassDriverMEOpts::SetPrintPassList(print_passes);
678 } else if (option == "--print-all-passes") {
679 PassDriverMEOpts::SetPrintAllPasses();
680 } else if (option.starts_with("--dump-cfg-passes=")) {
681 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
682 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
683 } else if (option == "--print-pass-options") {
684 print_pass_options = true;
685 } else if (option.starts_with("--pass-options=")) {
686 std::string options = option.substr(strlen("--pass-options=")).data();
687 PassDriverMEOpts::SetOverriddenPassOptions(options);
688 } else if (option == "--include-patch-information") {
689 include_patch_information = true;
690 } else if (option == "--no-include-patch-information") {
691 include_patch_information = false;
692 } else if (option.starts_with("--verbose-methods=")) {
693 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
694 // on having verbost methods.
695 gLogVerbosity.compiler = false;
696 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
697 } else {
698 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700699 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800700 }
701
702 if (oat_filename_.empty() && oat_fd_ == -1) {
703 Usage("Output must be supplied with either --oat-file or --oat-fd");
704 }
705
706 if (!oat_filename_.empty() && oat_fd_ != -1) {
707 Usage("--oat-file should not be used with --oat-fd");
708 }
709
710 if (!oat_symbols.empty() && oat_fd_ != -1) {
711 Usage("--oat-symbols should not be used with --oat-fd");
712 }
713
714 if (!oat_symbols.empty() && is_host_) {
715 Usage("--oat-symbols should not be used with --host");
716 }
717
718 if (oat_fd_ != -1 && !image_filename_.empty()) {
719 Usage("--oat-fd should not be used with --image");
720 }
721
722 if (android_root_.empty()) {
723 const char* android_root_env_var = getenv("ANDROID_ROOT");
724 if (android_root_env_var == nullptr) {
725 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800727 android_root_ += android_root_env_var;
728 }
729
730 image_ = (!image_filename_.empty());
731 if (!image_ && boot_image_filename.empty()) {
732 boot_image_filename += android_root_;
733 boot_image_filename += "/framework/boot.art";
734 }
735 if (!boot_image_filename.empty()) {
736 boot_image_option_ += "-Ximage:";
737 boot_image_option_ += boot_image_filename;
738 }
739
740 if (image_classes_filename_ != nullptr && !image_) {
741 Usage("--image-classes should only be used with --image");
742 }
743
744 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
745 Usage("--image-classes should not be used with --boot-image");
746 }
747
748 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
749 Usage("--image-classes-zip should be used with --image-classes");
750 }
751
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800752 if (compiled_classes_filename_ != nullptr && !image_) {
753 Usage("--compiled-classes should only be used with --image");
754 }
755
756 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
757 Usage("--compiled-classes should not be used with --boot-image");
758 }
759
760 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
761 Usage("--compiled-classes-zip should be used with --compiled-classes");
762 }
763
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800764 if (dex_filenames_.empty() && zip_fd_ == -1) {
765 Usage("Input must be supplied with either --dex-file or --zip-fd");
766 }
767
768 if (!dex_filenames_.empty() && zip_fd_ != -1) {
769 Usage("--dex-file should not be used with --zip-fd");
770 }
771
772 if (!dex_filenames_.empty() && !zip_location_.empty()) {
773 Usage("--dex-file should not be used with --zip-location");
774 }
775
776 if (dex_locations_.empty()) {
777 for (const char* dex_file_name : dex_filenames_) {
778 dex_locations_.push_back(dex_file_name);
779 }
780 } else if (dex_locations_.size() != dex_filenames_.size()) {
781 Usage("--dex-location arguments do not match --dex-file arguments");
782 }
783
784 if (zip_fd_ != -1 && zip_location_.empty()) {
785 Usage("--zip-location should be supplied with --zip-fd");
786 }
787
788 if (boot_image_option_.empty()) {
789 if (image_base_ == 0) {
790 Usage("Non-zero --base not specified");
791 }
792 }
793
794 oat_stripped_ = oat_filename_;
795 if (!oat_symbols.empty()) {
796 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700797 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 oat_unstripped_ = oat_filename_;
799 }
800
801 // If no instruction set feature was given, use the default one for the target
802 // instruction set.
803 if (instruction_set_features_.get() == nullptr) {
804 instruction_set_features_.reset(
805 InstructionSetFeatures::FromFeatureString(instruction_set_, "default", &error_msg));
806 }
807
808 if (instruction_set_ == kRuntimeISA) {
809 std::unique_ptr<const InstructionSetFeatures> runtime_features(
810 InstructionSetFeatures::FromCppDefines());
811 if (!instruction_set_features_->Equals(runtime_features.get())) {
812 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
813 << *instruction_set_features_ << ") and those of dex2oat executable ("
814 << *runtime_features <<") for the command line:\n"
815 << CommandLine();
816 }
817 }
818
819 if (compiler_filter_string == nullptr) {
820 if (instruction_set_ == kMips64) {
821 // TODO: fix compiler for Mips64.
822 compiler_filter_string = "interpret-only";
823 } else if (image_) {
824 compiler_filter_string = "speed";
825 } else {
826 // TODO: Migrate SMALL mode to command line option.
827 #if ART_SMALL_MODE
828 compiler_filter_string = "interpret-only";
829 #else
830 compiler_filter_string = "speed";
831 #endif
832 }
833 }
834 CHECK(compiler_filter_string != nullptr);
835 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
836 if (strcmp(compiler_filter_string, "verify-none") == 0) {
837 compiler_filter = CompilerOptions::kVerifyNone;
838 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
839 compiler_filter = CompilerOptions::kInterpretOnly;
840 } else if (strcmp(compiler_filter_string, "space") == 0) {
841 compiler_filter = CompilerOptions::kSpace;
842 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
843 compiler_filter = CompilerOptions::kBalanced;
844 } else if (strcmp(compiler_filter_string, "speed") == 0) {
845 compiler_filter = CompilerOptions::kSpeed;
846 } else if (strcmp(compiler_filter_string, "everything") == 0) {
847 compiler_filter = CompilerOptions::kEverything;
848 } else if (strcmp(compiler_filter_string, "time") == 0) {
849 compiler_filter = CompilerOptions::kTime;
850 } else {
851 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
852 }
853
854 // Checks are all explicit until we know the architecture.
855 bool implicit_null_checks = false;
856 bool implicit_so_checks = false;
857 bool implicit_suspend_checks = false;
858 // Set the compilation target's implicit checks options.
859 switch (instruction_set_) {
860 case kArm:
861 case kThumb2:
862 case kArm64:
863 case kX86:
864 case kX86_64:
865 implicit_null_checks = true;
866 implicit_so_checks = true;
867 break;
868
869 default:
870 // Defaults are correct.
871 break;
872 }
873
874 if (print_pass_options) {
875 PassDriverMEOpts::PrintPassOptions();
876 }
877
878 compiler_options_.reset(new CompilerOptions(compiler_filter,
879 huge_method_threshold,
880 large_method_threshold,
881 small_method_threshold,
882 tiny_method_threshold,
883 num_dex_methods_threshold,
884 generate_gdb_information,
885 include_patch_information,
886 top_k_profile_threshold,
887 include_debug_symbols,
888 implicit_null_checks,
889 implicit_so_checks,
890 implicit_suspend_checks,
891 compile_pic,
892 #ifdef ART_SEA_IR_MODE
893 true,
894 #endif
895 verbose_methods_.empty() ?
896 nullptr :
897 &verbose_methods_));
898
899 // Done with usage checks, enable watchdog if requested
900 if (watch_dog_enabled) {
901 watchdog_.reset(new WatchDog(true));
902 }
903
904 // Fill some values into the key-value store for the oat header.
905 key_value_store_.reset(new SafeMap<std::string, std::string>());
906
907 // Insert some compiler things.
908 {
909 std::ostringstream oss;
910 for (int i = 0; i < argc; ++i) {
911 if (i > 0) {
912 oss << ' ';
913 }
914 oss << argv[i];
915 }
916 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
917 oss.str(""); // Reset.
918 oss << kRuntimeISA;
919 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
920 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
921 }
922 }
923
924 // Check whether the oat output file is writable, and open it for later.
925 bool OpenFile() {
926 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
927 if (create_file) {
928 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
929 if (oat_location_.empty()) {
930 oat_location_ = oat_filename_;
931 }
932 } else {
933 oat_file_.reset(new File(oat_fd_, oat_location_));
934 oat_file_->DisableAutoClose();
935 oat_file_->SetLength(0);
936 }
937 if (oat_file_.get() == nullptr) {
938 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
939 return false;
940 }
941 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
942 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
943 return false;
944 }
945 return true;
946 }
947
948 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
949 // boot class path.
950 bool Setup() {
951 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
952 RuntimeOptions runtime_options;
953 std::vector<const DexFile*> boot_class_path;
954 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
955 if (boot_image_option_.empty()) {
956 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800957 if (failure_count > 0) {
958 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800959 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800960 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800961 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
962 } else {
963 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
964 }
965 for (size_t i = 0; i < runtime_args_.size(); i++) {
966 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700968
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800969 verification_results_.reset(new VerificationResults(compiler_options_.get()));
970 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
971 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
972 runtime_options.push_back(
973 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
974
975 if (!CreateRuntime(runtime_options)) {
976 return false;
977 }
978
979 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
980 // Runtime::Start, give it away now so that we don't starve GC.
981 Thread* self = Thread::Current();
982 self->TransitionFromRunnableToSuspended(kNative);
983 // If we're doing the image, override the compiler filter to force full compilation. Must be
984 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
985 // compilation of class initializers.
986 // Whilst we're in native take the opportunity to initialize well known classes.
987 WellKnownClasses::Init(self->GetJniEnv());
988
989 // If --image-classes was specified, calculate the full list of classes to include in the image
990 if (image_classes_filename_ != nullptr) {
991 std::string error_msg;
992 if (image_classes_zip_filename_ != nullptr) {
993 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
994 image_classes_filename_,
995 &error_msg));
996 } else {
997 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
998 }
999 if (image_classes_.get() == nullptr) {
1000 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1001 "': " << error_msg;
1002 return false;
1003 }
1004 } else if (image_) {
1005 image_classes_.reset(new std::set<std::string>);
1006 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001007 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1008 // image.
1009 if (compiled_classes_filename_ != nullptr) {
1010 std::string error_msg;
1011 if (compiled_classes_zip_filename_ != nullptr) {
1012 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1013 compiled_classes_filename_,
1014 &error_msg));
1015 } else {
1016 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1017 }
1018 if (compiled_classes_.get() == nullptr) {
1019 LOG(ERROR) << "Failed to create list of compiled classes from '"
1020 << compiled_classes_filename_ << "': " << error_msg;
1021 return false;
1022 }
1023 } else if (image_) {
1024 compiled_classes_.reset(nullptr); // By default compile everything.
1025 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001026
1027 if (boot_image_option_.empty()) {
1028 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1029 } else {
1030 if (dex_filenames_.empty()) {
1031 ATRACE_BEGIN("Opening zip archive from file descriptor");
1032 std::string error_msg;
1033 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1034 zip_location_.c_str(),
1035 &error_msg));
1036 if (zip_archive.get() == nullptr) {
1037 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1038 << error_msg;
1039 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001040 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001041 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1042 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1043 << "': " << error_msg;
1044 return false;
1045 }
1046 ATRACE_END();
1047 } else {
1048 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1049 if (failure_count > 0) {
1050 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1051 return false;
1052 }
1053 }
1054
1055 constexpr bool kSaveDexInput = false;
1056 if (kSaveDexInput) {
1057 for (size_t i = 0; i < dex_files_.size(); ++i) {
1058 const DexFile* dex_file = dex_files_[i];
1059 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1060 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1061 if (tmp_file.get() == nullptr) {
1062 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1063 << ". Try: adb shell chmod 777 /data/local/tmp";
1064 continue;
1065 }
1066 tmp_file->WriteFully(dex_file->Begin(), dex_file->Size());
1067 LOG(INFO) << "Wrote input to " << tmp_file_name;
1068 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001069 }
1070 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001071 // Ensure opened dex files are writable for dex-to-dex transformations.
1072 for (const auto& dex_file : dex_files_) {
1073 if (!dex_file->EnableWrite()) {
1074 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001075 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001076 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001077
1078 /*
1079 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1080 * Don't bother to check if we're doing the image.
1081 */
1082 if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1083 size_t num_methods = 0;
1084 for (size_t i = 0; i != dex_files_.size(); ++i) {
1085 const DexFile* dex_file = dex_files_[i];
1086 CHECK(dex_file != nullptr);
1087 num_methods += dex_file->NumMethodIds();
1088 }
1089 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1090 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1091 VLOG(compiler) << "Below method threshold, compiling anyways";
1092 }
1093 }
1094
1095 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001096 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001097
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001098 // Create and invoke the compiler driver. This will compile all the dex files.
1099 void Compile() {
1100 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1101 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001102
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001103 // Handle and ClassLoader creation needs to come after Runtime::Create
1104 jobject class_loader = nullptr;
1105 Thread* self = Thread::Current();
1106 if (!boot_image_option_.empty()) {
1107 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1108 std::vector<const DexFile*> class_path_files(dex_files_);
1109 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1110 ScopedObjectAccess soa(self);
1111 for (size_t i = 0; i < class_path_files.size(); i++) {
1112 class_linker->RegisterDexFile(*class_path_files[i]);
1113 }
1114 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1115 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1116 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1117 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1118 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1119 }
1120
1121 driver_.reset(new CompilerDriver(compiler_options_.get(),
1122 verification_results_.get(),
1123 &method_inliner_map_,
1124 compiler_kind_,
1125 instruction_set_,
1126 instruction_set_features_.get(),
1127 image_,
1128 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001129 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 thread_count_,
1131 dump_stats_,
1132 dump_passes_,
1133 compiler_phases_timings_.get(),
1134 profile_file_));
1135
1136 driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1137
1138 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001139 }
1140
Brian Carlstrom7940e442013-07-12 13:46:57 -07001141 // Notes on the interleaving of creating the image and oat file to
1142 // ensure the references between the two are correct.
1143 //
1144 // Currently we have a memory layout that looks something like this:
1145 //
1146 // +--------------+
1147 // | image |
1148 // +--------------+
1149 // | boot oat |
1150 // +--------------+
1151 // | alloc spaces |
1152 // +--------------+
1153 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001154 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155 //
1156 // 1. The image is expected to be loaded at an absolute address and
1157 // contains Objects with absolute pointers within the image.
1158 //
1159 // 2. There are absolute pointers from Methods in the image to their
1160 // code in the oat.
1161 //
1162 // 3. There are absolute pointers from the code in the oat to Methods
1163 // in the image.
1164 //
1165 // 4. There are absolute pointers from code in the oat to other code
1166 // in the oat.
1167 //
1168 // To get this all correct, we go through several steps.
1169 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001170 // 1. We prepare offsets for all data in the oat file and calculate
1171 // the oat data size and code size. During this stage, we also set
1172 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001173 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001174 // 2. We prepare offsets for the objects in the image and calculate
1175 // the image size.
1176 //
1177 // 3. We create the oat file. Originally this was just our own proprietary
1178 // file but now it is contained within an ELF dynamic object (aka an .so
1179 // file). Since we know the image size and oat data size and code size we
1180 // can prepare the ELF headers and we then know the ELF memory segment
1181 // layout and we can now resolve all references. The compiler provides
1182 // LinkerPatch information in each CompiledMethod and we resolve these,
1183 // using the layout information and image object locations provided by
1184 // image writer, as we're writing the method code.
1185 //
1186 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001187 // will be loaded after itself. Originally when oat file was simply
1188 // memory mapped so we could predict where its contents were based
1189 // on the file size. Now that it is an ELF file, we need to inspect
1190 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001191 // where the oat header is located within.
1192 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001193 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001194 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001195 // load the .so at the desired location at runtime by offsetting the
1196 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001197 // TODO: Do this in step 3. We already know the layout there.
1198 //
1199 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1200 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001201
1202
1203 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1204 // ImageWriter, if necessary.
1205 bool CreateOatFile() {
1206 CHECK(key_value_store_.get() != nullptr);
1207
1208 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1209
1210 std::unique_ptr<OatWriter> oat_writer;
1211 {
1212 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1213 std::string image_file_location;
1214 uint32_t image_file_location_oat_checksum = 0;
1215 uintptr_t image_file_location_oat_data_begin = 0;
1216 int32_t image_patch_delta = 0;
1217 if (image_) {
1218 PrepareImageWriter(image_base_);
1219 } else {
1220 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1221 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1222 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1223 image_file_location_oat_data_begin =
1224 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1225 image_file_location = image_space->GetImageFilename();
1226 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1227 }
1228
1229 if (!image_file_location.empty()) {
1230 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1231 }
1232
1233 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1234 image_file_location_oat_data_begin,
1235 image_patch_delta,
1236 driver_.get(),
1237 image_writer_.get(),
1238 timings_,
1239 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001240 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001241
1242 if (image_) {
1243 // The OatWriter constructor has already updated offsets in methods and we need to
1244 // prepare method offsets in the image address space for direct method patching.
1245 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1246 if (!image_writer_->PrepareImageAddressSpace()) {
1247 LOG(ERROR) << "Failed to prepare image address space.";
1248 return false;
1249 }
1250 }
1251
1252 {
1253 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1254 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1255 oat_file_.get())) {
1256 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1257 return false;
1258 }
1259 }
1260
1261 // Flush result to disk.
1262 {
1263 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1264 if (oat_file_->Flush() != 0) {
1265 LOG(ERROR) << "Failed to flush ELF file " << oat_file_->GetPath();
1266 return false;
1267 }
1268 }
1269
1270 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1271 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001272 }
1273
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001274 // If we are compiling an image, invoke the image creation routine. Else just skip.
1275 bool HandleImage() {
1276 if (image_) {
1277 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1278 if (!CreateImageFile()) {
1279 return false;
1280 }
1281 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001282 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001283 return true;
1284 }
1285
1286 // Strip the oat file, if requested. This first creates a copy from unstripped to stripped, and
1287 // then runs the ElfStripper. Currently only relevant for the portable compiler.
1288 bool Strip() {
1289 // If we don't want to strip in place, copy from unstripped location to stripped location.
1290 // We need to strip after image creation because FixupElf needs to use .strtab.
1291 if (oat_unstripped_ != oat_stripped_) {
1292 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1293 oat_file_.reset();
1294 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1295 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1296 size_t buffer_size = 8192;
1297 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1298 while (true) {
1299 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1300 if (bytes_read <= 0) {
1301 break;
1302 }
1303 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1304 CHECK(write_ok);
1305 }
1306 oat_file_.reset(out.release());
1307 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001308 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001309
1310 if (kUsePortableCompiler) {
1311 // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1312 // strip them now. Quick generates debug symbols only when the flag(s) are set.
1313 if (!compiler_options_->GetIncludeDebugSymbols()) {
1314 TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1315 // Strip unneeded sections for target
1316 off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1317 CHECK_EQ(0, seek_actual);
1318 std::string error_msg;
1319 if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1320 LOG(ERROR) << "Failed to strip elf file: " << error_msg;
1321 return false;
1322 }
1323
1324 // We wrote the oat file successfully, and want to keep it.
1325 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1326 } else {
1327 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1328 }
1329 }
1330
1331 return true;
1332 }
1333
1334 void DumpTiming() {
1335 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1336 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1337 }
1338 if (dump_passes_) {
1339 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1340 }
1341 }
1342
1343 CompilerOptions* GetCompilerOptions() const {
1344 return compiler_options_.get();
1345 }
1346
1347 bool IsHost() const {
1348 return is_host_;
1349 }
1350
1351 private:
1352 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1353 const std::vector<const char*>& dex_locations,
1354 std::vector<const DexFile*>& dex_files) {
1355 size_t failure_count = 0;
1356 for (size_t i = 0; i < dex_filenames.size(); i++) {
1357 const char* dex_filename = dex_filenames[i];
1358 const char* dex_location = dex_locations[i];
1359 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1360 std::string error_msg;
1361 if (!OS::FileExists(dex_filename)) {
1362 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1363 continue;
1364 }
1365 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1366 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1367 ++failure_count;
1368 }
1369 ATRACE_END();
1370 }
1371 return failure_count;
1372 }
1373
1374 // Returns true if dex_files has a dex with the named location.
1375 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1376 const std::string& location) {
1377 for (size_t i = 0; i < dex_files.size(); ++i) {
1378 if (dex_files[i]->GetLocation() == location) {
1379 return true;
1380 }
1381 }
1382 return false;
1383 }
1384
1385 // Appends to dex_files any elements of class_path that it doesn't already
1386 // contain. This will open those dex files as necessary.
1387 static void OpenClassPathFiles(const std::string& class_path,
1388 std::vector<const DexFile*>& dex_files) {
1389 std::vector<std::string> parsed;
1390 Split(class_path, ':', &parsed);
1391 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1392 ScopedObjectAccess soa(Thread::Current());
1393 for (size_t i = 0; i < parsed.size(); ++i) {
1394 if (DexFilesContains(dex_files, parsed[i])) {
1395 continue;
1396 }
1397 std::string error_msg;
1398 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1399 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1400 }
1401 }
1402 }
1403
1404 // Create a runtime necessary for compilation.
1405 bool CreateRuntime(const RuntimeOptions& runtime_options)
1406 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1407 if (!Runtime::Create(runtime_options, false)) {
1408 LOG(ERROR) << "Failed to create runtime";
1409 return false;
1410 }
1411 Runtime* runtime = Runtime::Current();
1412 runtime->SetInstructionSet(instruction_set_);
1413 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1414 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1415 if (!runtime->HasCalleeSaveMethod(type)) {
1416 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1417 }
1418 }
1419 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1420 runtime->GetClassLinker()->RunRootClinits();
1421 runtime_ = runtime;
1422 return true;
1423 }
1424
1425 void PrepareImageWriter(uintptr_t image_base) {
1426 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1427 }
1428
1429 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1430 bool CreateImageFile()
1431 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1432 CHECK(image_writer_ != nullptr);
1433 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1434 LOG(ERROR) << "Failed to create image file " << image_filename_;
1435 return false;
1436 }
1437 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1438
1439 // Destroy ImageWriter before doing FixupElf.
1440 image_writer_.reset();
1441
1442 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1443 if (oat_file.get() == nullptr) {
1444 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1445 return false;
1446 }
1447
1448 // Do not fix up the ELF file if we are --compile-pic
1449 if (!compiler_options_->GetCompilePic()) {
1450 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
1451 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1452 return false;
1453 }
1454 }
1455
1456 return true;
1457 }
1458
1459 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1460 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1461 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1462 std::ifstream::in));
1463 if (image_classes_file.get() == nullptr) {
1464 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1465 return nullptr;
1466 }
1467 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1468 image_classes_file->close();
1469 return result.release();
1470 }
1471
1472 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1473 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1474 while (image_classes_stream.good()) {
1475 std::string dot;
1476 std::getline(image_classes_stream, dot);
1477 if (StartsWith(dot, "#") || dot.empty()) {
1478 continue;
1479 }
1480 std::string descriptor(DotToDescriptor(dot.c_str()));
1481 image_classes->insert(descriptor);
1482 }
1483 return image_classes.release();
1484 }
1485
1486 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1487 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1488 const char* image_classes_filename,
1489 std::string* error_msg) {
1490 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1491 if (zip_archive.get() == nullptr) {
1492 return nullptr;
1493 }
1494 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1495 if (zip_entry.get() == nullptr) {
1496 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1497 zip_filename, error_msg->c_str());
1498 return nullptr;
1499 }
1500 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1501 image_classes_filename,
1502 error_msg));
1503 if (image_classes_file.get() == nullptr) {
1504 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1505 zip_filename, error_msg->c_str());
1506 return nullptr;
1507 }
1508 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1509 image_classes_file->Size());
1510 std::istringstream image_classes_stream(image_classes_string);
1511 return ReadImageClasses(image_classes_stream);
1512 }
1513
1514 void LogCompletionTime() const {
1515 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
1516 << " (threads: " << thread_count_ << ")";
1517 }
1518
1519 std::unique_ptr<CompilerOptions> compiler_options_;
1520 Compiler::Kind compiler_kind_;
1521
1522 InstructionSet instruction_set_;
1523 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1524
1525 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1526
1527 std::unique_ptr<VerificationResults> verification_results_;
1528 DexFileToMethodInlinerMap method_inliner_map_;
1529 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1530
1531 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1532 // in an orderly fashion. The destructor takes care of deleting this.
1533 Runtime* runtime_;
1534
1535 size_t thread_count_;
1536 uint64_t start_ns_;
1537 std::unique_ptr<WatchDog> watchdog_;
1538 std::unique_ptr<File> oat_file_;
1539 std::string oat_stripped_;
1540 std::string oat_unstripped_;
1541 std::string oat_location_;
1542 std::string oat_filename_;
1543 int oat_fd_;
1544 std::string bitcode_filename_;
1545 std::vector<const char*> dex_filenames_;
1546 std::vector<const char*> dex_locations_;
1547 int zip_fd_;
1548 std::string zip_location_;
1549 std::string boot_image_option_;
1550 std::vector<const char*> runtime_args_;
1551 std::string image_filename_;
1552 uintptr_t image_base_;
1553 const char* image_classes_zip_filename_;
1554 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001555 const char* compiled_classes_zip_filename_;
1556 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001557 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001558 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001559 bool image_;
1560 std::unique_ptr<ImageWriter> image_writer_;
1561 bool is_host_;
1562 std::string android_root_;
1563 std::vector<const DexFile*> dex_files_;
1564 std::unique_ptr<CompilerDriver> driver_;
1565 std::vector<std::string> verbose_methods_;
1566 bool dump_stats_;
1567 bool dump_passes_;
1568 bool dump_timing_;
1569 bool dump_slow_timing_;
1570 std::string profile_file_; // Profile file to use
1571 TimingLogger* timings_;
1572 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1573
1574 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1575};
1576
1577const unsigned int WatchDog::kWatchDogWarningSeconds;
1578const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1579
1580static void b13564922() {
1581#if defined(__linux__) && defined(__arm__)
1582 int major, minor;
1583 struct utsname uts;
1584 if (uname(&uts) != -1 &&
1585 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1586 ((major < 3) || ((major == 3) && (minor < 4)))) {
1587 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1588 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1589 int old_personality = personality(0xffffffff);
1590 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1591 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1592 if (new_personality == -1) {
1593 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1594 }
1595 }
1596 }
1597#endif
1598}
1599
1600static int dex2oat(int argc, char** argv) {
1601 b13564922();
1602
1603 TimingLogger timings("compiler", false, false);
1604
1605 Dex2Oat dex2oat(&timings);
1606
1607 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1608 dex2oat.ParseArgs(argc, argv);
1609
1610 // Check early that the result of compilation can be written
1611 if (!dex2oat.OpenFile()) {
1612 return EXIT_FAILURE;
1613 }
1614
1615 LOG(INFO) << CommandLine();
1616
1617 if (!dex2oat.Setup()) {
1618 return EXIT_FAILURE;
1619 }
1620
1621 dex2oat.Compile();
1622
1623 if (!dex2oat.CreateOatFile()) {
1624 return EXIT_FAILURE;
1625 }
1626
1627 if (!dex2oat.HandleImage()) {
1628 return EXIT_FAILURE;
1629 }
1630
1631 if (dex2oat.IsHost()) {
1632 dex2oat.DumpTiming();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633 return EXIT_SUCCESS;
1634 }
1635
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001636 if (!dex2oat.Strip()) {
1637 return EXIT_FAILURE;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001638 }
1639
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001640 dex2oat.DumpTiming();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001641 return EXIT_SUCCESS;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001642}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001643} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001644
1645int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001646 int result = art::dex2oat(argc, argv);
1647 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1648 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1649 // should not destruct the runtime in this case.
1650 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1651 exit(result);
1652 }
1653 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001654}