blob: d87faebac07661defcab72f53915b63d874986cb [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),
433 image_(false),
434 is_host_(false),
435 dump_stats_(false),
436 dump_passes_(false),
437 dump_timing_(false),
438 dump_slow_timing_(kIsDebugBuild),
439 timings_(timings) {}
440
441 ~Dex2Oat() {
442 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
443 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100444 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445 LogCompletionTime();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 }
447
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800448 // Parse the arguments from the command line. In case of an unrecognized option or impossible
449 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
450 // returns, arguments have been successfully parsed.
451 void ParseArgs(int argc, char** argv) {
452 original_argc = argc;
453 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700454
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700456
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800457 // Skip over argv[0].
458 argv++;
459 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700460
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800461 if (argc == 0) {
462 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800464
465 std::string oat_symbols;
466 std::string boot_image_filename;
467 const char* compiler_filter_string = nullptr;
468 bool compile_pic = false;
469 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
470 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
471 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
472 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
473 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
474
475 // Profile file to use
476 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
477
478 bool print_pass_options = false;
479 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
480 bool include_debug_symbols = kIsDebugBuild;
481 bool watch_dog_enabled = true;
482 bool generate_gdb_information = kIsDebugBuild;
483
484 std::string error_msg;
485
486 for (int i = 0; i < argc; i++) {
487 const StringPiece option(argv[i]);
488 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700489 if (log_options) {
490 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
491 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800492 if (option.starts_with("--dex-file=")) {
493 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
494 } else if (option.starts_with("--dex-location=")) {
495 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
496 } else if (option.starts_with("--zip-fd=")) {
497 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
498 if (!ParseInt(zip_fd_str, &zip_fd_)) {
499 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
500 }
501 if (zip_fd_ < 0) {
502 Usage("--zip-fd passed a negative value %d", zip_fd_);
503 }
504 } else if (option.starts_with("--zip-location=")) {
505 zip_location_ = option.substr(strlen("--zip-location=")).data();
506 } else if (option.starts_with("--oat-file=")) {
507 oat_filename_ = option.substr(strlen("--oat-file=")).data();
508 } else if (option.starts_with("--oat-symbols=")) {
509 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
510 } else if (option.starts_with("--oat-fd=")) {
511 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
512 if (!ParseInt(oat_fd_str, &oat_fd_)) {
513 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
514 }
515 if (oat_fd_ < 0) {
516 Usage("--oat-fd passed a negative value %d", oat_fd_);
517 }
518 } else if (option == "--watch-dog") {
519 watch_dog_enabled = true;
520 } else if (option == "--no-watch-dog") {
521 watch_dog_enabled = false;
522 } else if (option == "--gen-gdb-info") {
523 generate_gdb_information = true;
524 // Debug symbols are needed for gdb information.
525 include_debug_symbols = true;
526 } else if (option == "--no-gen-gdb-info") {
527 generate_gdb_information = false;
528 } else if (option.starts_with("-j")) {
529 const char* thread_count_str = option.substr(strlen("-j")).data();
530 if (!ParseUint(thread_count_str, &thread_count_)) {
531 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
532 }
533 } else if (option.starts_with("--oat-location=")) {
534 oat_location_ = option.substr(strlen("--oat-location=")).data();
535 } else if (option.starts_with("--bitcode=")) {
536 bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
537 } else if (option.starts_with("--image=")) {
538 image_filename_ = option.substr(strlen("--image=")).data();
539 } else if (option.starts_with("--image-classes=")) {
540 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
541 } else if (option.starts_with("--image-classes-zip=")) {
542 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
543 } else if (option.starts_with("--base=")) {
544 const char* image_base_str = option.substr(strlen("--base=")).data();
545 char* end;
546 image_base_ = strtoul(image_base_str, &end, 16);
547 if (end == image_base_str || *end != '\0') {
548 Usage("Failed to parse hexadecimal value for option %s", option.data());
549 }
550 } else if (option.starts_with("--boot-image=")) {
551 boot_image_filename = option.substr(strlen("--boot-image=")).data();
552 } else if (option.starts_with("--android-root=")) {
553 android_root_ = option.substr(strlen("--android-root=")).data();
554 } else if (option.starts_with("--instruction-set=")) {
555 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
556 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
557 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
558 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
559 buf.get()[instruction_set_str.length()] = 0;
560 instruction_set_ = GetInstructionSetFromString(buf.get());
561 // arm actually means thumb2.
562 if (instruction_set_ == InstructionSet::kArm) {
563 instruction_set_ = InstructionSet::kThumb2;
564 }
565 } else if (option.starts_with("--instruction-set-variant=")) {
566 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
567 instruction_set_features_.reset(
568 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
569 if (instruction_set_features_.get() == nullptr) {
570 Usage("%s", error_msg.c_str());
571 }
572 } else if (option.starts_with("--instruction-set-features=")) {
573 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
574 instruction_set_features_.reset(
575 InstructionSetFeatures::FromFeatureString(instruction_set_, str.as_string(),
576 &error_msg));
577 if (instruction_set_features_.get() == nullptr) {
578 Usage("%s", error_msg.c_str());
579 }
580 } else if (option.starts_with("--compiler-backend=")) {
581 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
582 if (backend_str == "Quick") {
583 compiler_kind_ = Compiler::kQuick;
584 } else if (backend_str == "Optimizing") {
585 compiler_kind_ = Compiler::kOptimizing;
586 } else if (backend_str == "Portable") {
587 compiler_kind_ = Compiler::kPortable;
588 } else {
589 Usage("Unknown compiler backend: %s", backend_str.data());
590 }
591 } else if (option.starts_with("--compiler-filter=")) {
592 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
593 } else if (option == "--compile-pic") {
594 compile_pic = true;
595 } else if (option.starts_with("--huge-method-max=")) {
596 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
597 if (!ParseInt(threshold, &huge_method_threshold)) {
598 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
599 }
600 if (huge_method_threshold < 0) {
601 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
602 }
603 } else if (option.starts_with("--large-method-max=")) {
604 const char* threshold = option.substr(strlen("--large-method-max=")).data();
605 if (!ParseInt(threshold, &large_method_threshold)) {
606 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
607 }
608 if (large_method_threshold < 0) {
609 Usage("--large-method-max passed a negative value %s", large_method_threshold);
610 }
611 } else if (option.starts_with("--small-method-max=")) {
612 const char* threshold = option.substr(strlen("--small-method-max=")).data();
613 if (!ParseInt(threshold, &small_method_threshold)) {
614 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
615 }
616 if (small_method_threshold < 0) {
617 Usage("--small-method-max passed a negative value %s", small_method_threshold);
618 }
619 } else if (option.starts_with("--tiny-method-max=")) {
620 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
621 if (!ParseInt(threshold, &tiny_method_threshold)) {
622 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
623 }
624 if (tiny_method_threshold < 0) {
625 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
626 }
627 } else if (option.starts_with("--num-dex-methods=")) {
628 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
629 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
630 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
631 }
632 if (num_dex_methods_threshold < 0) {
633 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
634 }
635 } else if (option == "--host") {
636 is_host_ = true;
637 } else if (option == "--runtime-arg") {
638 if (++i >= argc) {
639 Usage("Missing required argument for --runtime-arg");
640 }
641 if (log_options) {
642 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
643 }
644 runtime_args_.push_back(argv[i]);
645 } else if (option == "--dump-timing") {
646 dump_timing_ = true;
647 } else if (option == "--dump-passes") {
648 dump_passes_ = true;
649 } else if (option == "--dump-stats") {
650 dump_stats_ = true;
651 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
652 include_debug_symbols = true;
653 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
654 include_debug_symbols = false;
655 generate_gdb_information = false; // Depends on debug symbols, see above.
656 } else if (option.starts_with("--profile-file=")) {
657 profile_file_ = option.substr(strlen("--profile-file=")).data();
658 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
659 } else if (option == "--no-profile-file") {
660 // No profile
661 } else if (option.starts_with("--top-k-profile-threshold=")) {
662 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
663 } else if (option == "--print-pass-names") {
664 PassDriverMEOpts::PrintPassNames();
665 } else if (option.starts_with("--disable-passes=")) {
666 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
667 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
668 } else if (option.starts_with("--print-passes=")) {
669 std::string print_passes = option.substr(strlen("--print-passes=")).data();
670 PassDriverMEOpts::SetPrintPassList(print_passes);
671 } else if (option == "--print-all-passes") {
672 PassDriverMEOpts::SetPrintAllPasses();
673 } else if (option.starts_with("--dump-cfg-passes=")) {
674 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
675 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
676 } else if (option == "--print-pass-options") {
677 print_pass_options = true;
678 } else if (option.starts_with("--pass-options=")) {
679 std::string options = option.substr(strlen("--pass-options=")).data();
680 PassDriverMEOpts::SetOverriddenPassOptions(options);
681 } else if (option == "--include-patch-information") {
682 include_patch_information = true;
683 } else if (option == "--no-include-patch-information") {
684 include_patch_information = false;
685 } else if (option.starts_with("--verbose-methods=")) {
686 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
687 // on having verbost methods.
688 gLogVerbosity.compiler = false;
689 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
690 } else {
691 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800693 }
694
695 if (oat_filename_.empty() && oat_fd_ == -1) {
696 Usage("Output must be supplied with either --oat-file or --oat-fd");
697 }
698
699 if (!oat_filename_.empty() && oat_fd_ != -1) {
700 Usage("--oat-file should not be used with --oat-fd");
701 }
702
703 if (!oat_symbols.empty() && oat_fd_ != -1) {
704 Usage("--oat-symbols should not be used with --oat-fd");
705 }
706
707 if (!oat_symbols.empty() && is_host_) {
708 Usage("--oat-symbols should not be used with --host");
709 }
710
711 if (oat_fd_ != -1 && !image_filename_.empty()) {
712 Usage("--oat-fd should not be used with --image");
713 }
714
715 if (android_root_.empty()) {
716 const char* android_root_env_var = getenv("ANDROID_ROOT");
717 if (android_root_env_var == nullptr) {
718 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 android_root_ += android_root_env_var;
721 }
722
723 image_ = (!image_filename_.empty());
724 if (!image_ && boot_image_filename.empty()) {
725 boot_image_filename += android_root_;
726 boot_image_filename += "/framework/boot.art";
727 }
728 if (!boot_image_filename.empty()) {
729 boot_image_option_ += "-Ximage:";
730 boot_image_option_ += boot_image_filename;
731 }
732
733 if (image_classes_filename_ != nullptr && !image_) {
734 Usage("--image-classes should only be used with --image");
735 }
736
737 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
738 Usage("--image-classes should not be used with --boot-image");
739 }
740
741 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
742 Usage("--image-classes-zip should be used with --image-classes");
743 }
744
745 if (dex_filenames_.empty() && zip_fd_ == -1) {
746 Usage("Input must be supplied with either --dex-file or --zip-fd");
747 }
748
749 if (!dex_filenames_.empty() && zip_fd_ != -1) {
750 Usage("--dex-file should not be used with --zip-fd");
751 }
752
753 if (!dex_filenames_.empty() && !zip_location_.empty()) {
754 Usage("--dex-file should not be used with --zip-location");
755 }
756
757 if (dex_locations_.empty()) {
758 for (const char* dex_file_name : dex_filenames_) {
759 dex_locations_.push_back(dex_file_name);
760 }
761 } else if (dex_locations_.size() != dex_filenames_.size()) {
762 Usage("--dex-location arguments do not match --dex-file arguments");
763 }
764
765 if (zip_fd_ != -1 && zip_location_.empty()) {
766 Usage("--zip-location should be supplied with --zip-fd");
767 }
768
769 if (boot_image_option_.empty()) {
770 if (image_base_ == 0) {
771 Usage("Non-zero --base not specified");
772 }
773 }
774
775 oat_stripped_ = oat_filename_;
776 if (!oat_symbols.empty()) {
777 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700778 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800779 oat_unstripped_ = oat_filename_;
780 }
781
782 // If no instruction set feature was given, use the default one for the target
783 // instruction set.
784 if (instruction_set_features_.get() == nullptr) {
785 instruction_set_features_.reset(
786 InstructionSetFeatures::FromFeatureString(instruction_set_, "default", &error_msg));
787 }
788
789 if (instruction_set_ == kRuntimeISA) {
790 std::unique_ptr<const InstructionSetFeatures> runtime_features(
791 InstructionSetFeatures::FromCppDefines());
792 if (!instruction_set_features_->Equals(runtime_features.get())) {
793 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
794 << *instruction_set_features_ << ") and those of dex2oat executable ("
795 << *runtime_features <<") for the command line:\n"
796 << CommandLine();
797 }
798 }
799
800 if (compiler_filter_string == nullptr) {
801 if (instruction_set_ == kMips64) {
802 // TODO: fix compiler for Mips64.
803 compiler_filter_string = "interpret-only";
804 } else if (image_) {
805 compiler_filter_string = "speed";
806 } else {
807 // TODO: Migrate SMALL mode to command line option.
808 #if ART_SMALL_MODE
809 compiler_filter_string = "interpret-only";
810 #else
811 compiler_filter_string = "speed";
812 #endif
813 }
814 }
815 CHECK(compiler_filter_string != nullptr);
816 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
817 if (strcmp(compiler_filter_string, "verify-none") == 0) {
818 compiler_filter = CompilerOptions::kVerifyNone;
819 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
820 compiler_filter = CompilerOptions::kInterpretOnly;
821 } else if (strcmp(compiler_filter_string, "space") == 0) {
822 compiler_filter = CompilerOptions::kSpace;
823 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
824 compiler_filter = CompilerOptions::kBalanced;
825 } else if (strcmp(compiler_filter_string, "speed") == 0) {
826 compiler_filter = CompilerOptions::kSpeed;
827 } else if (strcmp(compiler_filter_string, "everything") == 0) {
828 compiler_filter = CompilerOptions::kEverything;
829 } else if (strcmp(compiler_filter_string, "time") == 0) {
830 compiler_filter = CompilerOptions::kTime;
831 } else {
832 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
833 }
834
835 // Checks are all explicit until we know the architecture.
836 bool implicit_null_checks = false;
837 bool implicit_so_checks = false;
838 bool implicit_suspend_checks = false;
839 // Set the compilation target's implicit checks options.
840 switch (instruction_set_) {
841 case kArm:
842 case kThumb2:
843 case kArm64:
844 case kX86:
845 case kX86_64:
846 implicit_null_checks = true;
847 implicit_so_checks = true;
848 break;
849
850 default:
851 // Defaults are correct.
852 break;
853 }
854
855 if (print_pass_options) {
856 PassDriverMEOpts::PrintPassOptions();
857 }
858
859 compiler_options_.reset(new CompilerOptions(compiler_filter,
860 huge_method_threshold,
861 large_method_threshold,
862 small_method_threshold,
863 tiny_method_threshold,
864 num_dex_methods_threshold,
865 generate_gdb_information,
866 include_patch_information,
867 top_k_profile_threshold,
868 include_debug_symbols,
869 implicit_null_checks,
870 implicit_so_checks,
871 implicit_suspend_checks,
872 compile_pic,
873 #ifdef ART_SEA_IR_MODE
874 true,
875 #endif
876 verbose_methods_.empty() ?
877 nullptr :
878 &verbose_methods_));
879
880 // Done with usage checks, enable watchdog if requested
881 if (watch_dog_enabled) {
882 watchdog_.reset(new WatchDog(true));
883 }
884
885 // Fill some values into the key-value store for the oat header.
886 key_value_store_.reset(new SafeMap<std::string, std::string>());
887
888 // Insert some compiler things.
889 {
890 std::ostringstream oss;
891 for (int i = 0; i < argc; ++i) {
892 if (i > 0) {
893 oss << ' ';
894 }
895 oss << argv[i];
896 }
897 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
898 oss.str(""); // Reset.
899 oss << kRuntimeISA;
900 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
901 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
902 }
903 }
904
905 // Check whether the oat output file is writable, and open it for later.
906 bool OpenFile() {
907 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
908 if (create_file) {
909 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
910 if (oat_location_.empty()) {
911 oat_location_ = oat_filename_;
912 }
913 } else {
914 oat_file_.reset(new File(oat_fd_, oat_location_));
915 oat_file_->DisableAutoClose();
916 oat_file_->SetLength(0);
917 }
918 if (oat_file_.get() == nullptr) {
919 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
920 return false;
921 }
922 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
923 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
924 return false;
925 }
926 return true;
927 }
928
929 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
930 // boot class path.
931 bool Setup() {
932 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
933 RuntimeOptions runtime_options;
934 std::vector<const DexFile*> boot_class_path;
935 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
936 if (boot_image_option_.empty()) {
937 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800938 if (failure_count > 0) {
939 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800940 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800941 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800942 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
943 } else {
944 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
945 }
946 for (size_t i = 0; i < runtime_args_.size(); i++) {
947 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700949
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800950 verification_results_.reset(new VerificationResults(compiler_options_.get()));
951 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
952 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
953 runtime_options.push_back(
954 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
955
956 if (!CreateRuntime(runtime_options)) {
957 return false;
958 }
959
960 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
961 // Runtime::Start, give it away now so that we don't starve GC.
962 Thread* self = Thread::Current();
963 self->TransitionFromRunnableToSuspended(kNative);
964 // If we're doing the image, override the compiler filter to force full compilation. Must be
965 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
966 // compilation of class initializers.
967 // Whilst we're in native take the opportunity to initialize well known classes.
968 WellKnownClasses::Init(self->GetJniEnv());
969
970 // If --image-classes was specified, calculate the full list of classes to include in the image
971 if (image_classes_filename_ != nullptr) {
972 std::string error_msg;
973 if (image_classes_zip_filename_ != nullptr) {
974 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
975 image_classes_filename_,
976 &error_msg));
977 } else {
978 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
979 }
980 if (image_classes_.get() == nullptr) {
981 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
982 "': " << error_msg;
983 return false;
984 }
985 } else if (image_) {
986 image_classes_.reset(new std::set<std::string>);
987 }
988
989 if (boot_image_option_.empty()) {
990 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
991 } else {
992 if (dex_filenames_.empty()) {
993 ATRACE_BEGIN("Opening zip archive from file descriptor");
994 std::string error_msg;
995 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
996 zip_location_.c_str(),
997 &error_msg));
998 if (zip_archive.get() == nullptr) {
999 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1000 << error_msg;
1001 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001002 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001003 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1004 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1005 << "': " << error_msg;
1006 return false;
1007 }
1008 ATRACE_END();
1009 } else {
1010 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1011 if (failure_count > 0) {
1012 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1013 return false;
1014 }
1015 }
1016
1017 constexpr bool kSaveDexInput = false;
1018 if (kSaveDexInput) {
1019 for (size_t i = 0; i < dex_files_.size(); ++i) {
1020 const DexFile* dex_file = dex_files_[i];
1021 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1022 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1023 if (tmp_file.get() == nullptr) {
1024 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1025 << ". Try: adb shell chmod 777 /data/local/tmp";
1026 continue;
1027 }
1028 tmp_file->WriteFully(dex_file->Begin(), dex_file->Size());
1029 LOG(INFO) << "Wrote input to " << tmp_file_name;
1030 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001031 }
1032 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001033 // Ensure opened dex files are writable for dex-to-dex transformations.
1034 for (const auto& dex_file : dex_files_) {
1035 if (!dex_file->EnableWrite()) {
1036 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001037 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001038 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001039
1040 /*
1041 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1042 * Don't bother to check if we're doing the image.
1043 */
1044 if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1045 size_t num_methods = 0;
1046 for (size_t i = 0; i != dex_files_.size(); ++i) {
1047 const DexFile* dex_file = dex_files_[i];
1048 CHECK(dex_file != nullptr);
1049 num_methods += dex_file->NumMethodIds();
1050 }
1051 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1052 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1053 VLOG(compiler) << "Below method threshold, compiling anyways";
1054 }
1055 }
1056
1057 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001058 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001059
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001060 // Create and invoke the compiler driver. This will compile all the dex files.
1061 void Compile() {
1062 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1063 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001064
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001065 // Handle and ClassLoader creation needs to come after Runtime::Create
1066 jobject class_loader = nullptr;
1067 Thread* self = Thread::Current();
1068 if (!boot_image_option_.empty()) {
1069 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1070 std::vector<const DexFile*> class_path_files(dex_files_);
1071 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1072 ScopedObjectAccess soa(self);
1073 for (size_t i = 0; i < class_path_files.size(); i++) {
1074 class_linker->RegisterDexFile(*class_path_files[i]);
1075 }
1076 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1077 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1078 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1079 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1080 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1081 }
1082
1083 driver_.reset(new CompilerDriver(compiler_options_.get(),
1084 verification_results_.get(),
1085 &method_inliner_map_,
1086 compiler_kind_,
1087 instruction_set_,
1088 instruction_set_features_.get(),
1089 image_,
1090 image_classes_.release(),
1091 thread_count_,
1092 dump_stats_,
1093 dump_passes_,
1094 compiler_phases_timings_.get(),
1095 profile_file_));
1096
1097 driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1098
1099 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001100 }
1101
Brian Carlstrom7940e442013-07-12 13:46:57 -07001102 // Notes on the interleaving of creating the image and oat file to
1103 // ensure the references between the two are correct.
1104 //
1105 // Currently we have a memory layout that looks something like this:
1106 //
1107 // +--------------+
1108 // | image |
1109 // +--------------+
1110 // | boot oat |
1111 // +--------------+
1112 // | alloc spaces |
1113 // +--------------+
1114 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001115 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001116 //
1117 // 1. The image is expected to be loaded at an absolute address and
1118 // contains Objects with absolute pointers within the image.
1119 //
1120 // 2. There are absolute pointers from Methods in the image to their
1121 // code in the oat.
1122 //
1123 // 3. There are absolute pointers from the code in the oat to Methods
1124 // in the image.
1125 //
1126 // 4. There are absolute pointers from code in the oat to other code
1127 // in the oat.
1128 //
1129 // To get this all correct, we go through several steps.
1130 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001131 // 1. We prepare offsets for all data in the oat file and calculate
1132 // the oat data size and code size. During this stage, we also set
1133 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001134 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001135 // 2. We prepare offsets for the objects in the image and calculate
1136 // the image size.
1137 //
1138 // 3. We create the oat file. Originally this was just our own proprietary
1139 // file but now it is contained within an ELF dynamic object (aka an .so
1140 // file). Since we know the image size and oat data size and code size we
1141 // can prepare the ELF headers and we then know the ELF memory segment
1142 // layout and we can now resolve all references. The compiler provides
1143 // LinkerPatch information in each CompiledMethod and we resolve these,
1144 // using the layout information and image object locations provided by
1145 // image writer, as we're writing the method code.
1146 //
1147 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148 // will be loaded after itself. Originally when oat file was simply
1149 // memory mapped so we could predict where its contents were based
1150 // on the file size. Now that it is an ELF file, we need to inspect
1151 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001152 // where the oat header is located within.
1153 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001155 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001156 // load the .so at the desired location at runtime by offsetting the
1157 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001158 // TODO: Do this in step 3. We already know the layout there.
1159 //
1160 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1161 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001162
1163
1164 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1165 // ImageWriter, if necessary.
1166 bool CreateOatFile() {
1167 CHECK(key_value_store_.get() != nullptr);
1168
1169 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1170
1171 std::unique_ptr<OatWriter> oat_writer;
1172 {
1173 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1174 std::string image_file_location;
1175 uint32_t image_file_location_oat_checksum = 0;
1176 uintptr_t image_file_location_oat_data_begin = 0;
1177 int32_t image_patch_delta = 0;
1178 if (image_) {
1179 PrepareImageWriter(image_base_);
1180 } else {
1181 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1182 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1183 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1184 image_file_location_oat_data_begin =
1185 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1186 image_file_location = image_space->GetImageFilename();
1187 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1188 }
1189
1190 if (!image_file_location.empty()) {
1191 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1192 }
1193
1194 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1195 image_file_location_oat_data_begin,
1196 image_patch_delta,
1197 driver_.get(),
1198 image_writer_.get(),
1199 timings_,
1200 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001201 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001202
1203 if (image_) {
1204 // The OatWriter constructor has already updated offsets in methods and we need to
1205 // prepare method offsets in the image address space for direct method patching.
1206 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1207 if (!image_writer_->PrepareImageAddressSpace()) {
1208 LOG(ERROR) << "Failed to prepare image address space.";
1209 return false;
1210 }
1211 }
1212
1213 {
1214 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1215 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1216 oat_file_.get())) {
1217 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1218 return false;
1219 }
1220 }
1221
1222 // Flush result to disk.
1223 {
1224 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1225 if (oat_file_->Flush() != 0) {
1226 LOG(ERROR) << "Failed to flush ELF file " << oat_file_->GetPath();
1227 return false;
1228 }
1229 }
1230
1231 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1232 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001233 }
1234
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 // If we are compiling an image, invoke the image creation routine. Else just skip.
1236 bool HandleImage() {
1237 if (image_) {
1238 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1239 if (!CreateImageFile()) {
1240 return false;
1241 }
1242 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001243 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001244 return true;
1245 }
1246
1247 // Strip the oat file, if requested. This first creates a copy from unstripped to stripped, and
1248 // then runs the ElfStripper. Currently only relevant for the portable compiler.
1249 bool Strip() {
1250 // If we don't want to strip in place, copy from unstripped location to stripped location.
1251 // We need to strip after image creation because FixupElf needs to use .strtab.
1252 if (oat_unstripped_ != oat_stripped_) {
1253 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1254 oat_file_.reset();
1255 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1256 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1257 size_t buffer_size = 8192;
1258 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1259 while (true) {
1260 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1261 if (bytes_read <= 0) {
1262 break;
1263 }
1264 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1265 CHECK(write_ok);
1266 }
1267 oat_file_.reset(out.release());
1268 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001269 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001270
1271 if (kUsePortableCompiler) {
1272 // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1273 // strip them now. Quick generates debug symbols only when the flag(s) are set.
1274 if (!compiler_options_->GetIncludeDebugSymbols()) {
1275 TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1276 // Strip unneeded sections for target
1277 off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1278 CHECK_EQ(0, seek_actual);
1279 std::string error_msg;
1280 if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1281 LOG(ERROR) << "Failed to strip elf file: " << error_msg;
1282 return false;
1283 }
1284
1285 // We wrote the oat file successfully, and want to keep it.
1286 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1287 } else {
1288 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1289 }
1290 }
1291
1292 return true;
1293 }
1294
1295 void DumpTiming() {
1296 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1297 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1298 }
1299 if (dump_passes_) {
1300 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1301 }
1302 }
1303
1304 CompilerOptions* GetCompilerOptions() const {
1305 return compiler_options_.get();
1306 }
1307
1308 bool IsHost() const {
1309 return is_host_;
1310 }
1311
1312 private:
1313 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1314 const std::vector<const char*>& dex_locations,
1315 std::vector<const DexFile*>& dex_files) {
1316 size_t failure_count = 0;
1317 for (size_t i = 0; i < dex_filenames.size(); i++) {
1318 const char* dex_filename = dex_filenames[i];
1319 const char* dex_location = dex_locations[i];
1320 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1321 std::string error_msg;
1322 if (!OS::FileExists(dex_filename)) {
1323 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1324 continue;
1325 }
1326 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1327 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1328 ++failure_count;
1329 }
1330 ATRACE_END();
1331 }
1332 return failure_count;
1333 }
1334
1335 // Returns true if dex_files has a dex with the named location.
1336 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1337 const std::string& location) {
1338 for (size_t i = 0; i < dex_files.size(); ++i) {
1339 if (dex_files[i]->GetLocation() == location) {
1340 return true;
1341 }
1342 }
1343 return false;
1344 }
1345
1346 // Appends to dex_files any elements of class_path that it doesn't already
1347 // contain. This will open those dex files as necessary.
1348 static void OpenClassPathFiles(const std::string& class_path,
1349 std::vector<const DexFile*>& dex_files) {
1350 std::vector<std::string> parsed;
1351 Split(class_path, ':', &parsed);
1352 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1353 ScopedObjectAccess soa(Thread::Current());
1354 for (size_t i = 0; i < parsed.size(); ++i) {
1355 if (DexFilesContains(dex_files, parsed[i])) {
1356 continue;
1357 }
1358 std::string error_msg;
1359 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1360 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1361 }
1362 }
1363 }
1364
1365 // Create a runtime necessary for compilation.
1366 bool CreateRuntime(const RuntimeOptions& runtime_options)
1367 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1368 if (!Runtime::Create(runtime_options, false)) {
1369 LOG(ERROR) << "Failed to create runtime";
1370 return false;
1371 }
1372 Runtime* runtime = Runtime::Current();
1373 runtime->SetInstructionSet(instruction_set_);
1374 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1375 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1376 if (!runtime->HasCalleeSaveMethod(type)) {
1377 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1378 }
1379 }
1380 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1381 runtime->GetClassLinker()->RunRootClinits();
1382 runtime_ = runtime;
1383 return true;
1384 }
1385
1386 void PrepareImageWriter(uintptr_t image_base) {
1387 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1388 }
1389
1390 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1391 bool CreateImageFile()
1392 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1393 CHECK(image_writer_ != nullptr);
1394 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1395 LOG(ERROR) << "Failed to create image file " << image_filename_;
1396 return false;
1397 }
1398 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1399
1400 // Destroy ImageWriter before doing FixupElf.
1401 image_writer_.reset();
1402
1403 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1404 if (oat_file.get() == nullptr) {
1405 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1406 return false;
1407 }
1408
1409 // Do not fix up the ELF file if we are --compile-pic
1410 if (!compiler_options_->GetCompilePic()) {
1411 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
1412 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1413 return false;
1414 }
1415 }
1416
1417 return true;
1418 }
1419
1420 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1421 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1422 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1423 std::ifstream::in));
1424 if (image_classes_file.get() == nullptr) {
1425 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1426 return nullptr;
1427 }
1428 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1429 image_classes_file->close();
1430 return result.release();
1431 }
1432
1433 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1434 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1435 while (image_classes_stream.good()) {
1436 std::string dot;
1437 std::getline(image_classes_stream, dot);
1438 if (StartsWith(dot, "#") || dot.empty()) {
1439 continue;
1440 }
1441 std::string descriptor(DotToDescriptor(dot.c_str()));
1442 image_classes->insert(descriptor);
1443 }
1444 return image_classes.release();
1445 }
1446
1447 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1448 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1449 const char* image_classes_filename,
1450 std::string* error_msg) {
1451 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1452 if (zip_archive.get() == nullptr) {
1453 return nullptr;
1454 }
1455 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1456 if (zip_entry.get() == nullptr) {
1457 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1458 zip_filename, error_msg->c_str());
1459 return nullptr;
1460 }
1461 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1462 image_classes_filename,
1463 error_msg));
1464 if (image_classes_file.get() == nullptr) {
1465 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1466 zip_filename, error_msg->c_str());
1467 return nullptr;
1468 }
1469 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1470 image_classes_file->Size());
1471 std::istringstream image_classes_stream(image_classes_string);
1472 return ReadImageClasses(image_classes_stream);
1473 }
1474
1475 void LogCompletionTime() const {
1476 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
1477 << " (threads: " << thread_count_ << ")";
1478 }
1479
1480 std::unique_ptr<CompilerOptions> compiler_options_;
1481 Compiler::Kind compiler_kind_;
1482
1483 InstructionSet instruction_set_;
1484 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1485
1486 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1487
1488 std::unique_ptr<VerificationResults> verification_results_;
1489 DexFileToMethodInlinerMap method_inliner_map_;
1490 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1491
1492 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1493 // in an orderly fashion. The destructor takes care of deleting this.
1494 Runtime* runtime_;
1495
1496 size_t thread_count_;
1497 uint64_t start_ns_;
1498 std::unique_ptr<WatchDog> watchdog_;
1499 std::unique_ptr<File> oat_file_;
1500 std::string oat_stripped_;
1501 std::string oat_unstripped_;
1502 std::string oat_location_;
1503 std::string oat_filename_;
1504 int oat_fd_;
1505 std::string bitcode_filename_;
1506 std::vector<const char*> dex_filenames_;
1507 std::vector<const char*> dex_locations_;
1508 int zip_fd_;
1509 std::string zip_location_;
1510 std::string boot_image_option_;
1511 std::vector<const char*> runtime_args_;
1512 std::string image_filename_;
1513 uintptr_t image_base_;
1514 const char* image_classes_zip_filename_;
1515 const char* image_classes_filename_;
1516 std::unique_ptr<std::set<std::string>> image_classes_;
1517 bool image_;
1518 std::unique_ptr<ImageWriter> image_writer_;
1519 bool is_host_;
1520 std::string android_root_;
1521 std::vector<const DexFile*> dex_files_;
1522 std::unique_ptr<CompilerDriver> driver_;
1523 std::vector<std::string> verbose_methods_;
1524 bool dump_stats_;
1525 bool dump_passes_;
1526 bool dump_timing_;
1527 bool dump_slow_timing_;
1528 std::string profile_file_; // Profile file to use
1529 TimingLogger* timings_;
1530 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1531
1532 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1533};
1534
1535const unsigned int WatchDog::kWatchDogWarningSeconds;
1536const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1537
1538static void b13564922() {
1539#if defined(__linux__) && defined(__arm__)
1540 int major, minor;
1541 struct utsname uts;
1542 if (uname(&uts) != -1 &&
1543 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1544 ((major < 3) || ((major == 3) && (minor < 4)))) {
1545 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1546 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1547 int old_personality = personality(0xffffffff);
1548 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1549 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1550 if (new_personality == -1) {
1551 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1552 }
1553 }
1554 }
1555#endif
1556}
1557
1558static int dex2oat(int argc, char** argv) {
1559 b13564922();
1560
1561 TimingLogger timings("compiler", false, false);
1562
1563 Dex2Oat dex2oat(&timings);
1564
1565 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1566 dex2oat.ParseArgs(argc, argv);
1567
1568 // Check early that the result of compilation can be written
1569 if (!dex2oat.OpenFile()) {
1570 return EXIT_FAILURE;
1571 }
1572
1573 LOG(INFO) << CommandLine();
1574
1575 if (!dex2oat.Setup()) {
1576 return EXIT_FAILURE;
1577 }
1578
1579 dex2oat.Compile();
1580
1581 if (!dex2oat.CreateOatFile()) {
1582 return EXIT_FAILURE;
1583 }
1584
1585 if (!dex2oat.HandleImage()) {
1586 return EXIT_FAILURE;
1587 }
1588
1589 if (dex2oat.IsHost()) {
1590 dex2oat.DumpTiming();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001591 return EXIT_SUCCESS;
1592 }
1593
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001594 if (!dex2oat.Strip()) {
1595 return EXIT_FAILURE;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001596 }
1597
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001598 dex2oat.DumpTiming();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001599 return EXIT_SUCCESS;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001600}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001601} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602
1603int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001604 int result = art::dex2oat(argc, argv);
1605 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1606 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1607 // should not destruct the runtime in this case.
1608 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1609 exit(result);
1610 }
1611 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001612}