blob: 3be57516f9732968ddbb4f2e30b0e28d9df03a62 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
Vladimir Markof94b7812014-06-05 15:48:04 +010028#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
Ian Rogerscf7f1912014-10-22 22:06:39 -070033#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080034#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070035
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include "arch/instruction_set_features.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070037#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000043#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000044#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070046#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000047#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070048#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080051#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080052#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070053#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070058#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070068#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
Brian Carlstrom6449c622014-02-10 23:48:36 -080075static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79 std::vector<std::string> command;
80 for (int i = 0; i < original_argc; ++i) {
81 command.push_back(original_argv[i]);
82 }
83 return Join(command, ' ');
84}
85
Brian Carlstrom7940e442013-07-12 13:46:57 -070086static void UsageErrorV(const char* fmt, va_list ap) {
87 std::string error;
88 StringAppendV(&error, fmt, ap);
89 LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93 va_list ap;
94 va_start(ap, fmt);
95 UsageErrorV(fmt, ap);
96 va_end(ap);
97}
98
Ian Rogers7223d442014-10-10 20:05:39 -070099[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700100 va_list ap;
101 va_start(ap, fmt);
102 UsageErrorV(fmt, ap);
103 va_end(ap);
104
Brian Carlstrom6449c622014-02-10 23:48:36 -0800105 UsageError("Command: %s", CommandLine().c_str());
106
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 UsageError("Usage: dex2oat [options]...");
108 UsageError("");
109 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
110 UsageError(" Example: --dex-file=/system/framework/core.jar");
111 UsageError("");
112 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113 UsageError(" containing a classes.dex file to compile.");
114 UsageError(" Example: --zip-fd=5");
115 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700116 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
117 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
119 UsageError("");
120 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121 UsageError(" Example: --oat-file=/system/framework/boot.oat");
122 UsageError("");
123 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900124 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 UsageError("");
126 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127 UsageError(" to the file descriptor specified by --oat-fd.");
128 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129 UsageError("");
130 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
132 UsageError("");
133 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
134 UsageError(" Example: --bitcode=/system/framework/boot.bc");
135 UsageError("");
136 UsageError(" --image=<file.art>: specifies the output image filename.");
137 UsageError(" Example: --image=/system/framework/boot.art");
138 UsageError("");
139 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
140 UsageError(" Example: --image=frameworks/base/preloaded-classes");
141 UsageError("");
142 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
143 UsageError(" Example: --base=0x50000000");
144 UsageError("");
145 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
146 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000147 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 UsageError("");
149 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
150 UsageError(" Example: --android-root=out/host/linux-x86");
151 UsageError(" Default: $ANDROID_ROOT");
152 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700153 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
154 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700155 UsageError(" Example: --instruction-set=x86");
156 UsageError(" Default: arm");
157 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700158 UsageError(" --instruction-set-features=...,: Specify instruction set features");
159 UsageError(" Example: --instruction-set-features=div");
160 UsageError(" Default: default");
161 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700162 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
163 UsageError(" Default: disabled");
164 UsageError("");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000165 UsageError(" --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700167 UsageError(" Example: --compiler-backend=Portable");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 UsageError(" Default: Quick");
169 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100170 UsageError(" --compiler-filter="
171 "(verify-none"
172 "|interpret-only"
173 "|space"
174 "|balanced"
175 "|speed"
176 "|everything"
177 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700178 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800179 UsageError(" Example: --compiler-filter=everything");
180#if ART_SMALL_MODE
181 UsageError(" Default: interpret-only");
182#else
183 UsageError(" Default: speed");
184#endif
185 UsageError("");
186 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
187 UsageError(" method for compiler filter tuning.");
188 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
189 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
190 UsageError("");
191 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
192 UsageError(" method for compiler filter tuning.");
193 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError("");
196 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
197 UsageError(" method for compiler filter tuning.");
198 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
199 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
200 UsageError("");
201 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
202 UsageError(" method for compiler filter tuning.");
203 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
204 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
205 UsageError("");
206 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
207 UsageError(" method for compiler filter tuning.");
208 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
209 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
210 UsageError("");
211 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
212 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700213 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
214 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800215 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 UsageError(" --host: used with Portable backend to link against host runtime libraries");
219 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700220 UsageError(" --dump-timing: display a breakdown of where time was spent");
221 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700222 UsageError(" --include-patch-information: Include patching information so the generated code");
223 UsageError(" can have its base address moved without full recompilation.");
224 UsageError("");
225 UsageError(" --no-include-patch-information: Do not include patching information.");
226 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700227 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
228 UsageError("");
229 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
230 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
232 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
233 UsageError(" Use a separate --runtime-arg switch for each argument.");
234 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700235 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000236 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700238 UsageError(" --print-pass-names: print a list of pass names");
239 UsageError("");
240 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
241 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
242 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700243 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
244 "with the setting.");
245 UsageError(" Will print default if no overridden setting exists.");
246 UsageError("");
247 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
248 "Pass2Name:Pass2OptionName:Pass2Option#");
249 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
250 UsageError(" Separator used between options is a comma.");
251 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 std::cerr << "See log for usage error information\n";
253 exit(EXIT_FAILURE);
254}
255
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256// The primary goal of the watchdog is to prevent stuck build servers
257// during development when fatal aborts lead to a cascade of failures
258// that result in a deadlock.
259class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
261#undef CHECK_PTHREAD_CALL
262#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
263 do { \
264 int rc = call args; \
265 if (rc != 0) { \
266 errno = rc; \
267 std::string message(# call); \
268 message += " failed for "; \
269 message += reason; \
270 Fatal(message); \
271 } \
272 } while (false)
273
274 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700275 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276 is_watch_dog_enabled_ = is_watch_dog_enabled;
277 if (!is_watch_dog_enabled_) {
278 return;
279 }
280 shutting_down_ = false;
281 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700282 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
283 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700284 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
285 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
286 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
287 }
288 ~WatchDog() {
289 if (!is_watch_dog_enabled_) {
290 return;
291 }
292 const char* reason = "dex2oat watch dog thread shutdown";
293 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
294 shutting_down_ = true;
295 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
296 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
297
Kenny Root51316382014-05-13 14:59:37 -0700298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
302 }
303
304 private:
305 static void* CallBack(void* arg) {
306 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
307 ::art::SetThreadName("dex2oat watch dog");
308 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700309 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700310 }
311
312 static void Message(char severity, const std::string& message) {
313 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
314 // cases.
315 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
316 kIsDebugBuild ? "d" : "",
317 severity,
318 getpid(),
319 GetTid(),
320 message.c_str());
321 }
322
323 static void Warn(const std::string& message) {
324 Message('W', message);
325 }
326
Ian Rogers7223d442014-10-10 20:05:39 -0700327 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 Message('F', message);
329 exit(1);
330 }
331
332 void Wait() {
333 bool warning = true;
334 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
335 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
336 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800337 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 timespec warning_ts;
339 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
340 timespec timeout_ts;
341 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
342 const char* reason = "dex2oat watch dog thread waiting";
343 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
344 while (!shutting_down_) {
345 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
346 warning ? &warning_ts
347 : &timeout_ts));
348 if (rc == ETIMEDOUT) {
349 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
350 warning ? kWatchDogWarningSeconds
351 : kWatchDogTimeoutSeconds));
352 if (warning) {
353 Warn(message.c_str());
354 warning = false;
355 } else {
356 Fatal(message.c_str());
357 }
358 } else if (rc != 0) {
359 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
360 strerror(errno)));
361 Fatal(message.c_str());
362 }
363 }
364 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
365 }
366
367 // 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 -0700368 // Debug builds are slower so they have larger timeouts.
369 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800370
371 static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
372 kSlowdownFactor * 2 * 60 : // 2 minutes scaled by kSlowdownFactor (portable).
373 kSlowdownFactor * 1 * 60; // 1 minute scaled by kSlowdownFactor (not-portable).
374 static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
375 kSlowdownFactor * 30 * 60 : // 30 minutes scaled by kSlowdownFactor (portable).
376 kSlowdownFactor * 6 * 60; // 6 minutes scaled by kSlowdownFactor (not-portable).
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377
378 bool is_watch_dog_enabled_;
379 bool shutting_down_;
380 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
381 pthread_mutex_t mutex_;
382 pthread_cond_t cond_;
383 pthread_attr_t attr_;
384 pthread_t pthread_;
385};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800387static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100388 std::string::size_type colon = s.find(c);
389 if (colon == std::string::npos) {
390 Usage("Missing char %c in option %s\n", c, s.c_str());
391 }
392 // Add one to remove the char we were trimming until.
393 *parsed_value = s.substr(colon + 1);
394}
395
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800396static void ParseDouble(const std::string& option, char after_char, double min, double max,
397 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100398 std::string substring;
399 ParseStringAfterChar(option, after_char, &substring);
400 bool sane_val = true;
401 double value;
402 if (false) {
403 // TODO: this doesn't seem to work on the emulator. b/15114595
404 std::stringstream iss(substring);
405 iss >> value;
406 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
407 sane_val = iss.eof() && (value >= min) && (value <= max);
408 } else {
409 char* end = nullptr;
410 value = strtod(substring.c_str(), &end);
411 sane_val = *end == '\0' && value >= min && value <= max;
412 }
413 if (!sane_val) {
414 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
415 }
416 *parsed_value = value;
417}
418
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800419class Dex2Oat FINAL {
420 public:
421 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000422 compiler_kind_(kUsePortableCompiler
423 ? Compiler::kPortable
424 : (kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick)),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800425 instruction_set_(kRuntimeISA),
426 // Take the default set of instruction features from the build.
427 method_inliner_map_(),
428 runtime_(nullptr),
429 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
430 start_ns_(NanoTime()),
431 oat_fd_(-1),
432 zip_fd_(-1),
433 image_base_(0U),
434 image_classes_zip_filename_(nullptr),
435 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800436 compiled_classes_zip_filename_(nullptr),
437 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800438 image_(false),
439 is_host_(false),
440 dump_stats_(false),
441 dump_passes_(false),
442 dump_timing_(false),
443 dump_slow_timing_(kIsDebugBuild),
444 timings_(timings) {}
445
446 ~Dex2Oat() {
447 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
448 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100449 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800450 LogCompletionTime();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 }
452
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800453 // Parse the arguments from the command line. In case of an unrecognized option or impossible
454 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
455 // returns, arguments have been successfully parsed.
456 void ParseArgs(int argc, char** argv) {
457 original_argc = argc;
458 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700459
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800460 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700461
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800462 // Skip over argv[0].
463 argv++;
464 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700465
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800466 if (argc == 0) {
467 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700468 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469
470 std::string oat_symbols;
471 std::string boot_image_filename;
472 const char* compiler_filter_string = nullptr;
473 bool compile_pic = false;
474 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
475 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
476 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
477 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
478 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
479
480 // Profile file to use
481 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
482
483 bool print_pass_options = false;
484 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
485 bool include_debug_symbols = kIsDebugBuild;
486 bool watch_dog_enabled = true;
487 bool generate_gdb_information = kIsDebugBuild;
488
489 std::string error_msg;
490
491 for (int i = 0; i < argc; i++) {
492 const StringPiece option(argv[i]);
493 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700494 if (log_options) {
495 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
496 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800497 if (option.starts_with("--dex-file=")) {
498 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
499 } else if (option.starts_with("--dex-location=")) {
500 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
501 } else if (option.starts_with("--zip-fd=")) {
502 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
503 if (!ParseInt(zip_fd_str, &zip_fd_)) {
504 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
505 }
506 if (zip_fd_ < 0) {
507 Usage("--zip-fd passed a negative value %d", zip_fd_);
508 }
509 } else if (option.starts_with("--zip-location=")) {
510 zip_location_ = option.substr(strlen("--zip-location=")).data();
511 } else if (option.starts_with("--oat-file=")) {
512 oat_filename_ = option.substr(strlen("--oat-file=")).data();
513 } else if (option.starts_with("--oat-symbols=")) {
514 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
515 } else if (option.starts_with("--oat-fd=")) {
516 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
517 if (!ParseInt(oat_fd_str, &oat_fd_)) {
518 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
519 }
520 if (oat_fd_ < 0) {
521 Usage("--oat-fd passed a negative value %d", oat_fd_);
522 }
523 } else if (option == "--watch-dog") {
524 watch_dog_enabled = true;
525 } else if (option == "--no-watch-dog") {
526 watch_dog_enabled = false;
527 } else if (option == "--gen-gdb-info") {
528 generate_gdb_information = true;
529 // Debug symbols are needed for gdb information.
530 include_debug_symbols = true;
531 } else if (option == "--no-gen-gdb-info") {
532 generate_gdb_information = false;
533 } else if (option.starts_with("-j")) {
534 const char* thread_count_str = option.substr(strlen("-j")).data();
535 if (!ParseUint(thread_count_str, &thread_count_)) {
536 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
537 }
538 } else if (option.starts_with("--oat-location=")) {
539 oat_location_ = option.substr(strlen("--oat-location=")).data();
540 } else if (option.starts_with("--bitcode=")) {
541 bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
542 } else if (option.starts_with("--image=")) {
543 image_filename_ = option.substr(strlen("--image=")).data();
544 } else if (option.starts_with("--image-classes=")) {
545 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
546 } else if (option.starts_with("--image-classes-zip=")) {
547 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800548 } else if (option.starts_with("--compiled-classes=")) {
549 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
550 } else if (option.starts_with("--compiled-classes-zip=")) {
551 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800552 } else if (option.starts_with("--base=")) {
553 const char* image_base_str = option.substr(strlen("--base=")).data();
554 char* end;
555 image_base_ = strtoul(image_base_str, &end, 16);
556 if (end == image_base_str || *end != '\0') {
557 Usage("Failed to parse hexadecimal value for option %s", option.data());
558 }
559 } else if (option.starts_with("--boot-image=")) {
560 boot_image_filename = option.substr(strlen("--boot-image=")).data();
561 } else if (option.starts_with("--android-root=")) {
562 android_root_ = option.substr(strlen("--android-root=")).data();
563 } else if (option.starts_with("--instruction-set=")) {
564 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
565 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
566 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
567 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
568 buf.get()[instruction_set_str.length()] = 0;
569 instruction_set_ = GetInstructionSetFromString(buf.get());
570 // arm actually means thumb2.
571 if (instruction_set_ == InstructionSet::kArm) {
572 instruction_set_ = InstructionSet::kThumb2;
573 }
574 } else if (option.starts_with("--instruction-set-variant=")) {
575 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
576 instruction_set_features_.reset(
577 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
578 if (instruction_set_features_.get() == nullptr) {
579 Usage("%s", error_msg.c_str());
580 }
581 } else if (option.starts_with("--instruction-set-features=")) {
582 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800583 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800584 instruction_set_features_.reset(
585 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
586 if (instruction_set_features_.get() == nullptr) {
587 Usage("Problem initializing default instruction set features variant: %s",
588 error_msg.c_str());
589 }
590 }
591 instruction_set_features_.reset(
592 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
593 if (instruction_set_features_.get() == nullptr) {
594 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800595 }
596 } else if (option.starts_with("--compiler-backend=")) {
597 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
598 if (backend_str == "Quick") {
599 compiler_kind_ = Compiler::kQuick;
600 } else if (backend_str == "Optimizing") {
601 compiler_kind_ = Compiler::kOptimizing;
602 } else if (backend_str == "Portable") {
603 compiler_kind_ = Compiler::kPortable;
604 } else {
605 Usage("Unknown compiler backend: %s", backend_str.data());
606 }
607 } else if (option.starts_with("--compiler-filter=")) {
608 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
609 } else if (option == "--compile-pic") {
610 compile_pic = true;
611 } else if (option.starts_with("--huge-method-max=")) {
612 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
613 if (!ParseInt(threshold, &huge_method_threshold)) {
614 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
615 }
616 if (huge_method_threshold < 0) {
617 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
618 }
619 } else if (option.starts_with("--large-method-max=")) {
620 const char* threshold = option.substr(strlen("--large-method-max=")).data();
621 if (!ParseInt(threshold, &large_method_threshold)) {
622 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
623 }
624 if (large_method_threshold < 0) {
625 Usage("--large-method-max passed a negative value %s", large_method_threshold);
626 }
627 } else if (option.starts_with("--small-method-max=")) {
628 const char* threshold = option.substr(strlen("--small-method-max=")).data();
629 if (!ParseInt(threshold, &small_method_threshold)) {
630 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
631 }
632 if (small_method_threshold < 0) {
633 Usage("--small-method-max passed a negative value %s", small_method_threshold);
634 }
635 } else if (option.starts_with("--tiny-method-max=")) {
636 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
637 if (!ParseInt(threshold, &tiny_method_threshold)) {
638 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
639 }
640 if (tiny_method_threshold < 0) {
641 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
642 }
643 } else if (option.starts_with("--num-dex-methods=")) {
644 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
645 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
646 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
647 }
648 if (num_dex_methods_threshold < 0) {
649 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
650 }
651 } else if (option == "--host") {
652 is_host_ = true;
653 } else if (option == "--runtime-arg") {
654 if (++i >= argc) {
655 Usage("Missing required argument for --runtime-arg");
656 }
657 if (log_options) {
658 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
659 }
660 runtime_args_.push_back(argv[i]);
661 } else if (option == "--dump-timing") {
662 dump_timing_ = true;
663 } else if (option == "--dump-passes") {
664 dump_passes_ = true;
665 } else if (option == "--dump-stats") {
666 dump_stats_ = true;
667 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
668 include_debug_symbols = true;
669 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
670 include_debug_symbols = false;
671 generate_gdb_information = false; // Depends on debug symbols, see above.
672 } else if (option.starts_with("--profile-file=")) {
673 profile_file_ = option.substr(strlen("--profile-file=")).data();
674 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
675 } else if (option == "--no-profile-file") {
676 // No profile
677 } else if (option.starts_with("--top-k-profile-threshold=")) {
678 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
679 } else if (option == "--print-pass-names") {
680 PassDriverMEOpts::PrintPassNames();
681 } else if (option.starts_with("--disable-passes=")) {
682 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
683 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
684 } else if (option.starts_with("--print-passes=")) {
685 std::string print_passes = option.substr(strlen("--print-passes=")).data();
686 PassDriverMEOpts::SetPrintPassList(print_passes);
687 } else if (option == "--print-all-passes") {
688 PassDriverMEOpts::SetPrintAllPasses();
689 } else if (option.starts_with("--dump-cfg-passes=")) {
690 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
691 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
692 } else if (option == "--print-pass-options") {
693 print_pass_options = true;
694 } else if (option.starts_with("--pass-options=")) {
695 std::string options = option.substr(strlen("--pass-options=")).data();
696 PassDriverMEOpts::SetOverriddenPassOptions(options);
697 } else if (option == "--include-patch-information") {
698 include_patch_information = true;
699 } else if (option == "--no-include-patch-information") {
700 include_patch_information = false;
701 } else if (option.starts_with("--verbose-methods=")) {
702 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
703 // on having verbost methods.
704 gLogVerbosity.compiler = false;
705 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
706 } else {
707 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800709 }
710
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000711 if (compiler_kind_ == Compiler::kOptimizing) {
712 // Optimizing only supports PIC mode.
713 compile_pic = true;
714 }
715
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 if (oat_filename_.empty() && oat_fd_ == -1) {
717 Usage("Output must be supplied with either --oat-file or --oat-fd");
718 }
719
720 if (!oat_filename_.empty() && oat_fd_ != -1) {
721 Usage("--oat-file should not be used with --oat-fd");
722 }
723
724 if (!oat_symbols.empty() && oat_fd_ != -1) {
725 Usage("--oat-symbols should not be used with --oat-fd");
726 }
727
728 if (!oat_symbols.empty() && is_host_) {
729 Usage("--oat-symbols should not be used with --host");
730 }
731
732 if (oat_fd_ != -1 && !image_filename_.empty()) {
733 Usage("--oat-fd should not be used with --image");
734 }
735
736 if (android_root_.empty()) {
737 const char* android_root_env_var = getenv("ANDROID_ROOT");
738 if (android_root_env_var == nullptr) {
739 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800741 android_root_ += android_root_env_var;
742 }
743
744 image_ = (!image_filename_.empty());
745 if (!image_ && boot_image_filename.empty()) {
746 boot_image_filename += android_root_;
747 boot_image_filename += "/framework/boot.art";
748 }
749 if (!boot_image_filename.empty()) {
750 boot_image_option_ += "-Ximage:";
751 boot_image_option_ += boot_image_filename;
752 }
753
754 if (image_classes_filename_ != nullptr && !image_) {
755 Usage("--image-classes should only be used with --image");
756 }
757
758 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
759 Usage("--image-classes should not be used with --boot-image");
760 }
761
762 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
763 Usage("--image-classes-zip should be used with --image-classes");
764 }
765
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800766 if (compiled_classes_filename_ != nullptr && !image_) {
767 Usage("--compiled-classes should only be used with --image");
768 }
769
770 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
771 Usage("--compiled-classes should not be used with --boot-image");
772 }
773
774 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
775 Usage("--compiled-classes-zip should be used with --compiled-classes");
776 }
777
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800778 if (dex_filenames_.empty() && zip_fd_ == -1) {
779 Usage("Input must be supplied with either --dex-file or --zip-fd");
780 }
781
782 if (!dex_filenames_.empty() && zip_fd_ != -1) {
783 Usage("--dex-file should not be used with --zip-fd");
784 }
785
786 if (!dex_filenames_.empty() && !zip_location_.empty()) {
787 Usage("--dex-file should not be used with --zip-location");
788 }
789
790 if (dex_locations_.empty()) {
791 for (const char* dex_file_name : dex_filenames_) {
792 dex_locations_.push_back(dex_file_name);
793 }
794 } else if (dex_locations_.size() != dex_filenames_.size()) {
795 Usage("--dex-location arguments do not match --dex-file arguments");
796 }
797
798 if (zip_fd_ != -1 && zip_location_.empty()) {
799 Usage("--zip-location should be supplied with --zip-fd");
800 }
801
802 if (boot_image_option_.empty()) {
803 if (image_base_ == 0) {
804 Usage("Non-zero --base not specified");
805 }
806 }
807
808 oat_stripped_ = oat_filename_;
809 if (!oat_symbols.empty()) {
810 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700811 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800812 oat_unstripped_ = oat_filename_;
813 }
814
815 // If no instruction set feature was given, use the default one for the target
816 // instruction set.
817 if (instruction_set_features_.get() == nullptr) {
818 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800819 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
820 if (instruction_set_features_.get() == nullptr) {
821 Usage("Problem initializing default instruction set features variant: %s",
822 error_msg.c_str());
823 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800824 }
825
826 if (instruction_set_ == kRuntimeISA) {
827 std::unique_ptr<const InstructionSetFeatures> runtime_features(
828 InstructionSetFeatures::FromCppDefines());
829 if (!instruction_set_features_->Equals(runtime_features.get())) {
830 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
831 << *instruction_set_features_ << ") and those of dex2oat executable ("
832 << *runtime_features <<") for the command line:\n"
833 << CommandLine();
834 }
835 }
836
837 if (compiler_filter_string == nullptr) {
838 if (instruction_set_ == kMips64) {
839 // TODO: fix compiler for Mips64.
840 compiler_filter_string = "interpret-only";
841 } else if (image_) {
842 compiler_filter_string = "speed";
843 } else {
844 // TODO: Migrate SMALL mode to command line option.
845 #if ART_SMALL_MODE
846 compiler_filter_string = "interpret-only";
847 #else
848 compiler_filter_string = "speed";
849 #endif
850 }
851 }
852 CHECK(compiler_filter_string != nullptr);
853 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
854 if (strcmp(compiler_filter_string, "verify-none") == 0) {
855 compiler_filter = CompilerOptions::kVerifyNone;
856 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
857 compiler_filter = CompilerOptions::kInterpretOnly;
858 } else if (strcmp(compiler_filter_string, "space") == 0) {
859 compiler_filter = CompilerOptions::kSpace;
860 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
861 compiler_filter = CompilerOptions::kBalanced;
862 } else if (strcmp(compiler_filter_string, "speed") == 0) {
863 compiler_filter = CompilerOptions::kSpeed;
864 } else if (strcmp(compiler_filter_string, "everything") == 0) {
865 compiler_filter = CompilerOptions::kEverything;
866 } else if (strcmp(compiler_filter_string, "time") == 0) {
867 compiler_filter = CompilerOptions::kTime;
868 } else {
869 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
870 }
871
872 // Checks are all explicit until we know the architecture.
873 bool implicit_null_checks = false;
874 bool implicit_so_checks = false;
875 bool implicit_suspend_checks = false;
876 // Set the compilation target's implicit checks options.
877 switch (instruction_set_) {
878 case kArm:
879 case kThumb2:
880 case kArm64:
881 case kX86:
882 case kX86_64:
883 implicit_null_checks = true;
884 implicit_so_checks = true;
885 break;
886
887 default:
888 // Defaults are correct.
889 break;
890 }
891
892 if (print_pass_options) {
893 PassDriverMEOpts::PrintPassOptions();
894 }
895
896 compiler_options_.reset(new CompilerOptions(compiler_filter,
897 huge_method_threshold,
898 large_method_threshold,
899 small_method_threshold,
900 tiny_method_threshold,
901 num_dex_methods_threshold,
902 generate_gdb_information,
903 include_patch_information,
904 top_k_profile_threshold,
905 include_debug_symbols,
906 implicit_null_checks,
907 implicit_so_checks,
908 implicit_suspend_checks,
909 compile_pic,
910 #ifdef ART_SEA_IR_MODE
911 true,
912 #endif
913 verbose_methods_.empty() ?
914 nullptr :
915 &verbose_methods_));
916
917 // Done with usage checks, enable watchdog if requested
918 if (watch_dog_enabled) {
919 watchdog_.reset(new WatchDog(true));
920 }
921
922 // Fill some values into the key-value store for the oat header.
923 key_value_store_.reset(new SafeMap<std::string, std::string>());
924
925 // Insert some compiler things.
926 {
927 std::ostringstream oss;
928 for (int i = 0; i < argc; ++i) {
929 if (i > 0) {
930 oss << ' ';
931 }
932 oss << argv[i];
933 }
934 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
935 oss.str(""); // Reset.
936 oss << kRuntimeISA;
937 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
938 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
939 }
940 }
941
942 // Check whether the oat output file is writable, and open it for later.
943 bool OpenFile() {
944 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
945 if (create_file) {
946 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
947 if (oat_location_.empty()) {
948 oat_location_ = oat_filename_;
949 }
950 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800951 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800952 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800953 if (oat_file_->SetLength(0) != 0) {
954 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
955 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800956 }
957 if (oat_file_.get() == nullptr) {
958 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
959 return false;
960 }
961 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
962 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800963 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800964 return false;
965 }
966 return true;
967 }
968
969 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
970 // boot class path.
971 bool Setup() {
972 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
973 RuntimeOptions runtime_options;
974 std::vector<const DexFile*> boot_class_path;
975 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
976 if (boot_image_option_.empty()) {
977 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800978 if (failure_count > 0) {
979 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800980 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800981 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800982 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
983 } else {
984 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
985 }
986 for (size_t i = 0; i < runtime_args_.size(); i++) {
987 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988 }
Brian Carlstromd76e0832013-08-29 15:17:42 -0700989
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800990 verification_results_.reset(new VerificationResults(compiler_options_.get()));
991 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
992 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
993 runtime_options.push_back(
994 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
995
996 if (!CreateRuntime(runtime_options)) {
997 return false;
998 }
999
1000 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1001 // Runtime::Start, give it away now so that we don't starve GC.
1002 Thread* self = Thread::Current();
1003 self->TransitionFromRunnableToSuspended(kNative);
1004 // If we're doing the image, override the compiler filter to force full compilation. Must be
1005 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1006 // compilation of class initializers.
1007 // Whilst we're in native take the opportunity to initialize well known classes.
1008 WellKnownClasses::Init(self->GetJniEnv());
1009
1010 // If --image-classes was specified, calculate the full list of classes to include in the image
1011 if (image_classes_filename_ != nullptr) {
1012 std::string error_msg;
1013 if (image_classes_zip_filename_ != nullptr) {
1014 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1015 image_classes_filename_,
1016 &error_msg));
1017 } else {
1018 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1019 }
1020 if (image_classes_.get() == nullptr) {
1021 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1022 "': " << error_msg;
1023 return false;
1024 }
1025 } else if (image_) {
1026 image_classes_.reset(new std::set<std::string>);
1027 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001028 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1029 // image.
1030 if (compiled_classes_filename_ != nullptr) {
1031 std::string error_msg;
1032 if (compiled_classes_zip_filename_ != nullptr) {
1033 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1034 compiled_classes_filename_,
1035 &error_msg));
1036 } else {
1037 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1038 }
1039 if (compiled_classes_.get() == nullptr) {
1040 LOG(ERROR) << "Failed to create list of compiled classes from '"
1041 << compiled_classes_filename_ << "': " << error_msg;
1042 return false;
1043 }
1044 } else if (image_) {
1045 compiled_classes_.reset(nullptr); // By default compile everything.
1046 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001047
1048 if (boot_image_option_.empty()) {
1049 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1050 } else {
1051 if (dex_filenames_.empty()) {
1052 ATRACE_BEGIN("Opening zip archive from file descriptor");
1053 std::string error_msg;
1054 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1055 zip_location_.c_str(),
1056 &error_msg));
1057 if (zip_archive.get() == nullptr) {
1058 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1059 << error_msg;
1060 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001061 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001062 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1063 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1064 << "': " << error_msg;
1065 return false;
1066 }
1067 ATRACE_END();
1068 } else {
1069 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1070 if (failure_count > 0) {
1071 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1072 return false;
1073 }
1074 }
1075
1076 constexpr bool kSaveDexInput = false;
1077 if (kSaveDexInput) {
1078 for (size_t i = 0; i < dex_files_.size(); ++i) {
1079 const DexFile* dex_file = dex_files_[i];
1080 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1081 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1082 if (tmp_file.get() == nullptr) {
1083 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1084 << ". Try: adb shell chmod 777 /data/local/tmp";
1085 continue;
1086 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001087 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1088 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1089 UNUSED(tmp_file->Flush());
1090 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001091 LOG(INFO) << "Wrote input to " << tmp_file_name;
1092 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001093 }
1094 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001095 // Ensure opened dex files are writable for dex-to-dex transformations.
1096 for (const auto& dex_file : dex_files_) {
1097 if (!dex_file->EnableWrite()) {
1098 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001099 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001100 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001101
1102 /*
1103 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1104 * Don't bother to check if we're doing the image.
1105 */
1106 if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1107 size_t num_methods = 0;
1108 for (size_t i = 0; i != dex_files_.size(); ++i) {
1109 const DexFile* dex_file = dex_files_[i];
1110 CHECK(dex_file != nullptr);
1111 num_methods += dex_file->NumMethodIds();
1112 }
1113 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1114 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1115 VLOG(compiler) << "Below method threshold, compiling anyways";
1116 }
1117 }
1118
1119 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001120 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001121
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001122 // Create and invoke the compiler driver. This will compile all the dex files.
1123 void Compile() {
1124 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1125 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001126
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001127 // Handle and ClassLoader creation needs to come after Runtime::Create
1128 jobject class_loader = nullptr;
1129 Thread* self = Thread::Current();
1130 if (!boot_image_option_.empty()) {
1131 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1132 std::vector<const DexFile*> class_path_files(dex_files_);
1133 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1134 ScopedObjectAccess soa(self);
1135 for (size_t i = 0; i < class_path_files.size(); i++) {
1136 class_linker->RegisterDexFile(*class_path_files[i]);
1137 }
1138 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1139 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1140 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1141 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1142 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1143 }
1144
1145 driver_.reset(new CompilerDriver(compiler_options_.get(),
1146 verification_results_.get(),
1147 &method_inliner_map_,
1148 compiler_kind_,
1149 instruction_set_,
1150 instruction_set_features_.get(),
1151 image_,
1152 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001153 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001154 thread_count_,
1155 dump_stats_,
1156 dump_passes_,
1157 compiler_phases_timings_.get(),
1158 profile_file_));
1159
1160 driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1161
1162 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001163 }
1164
Brian Carlstrom7940e442013-07-12 13:46:57 -07001165 // Notes on the interleaving of creating the image and oat file to
1166 // ensure the references between the two are correct.
1167 //
1168 // Currently we have a memory layout that looks something like this:
1169 //
1170 // +--------------+
1171 // | image |
1172 // +--------------+
1173 // | boot oat |
1174 // +--------------+
1175 // | alloc spaces |
1176 // +--------------+
1177 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001178 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001179 //
1180 // 1. The image is expected to be loaded at an absolute address and
1181 // contains Objects with absolute pointers within the image.
1182 //
1183 // 2. There are absolute pointers from Methods in the image to their
1184 // code in the oat.
1185 //
1186 // 3. There are absolute pointers from the code in the oat to Methods
1187 // in the image.
1188 //
1189 // 4. There are absolute pointers from code in the oat to other code
1190 // in the oat.
1191 //
1192 // To get this all correct, we go through several steps.
1193 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001194 // 1. We prepare offsets for all data in the oat file and calculate
1195 // the oat data size and code size. During this stage, we also set
1196 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001198 // 2. We prepare offsets for the objects in the image and calculate
1199 // the image size.
1200 //
1201 // 3. We create the oat file. Originally this was just our own proprietary
1202 // file but now it is contained within an ELF dynamic object (aka an .so
1203 // file). Since we know the image size and oat data size and code size we
1204 // can prepare the ELF headers and we then know the ELF memory segment
1205 // layout and we can now resolve all references. The compiler provides
1206 // LinkerPatch information in each CompiledMethod and we resolve these,
1207 // using the layout information and image object locations provided by
1208 // image writer, as we're writing the method code.
1209 //
1210 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001211 // will be loaded after itself. Originally when oat file was simply
1212 // memory mapped so we could predict where its contents were based
1213 // on the file size. Now that it is an ELF file, we need to inspect
1214 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001215 // where the oat header is located within.
1216 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001217 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001218 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001219 // load the .so at the desired location at runtime by offsetting the
1220 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001221 // TODO: Do this in step 3. We already know the layout there.
1222 //
1223 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1224 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001225
1226
1227 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1228 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001229 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1230 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001231 bool CreateOatFile() {
1232 CHECK(key_value_store_.get() != nullptr);
1233
1234 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1235
1236 std::unique_ptr<OatWriter> oat_writer;
1237 {
1238 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1239 std::string image_file_location;
1240 uint32_t image_file_location_oat_checksum = 0;
1241 uintptr_t image_file_location_oat_data_begin = 0;
1242 int32_t image_patch_delta = 0;
1243 if (image_) {
1244 PrepareImageWriter(image_base_);
1245 } else {
1246 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1247 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1248 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1249 image_file_location_oat_data_begin =
1250 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1251 image_file_location = image_space->GetImageFilename();
1252 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1253 }
1254
1255 if (!image_file_location.empty()) {
1256 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1257 }
1258
1259 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1260 image_file_location_oat_data_begin,
1261 image_patch_delta,
1262 driver_.get(),
1263 image_writer_.get(),
1264 timings_,
1265 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001266 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001267
1268 if (image_) {
1269 // The OatWriter constructor has already updated offsets in methods and we need to
1270 // prepare method offsets in the image address space for direct method patching.
1271 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1272 if (!image_writer_->PrepareImageAddressSpace()) {
1273 LOG(ERROR) << "Failed to prepare image address space.";
1274 return false;
1275 }
1276 }
1277
1278 {
1279 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1280 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1281 oat_file_.get())) {
1282 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001283 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001284 return false;
1285 }
1286 }
1287
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001288 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1289 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001290 }
1291
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001292 // If we are compiling an image, invoke the image creation routine. Else just skip.
1293 bool HandleImage() {
1294 if (image_) {
1295 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1296 if (!CreateImageFile()) {
1297 return false;
1298 }
1299 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001300 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001301 return true;
1302 }
1303
Andreas Gampe10e477d2014-11-19 12:57:42 -08001304 // Create a copy from unstripped to stripped.
1305 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001306 // If we don't want to strip in place, copy from unstripped location to stripped location.
1307 // We need to strip after image creation because FixupElf needs to use .strtab.
1308 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001309 // If the oat file is still open, flush it.
1310 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1311 if (!FlushCloseOatFile()) {
1312 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001313 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001314 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001315
1316 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001317 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1318 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1319 size_t buffer_size = 8192;
1320 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1321 while (true) {
1322 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1323 if (bytes_read <= 0) {
1324 break;
1325 }
1326 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1327 CHECK(write_ok);
1328 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001329 if (kUsePortableCompiler) {
1330 oat_file_.reset(out.release());
1331 } else {
1332 if (out->FlushCloseOrErase() != 0) {
1333 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1334 return false;
1335 }
1336 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001337 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001338 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001339 return true;
1340 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001341
Andreas Gampe10e477d2014-11-19 12:57:42 -08001342 // Run the ElfStripper. Currently only relevant for the portable compiler.
1343 bool Strip() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001344 if (kUsePortableCompiler) {
1345 // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1346 // strip them now. Quick generates debug symbols only when the flag(s) are set.
1347 if (!compiler_options_->GetIncludeDebugSymbols()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001348 CHECK(oat_file_.get() != nullptr && oat_file_->IsOpened());
1349
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001350 TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1351 // Strip unneeded sections for target
1352 off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1353 CHECK_EQ(0, seek_actual);
1354 std::string error_msg;
1355 if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1356 LOG(ERROR) << "Failed to strip elf file: " << error_msg;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001357 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001358 return false;
1359 }
1360
Andreas Gampe10e477d2014-11-19 12:57:42 -08001361 if (!FlushCloseOatFile()) {
1362 return false;
1363 }
1364
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 // We wrote the oat file successfully, and want to keep it.
1366 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1367 } else {
1368 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1369 }
1370 }
1371
Andreas Gampe10e477d2014-11-19 12:57:42 -08001372 return true;
1373 }
1374
1375 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001376 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001377 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1378 if (oat_file_->Flush() != 0) {
1379 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1380 << oat_filename_;
1381 oat_file_->Erase();
1382 return false;
1383 }
1384 }
1385 return true;
1386 }
1387
1388 bool FlushCloseOatFile() {
1389 if (oat_file_.get() != nullptr) {
1390 std::unique_ptr<File> tmp(oat_file_.release());
1391 if (tmp->FlushCloseOrErase() != 0) {
1392 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1393 << oat_filename_;
1394 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001395 }
1396 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001397 return true;
1398 }
1399
1400 void DumpTiming() {
1401 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1402 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1403 }
1404 if (dump_passes_) {
1405 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1406 }
1407 }
1408
1409 CompilerOptions* GetCompilerOptions() const {
1410 return compiler_options_.get();
1411 }
1412
Andreas Gampe10e477d2014-11-19 12:57:42 -08001413 bool IsImage() const {
1414 return image_;
1415 }
1416
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001417 bool IsHost() const {
1418 return is_host_;
1419 }
1420
1421 private:
1422 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1423 const std::vector<const char*>& dex_locations,
1424 std::vector<const DexFile*>& dex_files) {
1425 size_t failure_count = 0;
1426 for (size_t i = 0; i < dex_filenames.size(); i++) {
1427 const char* dex_filename = dex_filenames[i];
1428 const char* dex_location = dex_locations[i];
1429 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1430 std::string error_msg;
1431 if (!OS::FileExists(dex_filename)) {
1432 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1433 continue;
1434 }
1435 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1436 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1437 ++failure_count;
1438 }
1439 ATRACE_END();
1440 }
1441 return failure_count;
1442 }
1443
1444 // Returns true if dex_files has a dex with the named location.
1445 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1446 const std::string& location) {
1447 for (size_t i = 0; i < dex_files.size(); ++i) {
1448 if (dex_files[i]->GetLocation() == location) {
1449 return true;
1450 }
1451 }
1452 return false;
1453 }
1454
1455 // Appends to dex_files any elements of class_path that it doesn't already
1456 // contain. This will open those dex files as necessary.
1457 static void OpenClassPathFiles(const std::string& class_path,
1458 std::vector<const DexFile*>& dex_files) {
1459 std::vector<std::string> parsed;
1460 Split(class_path, ':', &parsed);
1461 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1462 ScopedObjectAccess soa(Thread::Current());
1463 for (size_t i = 0; i < parsed.size(); ++i) {
1464 if (DexFilesContains(dex_files, parsed[i])) {
1465 continue;
1466 }
1467 std::string error_msg;
1468 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1469 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1470 }
1471 }
1472 }
1473
1474 // Create a runtime necessary for compilation.
1475 bool CreateRuntime(const RuntimeOptions& runtime_options)
1476 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1477 if (!Runtime::Create(runtime_options, false)) {
1478 LOG(ERROR) << "Failed to create runtime";
1479 return false;
1480 }
1481 Runtime* runtime = Runtime::Current();
1482 runtime->SetInstructionSet(instruction_set_);
1483 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1484 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1485 if (!runtime->HasCalleeSaveMethod(type)) {
1486 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1487 }
1488 }
1489 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1490 runtime->GetClassLinker()->RunRootClinits();
1491 runtime_ = runtime;
1492 return true;
1493 }
1494
1495 void PrepareImageWriter(uintptr_t image_base) {
1496 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1497 }
1498
1499 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1500 bool CreateImageFile()
1501 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1502 CHECK(image_writer_ != nullptr);
1503 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1504 LOG(ERROR) << "Failed to create image file " << image_filename_;
1505 return false;
1506 }
1507 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1508
1509 // Destroy ImageWriter before doing FixupElf.
1510 image_writer_.reset();
1511
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001512 // Do not fix up the ELF file if we are --compile-pic
1513 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001514 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1515 if (oat_file.get() == nullptr) {
1516 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1517 return false;
1518 }
1519
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001520 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001521 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001522 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1523 return false;
1524 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001525
1526 if (oat_file->FlushCloseOrErase()) {
1527 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1528 return false;
1529 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001530 }
1531
1532 return true;
1533 }
1534
1535 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1536 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1537 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1538 std::ifstream::in));
1539 if (image_classes_file.get() == nullptr) {
1540 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1541 return nullptr;
1542 }
1543 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1544 image_classes_file->close();
1545 return result.release();
1546 }
1547
1548 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1549 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1550 while (image_classes_stream.good()) {
1551 std::string dot;
1552 std::getline(image_classes_stream, dot);
1553 if (StartsWith(dot, "#") || dot.empty()) {
1554 continue;
1555 }
1556 std::string descriptor(DotToDescriptor(dot.c_str()));
1557 image_classes->insert(descriptor);
1558 }
1559 return image_classes.release();
1560 }
1561
1562 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1563 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1564 const char* image_classes_filename,
1565 std::string* error_msg) {
1566 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1567 if (zip_archive.get() == nullptr) {
1568 return nullptr;
1569 }
1570 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1571 if (zip_entry.get() == nullptr) {
1572 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1573 zip_filename, error_msg->c_str());
1574 return nullptr;
1575 }
1576 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1577 image_classes_filename,
1578 error_msg));
1579 if (image_classes_file.get() == nullptr) {
1580 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1581 zip_filename, error_msg->c_str());
1582 return nullptr;
1583 }
1584 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1585 image_classes_file->Size());
1586 std::istringstream image_classes_stream(image_classes_string);
1587 return ReadImageClasses(image_classes_stream);
1588 }
1589
1590 void LogCompletionTime() const {
1591 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
1592 << " (threads: " << thread_count_ << ")";
1593 }
1594
1595 std::unique_ptr<CompilerOptions> compiler_options_;
1596 Compiler::Kind compiler_kind_;
1597
1598 InstructionSet instruction_set_;
1599 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1600
1601 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1602
1603 std::unique_ptr<VerificationResults> verification_results_;
1604 DexFileToMethodInlinerMap method_inliner_map_;
1605 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1606
1607 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1608 // in an orderly fashion. The destructor takes care of deleting this.
1609 Runtime* runtime_;
1610
1611 size_t thread_count_;
1612 uint64_t start_ns_;
1613 std::unique_ptr<WatchDog> watchdog_;
1614 std::unique_ptr<File> oat_file_;
1615 std::string oat_stripped_;
1616 std::string oat_unstripped_;
1617 std::string oat_location_;
1618 std::string oat_filename_;
1619 int oat_fd_;
1620 std::string bitcode_filename_;
1621 std::vector<const char*> dex_filenames_;
1622 std::vector<const char*> dex_locations_;
1623 int zip_fd_;
1624 std::string zip_location_;
1625 std::string boot_image_option_;
1626 std::vector<const char*> runtime_args_;
1627 std::string image_filename_;
1628 uintptr_t image_base_;
1629 const char* image_classes_zip_filename_;
1630 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001631 const char* compiled_classes_zip_filename_;
1632 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001634 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001635 bool image_;
1636 std::unique_ptr<ImageWriter> image_writer_;
1637 bool is_host_;
1638 std::string android_root_;
1639 std::vector<const DexFile*> dex_files_;
1640 std::unique_ptr<CompilerDriver> driver_;
1641 std::vector<std::string> verbose_methods_;
1642 bool dump_stats_;
1643 bool dump_passes_;
1644 bool dump_timing_;
1645 bool dump_slow_timing_;
1646 std::string profile_file_; // Profile file to use
1647 TimingLogger* timings_;
1648 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1649
1650 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1651};
1652
1653const unsigned int WatchDog::kWatchDogWarningSeconds;
1654const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1655
1656static void b13564922() {
1657#if defined(__linux__) && defined(__arm__)
1658 int major, minor;
1659 struct utsname uts;
1660 if (uname(&uts) != -1 &&
1661 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1662 ((major < 3) || ((major == 3) && (minor < 4)))) {
1663 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1664 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1665 int old_personality = personality(0xffffffff);
1666 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1667 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1668 if (new_personality == -1) {
1669 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1670 }
1671 }
1672 }
1673#endif
1674}
1675
Andreas Gampe10e477d2014-11-19 12:57:42 -08001676static int CompileImage(Dex2Oat& dex2oat) {
1677 dex2oat.Compile();
1678
1679 // Create the boot.oat.
1680 if (!dex2oat.CreateOatFile()) {
1681 return EXIT_FAILURE;
1682 }
1683
1684 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1685 // re-opened from the unstripped name.
1686 if (!dex2oat.FlushCloseOatFile()) {
1687 return EXIT_FAILURE;
1688 }
1689
1690 // Creates the boot.art and patches the boot.oat.
1691 if (!dex2oat.HandleImage()) {
1692 return EXIT_FAILURE;
1693 }
1694
1695 // When given --host, finish early without stripping.
1696 if (dex2oat.IsHost()) {
1697 dex2oat.DumpTiming();
1698 return EXIT_SUCCESS;
1699 }
1700
1701 // Copy unstripped to stripped location, if necessary.
1702 if (!dex2oat.CopyUnstrippedToStripped()) {
1703 return EXIT_FAILURE;
1704 }
1705
1706 // Strip, if necessary.
1707 if (!dex2oat.Strip()) {
1708 return EXIT_FAILURE;
1709 }
1710
1711 // FlushClose again, as stripping might have re-opened the oat file.
1712 if (!dex2oat.FlushCloseOatFile()) {
1713 return EXIT_FAILURE;
1714 }
1715
1716 dex2oat.DumpTiming();
1717 return EXIT_SUCCESS;
1718}
1719
1720static int CompileApp(Dex2Oat& dex2oat) {
1721 dex2oat.Compile();
1722
1723 // Create the app oat.
1724 if (!dex2oat.CreateOatFile()) {
1725 return EXIT_FAILURE;
1726 }
1727
1728 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1729 // which we would lose.
1730 if (!dex2oat.FlushOatFile()) {
1731 return EXIT_FAILURE;
1732 }
1733
1734 // When given --host, finish early without stripping.
1735 if (dex2oat.IsHost()) {
1736 if (!dex2oat.FlushCloseOatFile()) {
1737 return EXIT_FAILURE;
1738 }
1739
1740 dex2oat.DumpTiming();
1741 return EXIT_SUCCESS;
1742 }
1743
1744 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1745 // unstripped version. If this is given, we expect to be able to open writable files by name.
1746 if (!dex2oat.CopyUnstrippedToStripped()) {
1747 return EXIT_FAILURE;
1748 }
1749
1750 // Strip, if necessary.
1751 if (!dex2oat.Strip()) {
1752 return EXIT_FAILURE;
1753 }
1754
1755 // Flush and close the file.
1756 if (!dex2oat.FlushCloseOatFile()) {
1757 return EXIT_FAILURE;
1758 }
1759
1760 dex2oat.DumpTiming();
1761 return EXIT_SUCCESS;
1762}
1763
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001764static int dex2oat(int argc, char** argv) {
1765 b13564922();
1766
1767 TimingLogger timings("compiler", false, false);
1768
1769 Dex2Oat dex2oat(&timings);
1770
1771 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1772 dex2oat.ParseArgs(argc, argv);
1773
1774 // Check early that the result of compilation can be written
1775 if (!dex2oat.OpenFile()) {
1776 return EXIT_FAILURE;
1777 }
1778
1779 LOG(INFO) << CommandLine();
1780
1781 if (!dex2oat.Setup()) {
1782 return EXIT_FAILURE;
1783 }
1784
Andreas Gampe10e477d2014-11-19 12:57:42 -08001785 if (dex2oat.IsImage()) {
1786 return CompileImage(dex2oat);
1787 } else {
1788 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001789 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001790}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001791} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001792
1793int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001794 int result = art::dex2oat(argc, argv);
1795 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1796 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1797 // should not destruct the runtime in this case.
1798 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1799 exit(result);
1800 }
1801 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001802}