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