blob: 25d6db16b4bdfc7a2d8f6521b2ed8cf3262daac5 [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
Mathieu Chartiere3a650a2014-12-02 18:23:21 -080028#ifndef __APPLE__
29#include <malloc.h> // For mallinfo
30#endif
31
Vladimir Markof94b7812014-06-05 15:48:04 +010032#if defined(__linux__) && defined(__arm__)
33#include <sys/personality.h>
34#include <sys/utsname.h>
35#endif
36
Ian Rogerscf7f1912014-10-22 22:06:39 -070037#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080038#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070039
Ian Rogersd582fa42014-11-05 23:46:43 -080040#include "arch/instruction_set_features.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "base/stl_util.h"
43#include "base/stringpiece.h"
44#include "base/timing_logger.h"
45#include "base/unix_file/fd_file.h"
46#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000047#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000048#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070050#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000051#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "dex/quick_compiler_callbacks.h"
53#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080055#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080056#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070057#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "gc/space/image_space.h"
59#include "gc/space/space-inl.h"
60#include "image_writer.h"
61#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070062#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/class-inl.h"
64#include "mirror/class_loader.h"
65#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
67#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "os.h"
69#include "runtime.h"
70#include "ScopedLocalRef.h"
71#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070072#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "vector_output_stream.h"
74#include "well_known_classes.h"
75#include "zip_archive.h"
76
77namespace art {
78
Brian Carlstrom6449c622014-02-10 23:48:36 -080079static int original_argc;
80static char** original_argv;
81
82static std::string CommandLine() {
83 std::vector<std::string> command;
84 for (int i = 0; i < original_argc; ++i) {
85 command.push_back(original_argv[i]);
86 }
87 return Join(command, ' ');
88}
89
Brian Carlstrom7940e442013-07-12 13:46:57 -070090static void UsageErrorV(const char* fmt, va_list ap) {
91 std::string error;
92 StringAppendV(&error, fmt, ap);
93 LOG(ERROR) << error;
94}
95
96static void UsageError(const char* fmt, ...) {
97 va_list ap;
98 va_start(ap, fmt);
99 UsageErrorV(fmt, ap);
100 va_end(ap);
101}
102
Ian Rogers7223d442014-10-10 20:05:39 -0700103[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700104 va_list ap;
105 va_start(ap, fmt);
106 UsageErrorV(fmt, ap);
107 va_end(ap);
108
Brian Carlstrom6449c622014-02-10 23:48:36 -0800109 UsageError("Command: %s", CommandLine().c_str());
110
Brian Carlstrom7940e442013-07-12 13:46:57 -0700111 UsageError("Usage: dex2oat [options]...");
112 UsageError("");
113 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
114 UsageError(" Example: --dex-file=/system/framework/core.jar");
115 UsageError("");
116 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
117 UsageError(" containing a classes.dex file to compile.");
118 UsageError(" Example: --zip-fd=5");
119 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700120 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
121 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700122 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
123 UsageError("");
124 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
125 UsageError(" Example: --oat-file=/system/framework/boot.oat");
126 UsageError("");
127 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900128 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129 UsageError("");
130 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
131 UsageError(" to the file descriptor specified by --oat-fd.");
132 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
133 UsageError("");
134 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
135 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
136 UsageError("");
137 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
138 UsageError(" Example: --bitcode=/system/framework/boot.bc");
139 UsageError("");
140 UsageError(" --image=<file.art>: specifies the output image filename.");
141 UsageError(" Example: --image=/system/framework/boot.art");
142 UsageError("");
143 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
144 UsageError(" Example: --image=frameworks/base/preloaded-classes");
145 UsageError("");
146 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
147 UsageError(" Example: --base=0x50000000");
148 UsageError("");
149 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
150 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000151 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 UsageError("");
153 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
154 UsageError(" Example: --android-root=out/host/linux-x86");
155 UsageError(" Default: $ANDROID_ROOT");
156 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700157 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
158 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159 UsageError(" Example: --instruction-set=x86");
160 UsageError(" Default: arm");
161 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700162 UsageError(" --instruction-set-features=...,: Specify instruction set features");
163 UsageError(" Example: --instruction-set-features=div");
164 UsageError(" Default: default");
165 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700166 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
167 UsageError(" Default: disabled");
168 UsageError("");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000169 UsageError(" --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700171 UsageError(" Example: --compiler-backend=Portable");
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000172 if (kUsePortableCompiler) {
173 UsageError(" Default: Portable");
174 } else if (kUseOptimizingCompiler) {
175 UsageError(" Default: Optimizing");
176 } else {
177 UsageError(" Default: Quick");
178 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100180 UsageError(" --compiler-filter="
181 "(verify-none"
182 "|interpret-only"
183 "|space"
184 "|balanced"
185 "|speed"
186 "|everything"
187 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700188 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800189 UsageError(" Example: --compiler-filter=everything");
190#if ART_SMALL_MODE
191 UsageError(" Default: interpret-only");
192#else
193 UsageError(" Default: speed");
194#endif
195 UsageError("");
196 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
197 UsageError(" method for compiler filter tuning.");
198 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
199 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
200 UsageError("");
201 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
202 UsageError(" method for compiler filter tuning.");
203 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
204 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
205 UsageError("");
206 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
207 UsageError(" method for compiler filter tuning.");
208 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
209 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
210 UsageError("");
211 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
212 UsageError(" method for compiler filter tuning.");
213 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
214 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
215 UsageError("");
216 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
217 UsageError(" method for compiler filter tuning.");
218 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
219 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
220 UsageError("");
221 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
222 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700223 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
224 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800225 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
226 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
227 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError(" --host: used with Portable backend to link against host runtime libraries");
229 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700230 UsageError(" --dump-timing: display a breakdown of where time was spent");
231 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700232 UsageError(" --include-patch-information: Include patching information so the generated code");
233 UsageError(" can have its base address moved without full recompilation.");
234 UsageError("");
235 UsageError(" --no-include-patch-information: Do not include patching information.");
236 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700237 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
238 UsageError("");
239 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
240 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
242 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
243 UsageError(" Use a separate --runtime-arg switch for each argument.");
244 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700245 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000246 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700248 UsageError(" --print-pass-names: print a list of pass names");
249 UsageError("");
250 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
251 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
252 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700253 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
254 "with the setting.");
255 UsageError(" Will print default if no overridden setting exists.");
256 UsageError("");
257 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
258 "Pass2Name:Pass2OptionName:Pass2Option#");
259 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
260 UsageError(" Separator used between options is a comma.");
261 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 std::cerr << "See log for usage error information\n";
263 exit(EXIT_FAILURE);
264}
265
Brian Carlstrom7940e442013-07-12 13:46:57 -0700266// The primary goal of the watchdog is to prevent stuck build servers
267// during development when fatal aborts lead to a cascade of failures
268// that result in a deadlock.
269class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
271#undef CHECK_PTHREAD_CALL
272#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
273 do { \
274 int rc = call args; \
275 if (rc != 0) { \
276 errno = rc; \
277 std::string message(# call); \
278 message += " failed for "; \
279 message += reason; \
280 Fatal(message); \
281 } \
282 } while (false)
283
284 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700285 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700286 is_watch_dog_enabled_ = is_watch_dog_enabled;
287 if (!is_watch_dog_enabled_) {
288 return;
289 }
290 shutting_down_ = false;
291 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
293 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700294 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
295 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
296 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
297 }
298 ~WatchDog() {
299 if (!is_watch_dog_enabled_) {
300 return;
301 }
302 const char* reason = "dex2oat watch dog thread shutdown";
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
304 shutting_down_ = true;
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
306 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
307
Kenny Root51316382014-05-13 14:59:37 -0700308 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700309
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
311 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
312 }
313
314 private:
315 static void* CallBack(void* arg) {
316 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
317 ::art::SetThreadName("dex2oat watch dog");
318 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700319 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320 }
321
322 static void Message(char severity, const std::string& message) {
323 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
324 // cases.
325 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
326 kIsDebugBuild ? "d" : "",
327 severity,
328 getpid(),
329 GetTid(),
330 message.c_str());
331 }
332
333 static void Warn(const std::string& message) {
334 Message('W', message);
335 }
336
Ian Rogers7223d442014-10-10 20:05:39 -0700337 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 Message('F', message);
339 exit(1);
340 }
341
342 void Wait() {
343 bool warning = true;
344 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
345 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
346 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800347 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 timespec warning_ts;
349 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
350 timespec timeout_ts;
351 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
352 const char* reason = "dex2oat watch dog thread waiting";
353 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
354 while (!shutting_down_) {
355 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
356 warning ? &warning_ts
357 : &timeout_ts));
358 if (rc == ETIMEDOUT) {
359 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
360 warning ? kWatchDogWarningSeconds
361 : kWatchDogTimeoutSeconds));
362 if (warning) {
363 Warn(message.c_str());
364 warning = false;
365 } else {
366 Fatal(message.c_str());
367 }
368 } else if (rc != 0) {
369 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
370 strerror(errno)));
371 Fatal(message.c_str());
372 }
373 }
374 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
375 }
376
377 // 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 -0700378 // Debug builds are slower so they have larger timeouts.
379 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800380
381 static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
382 kSlowdownFactor * 2 * 60 : // 2 minutes scaled by kSlowdownFactor (portable).
383 kSlowdownFactor * 1 * 60; // 1 minute scaled by kSlowdownFactor (not-portable).
384 static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
385 kSlowdownFactor * 30 * 60 : // 30 minutes scaled by kSlowdownFactor (portable).
386 kSlowdownFactor * 6 * 60; // 6 minutes scaled by kSlowdownFactor (not-portable).
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387
388 bool is_watch_dog_enabled_;
389 bool shutting_down_;
390 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
391 pthread_mutex_t mutex_;
392 pthread_cond_t cond_;
393 pthread_attr_t attr_;
394 pthread_t pthread_;
395};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800397static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100398 std::string::size_type colon = s.find(c);
399 if (colon == std::string::npos) {
400 Usage("Missing char %c in option %s\n", c, s.c_str());
401 }
402 // Add one to remove the char we were trimming until.
403 *parsed_value = s.substr(colon + 1);
404}
405
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800406static void ParseDouble(const std::string& option, char after_char, double min, double max,
407 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100408 std::string substring;
409 ParseStringAfterChar(option, after_char, &substring);
410 bool sane_val = true;
411 double value;
412 if (false) {
413 // TODO: this doesn't seem to work on the emulator. b/15114595
414 std::stringstream iss(substring);
415 iss >> value;
416 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
417 sane_val = iss.eof() && (value >= min) && (value <= max);
418 } else {
419 char* end = nullptr;
420 value = strtod(substring.c_str(), &end);
421 sane_val = *end == '\0' && value >= min && value <= max;
422 }
423 if (!sane_val) {
424 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
425 }
426 *parsed_value = value;
427}
428
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800429class Dex2Oat FINAL {
430 public:
431 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000432 compiler_kind_(kUsePortableCompiler
433 ? Compiler::kPortable
434 : (kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick)),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800435 instruction_set_(kRuntimeISA),
436 // Take the default set of instruction features from the build.
437 method_inliner_map_(),
438 runtime_(nullptr),
439 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
440 start_ns_(NanoTime()),
441 oat_fd_(-1),
442 zip_fd_(-1),
443 image_base_(0U),
444 image_classes_zip_filename_(nullptr),
445 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800446 compiled_classes_zip_filename_(nullptr),
447 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800448 image_(false),
449 is_host_(false),
450 dump_stats_(false),
451 dump_passes_(false),
452 dump_timing_(false),
453 dump_slow_timing_(kIsDebugBuild),
454 timings_(timings) {}
455
456 ~Dex2Oat() {
Mathieu Chartier49285c52014-12-02 15:43:48 -0800457 LogCompletionTime(); // Needs to be before since it accesses the runtime.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800458 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
459 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100460 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 }
462
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800463 // Parse the arguments from the command line. In case of an unrecognized option or impossible
464 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
465 // returns, arguments have been successfully parsed.
466 void ParseArgs(int argc, char** argv) {
467 original_argc = argc;
468 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700469
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800470 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700471
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472 // Skip over argv[0].
473 argv++;
474 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700475
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476 if (argc == 0) {
477 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700478 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800479
480 std::string oat_symbols;
481 std::string boot_image_filename;
482 const char* compiler_filter_string = nullptr;
483 bool compile_pic = false;
484 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
485 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
486 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
487 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
488 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
489
490 // Profile file to use
491 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
492
493 bool print_pass_options = false;
494 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
495 bool include_debug_symbols = kIsDebugBuild;
496 bool watch_dog_enabled = true;
497 bool generate_gdb_information = kIsDebugBuild;
498
499 std::string error_msg;
500
501 for (int i = 0; i < argc; i++) {
502 const StringPiece option(argv[i]);
503 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 if (log_options) {
505 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
506 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800507 if (option.starts_with("--dex-file=")) {
508 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
509 } else if (option.starts_with("--dex-location=")) {
510 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
511 } else if (option.starts_with("--zip-fd=")) {
512 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
513 if (!ParseInt(zip_fd_str, &zip_fd_)) {
514 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
515 }
516 if (zip_fd_ < 0) {
517 Usage("--zip-fd passed a negative value %d", zip_fd_);
518 }
519 } else if (option.starts_with("--zip-location=")) {
520 zip_location_ = option.substr(strlen("--zip-location=")).data();
521 } else if (option.starts_with("--oat-file=")) {
522 oat_filename_ = option.substr(strlen("--oat-file=")).data();
523 } else if (option.starts_with("--oat-symbols=")) {
524 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
525 } else if (option.starts_with("--oat-fd=")) {
526 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
527 if (!ParseInt(oat_fd_str, &oat_fd_)) {
528 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
529 }
530 if (oat_fd_ < 0) {
531 Usage("--oat-fd passed a negative value %d", oat_fd_);
532 }
533 } else if (option == "--watch-dog") {
534 watch_dog_enabled = true;
535 } else if (option == "--no-watch-dog") {
536 watch_dog_enabled = false;
537 } else if (option == "--gen-gdb-info") {
538 generate_gdb_information = true;
539 // Debug symbols are needed for gdb information.
540 include_debug_symbols = true;
541 } else if (option == "--no-gen-gdb-info") {
542 generate_gdb_information = false;
543 } else if (option.starts_with("-j")) {
544 const char* thread_count_str = option.substr(strlen("-j")).data();
545 if (!ParseUint(thread_count_str, &thread_count_)) {
546 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
547 }
548 } else if (option.starts_with("--oat-location=")) {
549 oat_location_ = option.substr(strlen("--oat-location=")).data();
550 } else if (option.starts_with("--bitcode=")) {
551 bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
552 } else if (option.starts_with("--image=")) {
553 image_filename_ = option.substr(strlen("--image=")).data();
554 } else if (option.starts_with("--image-classes=")) {
555 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
556 } else if (option.starts_with("--image-classes-zip=")) {
557 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800558 } else if (option.starts_with("--compiled-classes=")) {
559 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
560 } else if (option.starts_with("--compiled-classes-zip=")) {
561 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800562 } else if (option.starts_with("--base=")) {
563 const char* image_base_str = option.substr(strlen("--base=")).data();
564 char* end;
565 image_base_ = strtoul(image_base_str, &end, 16);
566 if (end == image_base_str || *end != '\0') {
567 Usage("Failed to parse hexadecimal value for option %s", option.data());
568 }
569 } else if (option.starts_with("--boot-image=")) {
570 boot_image_filename = option.substr(strlen("--boot-image=")).data();
571 } else if (option.starts_with("--android-root=")) {
572 android_root_ = option.substr(strlen("--android-root=")).data();
573 } else if (option.starts_with("--instruction-set=")) {
574 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
575 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
576 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
577 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
578 buf.get()[instruction_set_str.length()] = 0;
579 instruction_set_ = GetInstructionSetFromString(buf.get());
580 // arm actually means thumb2.
581 if (instruction_set_ == InstructionSet::kArm) {
582 instruction_set_ = InstructionSet::kThumb2;
583 }
584 } else if (option.starts_with("--instruction-set-variant=")) {
585 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
586 instruction_set_features_.reset(
587 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
588 if (instruction_set_features_.get() == nullptr) {
589 Usage("%s", error_msg.c_str());
590 }
591 } else if (option.starts_with("--instruction-set-features=")) {
592 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800593 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800594 instruction_set_features_.reset(
595 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
596 if (instruction_set_features_.get() == nullptr) {
597 Usage("Problem initializing default instruction set features variant: %s",
598 error_msg.c_str());
599 }
600 }
601 instruction_set_features_.reset(
602 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
603 if (instruction_set_features_.get() == nullptr) {
604 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800605 }
606 } else if (option.starts_with("--compiler-backend=")) {
607 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
608 if (backend_str == "Quick") {
609 compiler_kind_ = Compiler::kQuick;
610 } else if (backend_str == "Optimizing") {
611 compiler_kind_ = Compiler::kOptimizing;
612 } else if (backend_str == "Portable") {
613 compiler_kind_ = Compiler::kPortable;
614 } else {
615 Usage("Unknown compiler backend: %s", backend_str.data());
616 }
617 } else if (option.starts_with("--compiler-filter=")) {
618 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
619 } else if (option == "--compile-pic") {
620 compile_pic = true;
621 } else if (option.starts_with("--huge-method-max=")) {
622 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
623 if (!ParseInt(threshold, &huge_method_threshold)) {
624 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
625 }
626 if (huge_method_threshold < 0) {
627 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
628 }
629 } else if (option.starts_with("--large-method-max=")) {
630 const char* threshold = option.substr(strlen("--large-method-max=")).data();
631 if (!ParseInt(threshold, &large_method_threshold)) {
632 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
633 }
634 if (large_method_threshold < 0) {
635 Usage("--large-method-max passed a negative value %s", large_method_threshold);
636 }
637 } else if (option.starts_with("--small-method-max=")) {
638 const char* threshold = option.substr(strlen("--small-method-max=")).data();
639 if (!ParseInt(threshold, &small_method_threshold)) {
640 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
641 }
642 if (small_method_threshold < 0) {
643 Usage("--small-method-max passed a negative value %s", small_method_threshold);
644 }
645 } else if (option.starts_with("--tiny-method-max=")) {
646 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
647 if (!ParseInt(threshold, &tiny_method_threshold)) {
648 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
649 }
650 if (tiny_method_threshold < 0) {
651 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
652 }
653 } else if (option.starts_with("--num-dex-methods=")) {
654 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
655 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
656 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
657 }
658 if (num_dex_methods_threshold < 0) {
659 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
660 }
661 } else if (option == "--host") {
662 is_host_ = true;
663 } else if (option == "--runtime-arg") {
664 if (++i >= argc) {
665 Usage("Missing required argument for --runtime-arg");
666 }
667 if (log_options) {
668 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
669 }
670 runtime_args_.push_back(argv[i]);
671 } else if (option == "--dump-timing") {
672 dump_timing_ = true;
673 } else if (option == "--dump-passes") {
674 dump_passes_ = true;
675 } else if (option == "--dump-stats") {
676 dump_stats_ = true;
677 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
678 include_debug_symbols = true;
679 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
680 include_debug_symbols = false;
681 generate_gdb_information = false; // Depends on debug symbols, see above.
682 } else if (option.starts_with("--profile-file=")) {
683 profile_file_ = option.substr(strlen("--profile-file=")).data();
684 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
685 } else if (option == "--no-profile-file") {
686 // No profile
687 } else if (option.starts_with("--top-k-profile-threshold=")) {
688 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
689 } else if (option == "--print-pass-names") {
690 PassDriverMEOpts::PrintPassNames();
691 } else if (option.starts_with("--disable-passes=")) {
692 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
693 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
694 } else if (option.starts_with("--print-passes=")) {
695 std::string print_passes = option.substr(strlen("--print-passes=")).data();
696 PassDriverMEOpts::SetPrintPassList(print_passes);
697 } else if (option == "--print-all-passes") {
698 PassDriverMEOpts::SetPrintAllPasses();
699 } else if (option.starts_with("--dump-cfg-passes=")) {
700 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
701 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
702 } else if (option == "--print-pass-options") {
703 print_pass_options = true;
704 } else if (option.starts_with("--pass-options=")) {
705 std::string options = option.substr(strlen("--pass-options=")).data();
706 PassDriverMEOpts::SetOverriddenPassOptions(options);
707 } else if (option == "--include-patch-information") {
708 include_patch_information = true;
709 } else if (option == "--no-include-patch-information") {
710 include_patch_information = false;
711 } else if (option.starts_with("--verbose-methods=")) {
712 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
713 // on having verbost methods.
714 gLogVerbosity.compiler = false;
715 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800716 } else if (option.starts_with("--dump-init-failures=")) {
717 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
718 init_failure_output_.reset(new std::ofstream(file_name));
719 if (init_failure_output_.get() == nullptr) {
720 LOG(ERROR) << "Failed to allocate ofstream";
721 } else if (init_failure_output_->fail()) {
722 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
723 << "failures.";
724 init_failure_output_.reset();
725 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800726 } else {
727 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800729 }
730
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000731 if (compiler_kind_ == Compiler::kOptimizing) {
732 // Optimizing only supports PIC mode.
733 compile_pic = true;
734 }
735
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800736 if (oat_filename_.empty() && oat_fd_ == -1) {
737 Usage("Output must be supplied with either --oat-file or --oat-fd");
738 }
739
740 if (!oat_filename_.empty() && oat_fd_ != -1) {
741 Usage("--oat-file should not be used with --oat-fd");
742 }
743
744 if (!oat_symbols.empty() && oat_fd_ != -1) {
745 Usage("--oat-symbols should not be used with --oat-fd");
746 }
747
748 if (!oat_symbols.empty() && is_host_) {
749 Usage("--oat-symbols should not be used with --host");
750 }
751
752 if (oat_fd_ != -1 && !image_filename_.empty()) {
753 Usage("--oat-fd should not be used with --image");
754 }
755
756 if (android_root_.empty()) {
757 const char* android_root_env_var = getenv("ANDROID_ROOT");
758 if (android_root_env_var == nullptr) {
759 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700760 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800761 android_root_ += android_root_env_var;
762 }
763
764 image_ = (!image_filename_.empty());
765 if (!image_ && boot_image_filename.empty()) {
766 boot_image_filename += android_root_;
767 boot_image_filename += "/framework/boot.art";
768 }
769 if (!boot_image_filename.empty()) {
770 boot_image_option_ += "-Ximage:";
771 boot_image_option_ += boot_image_filename;
772 }
773
774 if (image_classes_filename_ != nullptr && !image_) {
775 Usage("--image-classes should only be used with --image");
776 }
777
778 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
779 Usage("--image-classes should not be used with --boot-image");
780 }
781
782 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
783 Usage("--image-classes-zip should be used with --image-classes");
784 }
785
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800786 if (compiled_classes_filename_ != nullptr && !image_) {
787 Usage("--compiled-classes should only be used with --image");
788 }
789
790 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
791 Usage("--compiled-classes should not be used with --boot-image");
792 }
793
794 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
795 Usage("--compiled-classes-zip should be used with --compiled-classes");
796 }
797
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 if (dex_filenames_.empty() && zip_fd_ == -1) {
799 Usage("Input must be supplied with either --dex-file or --zip-fd");
800 }
801
802 if (!dex_filenames_.empty() && zip_fd_ != -1) {
803 Usage("--dex-file should not be used with --zip-fd");
804 }
805
806 if (!dex_filenames_.empty() && !zip_location_.empty()) {
807 Usage("--dex-file should not be used with --zip-location");
808 }
809
810 if (dex_locations_.empty()) {
811 for (const char* dex_file_name : dex_filenames_) {
812 dex_locations_.push_back(dex_file_name);
813 }
814 } else if (dex_locations_.size() != dex_filenames_.size()) {
815 Usage("--dex-location arguments do not match --dex-file arguments");
816 }
817
818 if (zip_fd_ != -1 && zip_location_.empty()) {
819 Usage("--zip-location should be supplied with --zip-fd");
820 }
821
822 if (boot_image_option_.empty()) {
823 if (image_base_ == 0) {
824 Usage("Non-zero --base not specified");
825 }
826 }
827
828 oat_stripped_ = oat_filename_;
829 if (!oat_symbols.empty()) {
830 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700831 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800832 oat_unstripped_ = oat_filename_;
833 }
834
835 // If no instruction set feature was given, use the default one for the target
836 // instruction set.
837 if (instruction_set_features_.get() == nullptr) {
838 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800839 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
840 if (instruction_set_features_.get() == nullptr) {
841 Usage("Problem initializing default instruction set features variant: %s",
842 error_msg.c_str());
843 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800844 }
845
846 if (instruction_set_ == kRuntimeISA) {
847 std::unique_ptr<const InstructionSetFeatures> runtime_features(
848 InstructionSetFeatures::FromCppDefines());
849 if (!instruction_set_features_->Equals(runtime_features.get())) {
850 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
851 << *instruction_set_features_ << ") and those of dex2oat executable ("
852 << *runtime_features <<") for the command line:\n"
853 << CommandLine();
854 }
855 }
856
857 if (compiler_filter_string == nullptr) {
858 if (instruction_set_ == kMips64) {
859 // TODO: fix compiler for Mips64.
860 compiler_filter_string = "interpret-only";
861 } else if (image_) {
862 compiler_filter_string = "speed";
863 } else {
864 // TODO: Migrate SMALL mode to command line option.
865 #if ART_SMALL_MODE
866 compiler_filter_string = "interpret-only";
867 #else
868 compiler_filter_string = "speed";
869 #endif
870 }
871 }
872 CHECK(compiler_filter_string != nullptr);
873 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
874 if (strcmp(compiler_filter_string, "verify-none") == 0) {
875 compiler_filter = CompilerOptions::kVerifyNone;
876 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
877 compiler_filter = CompilerOptions::kInterpretOnly;
878 } else if (strcmp(compiler_filter_string, "space") == 0) {
879 compiler_filter = CompilerOptions::kSpace;
880 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
881 compiler_filter = CompilerOptions::kBalanced;
882 } else if (strcmp(compiler_filter_string, "speed") == 0) {
883 compiler_filter = CompilerOptions::kSpeed;
884 } else if (strcmp(compiler_filter_string, "everything") == 0) {
885 compiler_filter = CompilerOptions::kEverything;
886 } else if (strcmp(compiler_filter_string, "time") == 0) {
887 compiler_filter = CompilerOptions::kTime;
888 } else {
889 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
890 }
891
892 // Checks are all explicit until we know the architecture.
893 bool implicit_null_checks = false;
894 bool implicit_so_checks = false;
895 bool implicit_suspend_checks = false;
896 // Set the compilation target's implicit checks options.
897 switch (instruction_set_) {
898 case kArm:
899 case kThumb2:
900 case kArm64:
901 case kX86:
902 case kX86_64:
903 implicit_null_checks = true;
904 implicit_so_checks = true;
905 break;
906
907 default:
908 // Defaults are correct.
909 break;
910 }
911
912 if (print_pass_options) {
913 PassDriverMEOpts::PrintPassOptions();
914 }
915
916 compiler_options_.reset(new CompilerOptions(compiler_filter,
917 huge_method_threshold,
918 large_method_threshold,
919 small_method_threshold,
920 tiny_method_threshold,
921 num_dex_methods_threshold,
922 generate_gdb_information,
923 include_patch_information,
924 top_k_profile_threshold,
925 include_debug_symbols,
926 implicit_null_checks,
927 implicit_so_checks,
928 implicit_suspend_checks,
929 compile_pic,
930 #ifdef ART_SEA_IR_MODE
931 true,
932 #endif
933 verbose_methods_.empty() ?
934 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800935 &verbose_methods_,
936 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800937
938 // Done with usage checks, enable watchdog if requested
939 if (watch_dog_enabled) {
940 watchdog_.reset(new WatchDog(true));
941 }
942
943 // Fill some values into the key-value store for the oat header.
944 key_value_store_.reset(new SafeMap<std::string, std::string>());
945
946 // Insert some compiler things.
947 {
948 std::ostringstream oss;
949 for (int i = 0; i < argc; ++i) {
950 if (i > 0) {
951 oss << ' ';
952 }
953 oss << argv[i];
954 }
955 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
956 oss.str(""); // Reset.
957 oss << kRuntimeISA;
958 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
959 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
960 }
961 }
962
963 // Check whether the oat output file is writable, and open it for later.
964 bool OpenFile() {
965 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
966 if (create_file) {
967 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
968 if (oat_location_.empty()) {
969 oat_location_ = oat_filename_;
970 }
971 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800972 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800974 if (oat_file_->SetLength(0) != 0) {
975 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
976 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800977 }
978 if (oat_file_.get() == nullptr) {
979 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
980 return false;
981 }
982 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
983 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800984 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800985 return false;
986 }
987 return true;
988 }
989
Andreas Gampea650e702014-12-03 14:28:02 -0800990 void EraseOatFile() {
991 DCHECK(oat_file_.get() != nullptr);
992 oat_file_->Erase();
993 oat_file_.reset();
994 }
995
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800996 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
997 // boot class path.
998 bool Setup() {
999 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1000 RuntimeOptions runtime_options;
1001 std::vector<const DexFile*> boot_class_path;
1002 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1003 if (boot_image_option_.empty()) {
1004 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001005 if (failure_count > 0) {
1006 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001007 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001008 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001009 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
1010 } else {
1011 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
1012 }
1013 for (size_t i = 0; i < runtime_args_.size(); i++) {
1014 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001015 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001016
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001017 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1018 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1019 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1020 runtime_options.push_back(
1021 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1022
1023 if (!CreateRuntime(runtime_options)) {
1024 return false;
1025 }
1026
1027 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1028 // Runtime::Start, give it away now so that we don't starve GC.
1029 Thread* self = Thread::Current();
1030 self->TransitionFromRunnableToSuspended(kNative);
1031 // If we're doing the image, override the compiler filter to force full compilation. Must be
1032 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1033 // compilation of class initializers.
1034 // Whilst we're in native take the opportunity to initialize well known classes.
1035 WellKnownClasses::Init(self->GetJniEnv());
1036
1037 // If --image-classes was specified, calculate the full list of classes to include in the image
1038 if (image_classes_filename_ != nullptr) {
1039 std::string error_msg;
1040 if (image_classes_zip_filename_ != nullptr) {
1041 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1042 image_classes_filename_,
1043 &error_msg));
1044 } else {
1045 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1046 }
1047 if (image_classes_.get() == nullptr) {
1048 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1049 "': " << error_msg;
1050 return false;
1051 }
1052 } else if (image_) {
1053 image_classes_.reset(new std::set<std::string>);
1054 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001055 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1056 // image.
1057 if (compiled_classes_filename_ != nullptr) {
1058 std::string error_msg;
1059 if (compiled_classes_zip_filename_ != nullptr) {
1060 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1061 compiled_classes_filename_,
1062 &error_msg));
1063 } else {
1064 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1065 }
1066 if (compiled_classes_.get() == nullptr) {
1067 LOG(ERROR) << "Failed to create list of compiled classes from '"
1068 << compiled_classes_filename_ << "': " << error_msg;
1069 return false;
1070 }
1071 } else if (image_) {
1072 compiled_classes_.reset(nullptr); // By default compile everything.
1073 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001074
1075 if (boot_image_option_.empty()) {
1076 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1077 } else {
1078 if (dex_filenames_.empty()) {
1079 ATRACE_BEGIN("Opening zip archive from file descriptor");
1080 std::string error_msg;
1081 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1082 zip_location_.c_str(),
1083 &error_msg));
1084 if (zip_archive.get() == nullptr) {
1085 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1086 << error_msg;
1087 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001088 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001089 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1090 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1091 << "': " << error_msg;
1092 return false;
1093 }
1094 ATRACE_END();
1095 } else {
1096 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1097 if (failure_count > 0) {
1098 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1099 return false;
1100 }
1101 }
1102
1103 constexpr bool kSaveDexInput = false;
1104 if (kSaveDexInput) {
1105 for (size_t i = 0; i < dex_files_.size(); ++i) {
1106 const DexFile* dex_file = dex_files_[i];
1107 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1108 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1109 if (tmp_file.get() == nullptr) {
1110 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1111 << ". Try: adb shell chmod 777 /data/local/tmp";
1112 continue;
1113 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001114 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1115 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1116 UNUSED(tmp_file->Flush());
1117 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001118 LOG(INFO) << "Wrote input to " << tmp_file_name;
1119 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001120 }
1121 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001122 // Ensure opened dex files are writable for dex-to-dex transformations.
1123 for (const auto& dex_file : dex_files_) {
1124 if (!dex_file->EnableWrite()) {
1125 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001126 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001127 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001128
1129 /*
1130 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1131 * Don't bother to check if we're doing the image.
1132 */
1133 if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1134 size_t num_methods = 0;
1135 for (size_t i = 0; i != dex_files_.size(); ++i) {
1136 const DexFile* dex_file = dex_files_[i];
1137 CHECK(dex_file != nullptr);
1138 num_methods += dex_file->NumMethodIds();
1139 }
1140 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1141 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1142 VLOG(compiler) << "Below method threshold, compiling anyways";
1143 }
1144 }
1145
1146 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001147 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001148
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149 // Create and invoke the compiler driver. This will compile all the dex files.
1150 void Compile() {
1151 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1152 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001153
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001154 // Handle and ClassLoader creation needs to come after Runtime::Create
1155 jobject class_loader = nullptr;
1156 Thread* self = Thread::Current();
1157 if (!boot_image_option_.empty()) {
1158 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1159 std::vector<const DexFile*> class_path_files(dex_files_);
1160 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1161 ScopedObjectAccess soa(self);
1162 for (size_t i = 0; i < class_path_files.size(); i++) {
1163 class_linker->RegisterDexFile(*class_path_files[i]);
1164 }
1165 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1166 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1167 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1168 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1169 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1170 }
1171
1172 driver_.reset(new CompilerDriver(compiler_options_.get(),
1173 verification_results_.get(),
1174 &method_inliner_map_,
1175 compiler_kind_,
1176 instruction_set_,
1177 instruction_set_features_.get(),
1178 image_,
1179 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001180 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001181 thread_count_,
1182 dump_stats_,
1183 dump_passes_,
1184 compiler_phases_timings_.get(),
1185 profile_file_));
1186
1187 driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1188
1189 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001190 }
1191
Brian Carlstrom7940e442013-07-12 13:46:57 -07001192 // Notes on the interleaving of creating the image and oat file to
1193 // ensure the references between the two are correct.
1194 //
1195 // Currently we have a memory layout that looks something like this:
1196 //
1197 // +--------------+
1198 // | image |
1199 // +--------------+
1200 // | boot oat |
1201 // +--------------+
1202 // | alloc spaces |
1203 // +--------------+
1204 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001205 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001206 //
1207 // 1. The image is expected to be loaded at an absolute address and
1208 // contains Objects with absolute pointers within the image.
1209 //
1210 // 2. There are absolute pointers from Methods in the image to their
1211 // code in the oat.
1212 //
1213 // 3. There are absolute pointers from the code in the oat to Methods
1214 // in the image.
1215 //
1216 // 4. There are absolute pointers from code in the oat to other code
1217 // in the oat.
1218 //
1219 // To get this all correct, we go through several steps.
1220 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001221 // 1. We prepare offsets for all data in the oat file and calculate
1222 // the oat data size and code size. During this stage, we also set
1223 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001224 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 // 2. We prepare offsets for the objects in the image and calculate
1226 // the image size.
1227 //
1228 // 3. We create the oat file. Originally this was just our own proprietary
1229 // file but now it is contained within an ELF dynamic object (aka an .so
1230 // file). Since we know the image size and oat data size and code size we
1231 // can prepare the ELF headers and we then know the ELF memory segment
1232 // layout and we can now resolve all references. The compiler provides
1233 // LinkerPatch information in each CompiledMethod and we resolve these,
1234 // using the layout information and image object locations provided by
1235 // image writer, as we're writing the method code.
1236 //
1237 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001238 // will be loaded after itself. Originally when oat file was simply
1239 // memory mapped so we could predict where its contents were based
1240 // on the file size. Now that it is an ELF file, we need to inspect
1241 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001242 // where the oat header is located within.
1243 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001244 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001245 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001246 // load the .so at the desired location at runtime by offsetting the
1247 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001248 // TODO: Do this in step 3. We already know the layout there.
1249 //
1250 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1251 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001252
1253
1254 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1255 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001256 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1257 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001258 bool CreateOatFile() {
1259 CHECK(key_value_store_.get() != nullptr);
1260
1261 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1262
1263 std::unique_ptr<OatWriter> oat_writer;
1264 {
1265 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1266 std::string image_file_location;
1267 uint32_t image_file_location_oat_checksum = 0;
1268 uintptr_t image_file_location_oat_data_begin = 0;
1269 int32_t image_patch_delta = 0;
1270 if (image_) {
1271 PrepareImageWriter(image_base_);
1272 } else {
1273 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1274 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1275 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1276 image_file_location_oat_data_begin =
1277 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1278 image_file_location = image_space->GetImageFilename();
1279 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1280 }
1281
1282 if (!image_file_location.empty()) {
1283 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1284 }
1285
1286 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1287 image_file_location_oat_data_begin,
1288 image_patch_delta,
1289 driver_.get(),
1290 image_writer_.get(),
1291 timings_,
1292 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001293 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001294
1295 if (image_) {
1296 // The OatWriter constructor has already updated offsets in methods and we need to
1297 // prepare method offsets in the image address space for direct method patching.
1298 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1299 if (!image_writer_->PrepareImageAddressSpace()) {
1300 LOG(ERROR) << "Failed to prepare image address space.";
1301 return false;
1302 }
1303 }
1304
1305 {
1306 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1307 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1308 oat_file_.get())) {
1309 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1310 return false;
1311 }
1312 }
1313
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001314 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1315 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001316 }
1317
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001318 // If we are compiling an image, invoke the image creation routine. Else just skip.
1319 bool HandleImage() {
1320 if (image_) {
1321 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1322 if (!CreateImageFile()) {
1323 return false;
1324 }
1325 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001326 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001327 return true;
1328 }
1329
Andreas Gampe10e477d2014-11-19 12:57:42 -08001330 // Create a copy from unstripped to stripped.
1331 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001332 // If we don't want to strip in place, copy from unstripped location to stripped location.
1333 // We need to strip after image creation because FixupElf needs to use .strtab.
1334 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001335 // If the oat file is still open, flush it.
1336 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1337 if (!FlushCloseOatFile()) {
1338 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001339 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001340 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001341
1342 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001343 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1344 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1345 size_t buffer_size = 8192;
1346 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1347 while (true) {
1348 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1349 if (bytes_read <= 0) {
1350 break;
1351 }
1352 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1353 CHECK(write_ok);
1354 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001355 if (kUsePortableCompiler) {
1356 oat_file_.reset(out.release());
1357 } else {
1358 if (out->FlushCloseOrErase() != 0) {
1359 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1360 return false;
1361 }
1362 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001363 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001364 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001365 return true;
1366 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001367
Andreas Gampe10e477d2014-11-19 12:57:42 -08001368 // Run the ElfStripper. Currently only relevant for the portable compiler.
1369 bool Strip() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001370 if (kUsePortableCompiler) {
1371 // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1372 // strip them now. Quick generates debug symbols only when the flag(s) are set.
1373 if (!compiler_options_->GetIncludeDebugSymbols()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001374 CHECK(oat_file_.get() != nullptr && oat_file_->IsOpened());
1375
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001376 TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1377 // Strip unneeded sections for target
1378 off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1379 CHECK_EQ(0, seek_actual);
1380 std::string error_msg;
1381 if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1382 LOG(ERROR) << "Failed to strip elf file: " << error_msg;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001383 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001384 return false;
1385 }
1386
Andreas Gampe10e477d2014-11-19 12:57:42 -08001387 if (!FlushCloseOatFile()) {
1388 return false;
1389 }
1390
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001391 // We wrote the oat file successfully, and want to keep it.
1392 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1393 } else {
1394 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1395 }
1396 }
1397
Andreas Gampe10e477d2014-11-19 12:57:42 -08001398 return true;
1399 }
1400
1401 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001402 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001403 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1404 if (oat_file_->Flush() != 0) {
1405 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1406 << oat_filename_;
1407 oat_file_->Erase();
1408 return false;
1409 }
1410 }
1411 return true;
1412 }
1413
1414 bool FlushCloseOatFile() {
1415 if (oat_file_.get() != nullptr) {
1416 std::unique_ptr<File> tmp(oat_file_.release());
1417 if (tmp->FlushCloseOrErase() != 0) {
1418 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1419 << oat_filename_;
1420 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001421 }
1422 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001423 return true;
1424 }
1425
1426 void DumpTiming() {
1427 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1428 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1429 }
1430 if (dump_passes_) {
1431 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1432 }
1433 }
1434
1435 CompilerOptions* GetCompilerOptions() const {
1436 return compiler_options_.get();
1437 }
1438
Andreas Gampe10e477d2014-11-19 12:57:42 -08001439 bool IsImage() const {
1440 return image_;
1441 }
1442
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001443 bool IsHost() const {
1444 return is_host_;
1445 }
1446
1447 private:
1448 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1449 const std::vector<const char*>& dex_locations,
1450 std::vector<const DexFile*>& dex_files) {
1451 size_t failure_count = 0;
1452 for (size_t i = 0; i < dex_filenames.size(); i++) {
1453 const char* dex_filename = dex_filenames[i];
1454 const char* dex_location = dex_locations[i];
1455 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1456 std::string error_msg;
1457 if (!OS::FileExists(dex_filename)) {
1458 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1459 continue;
1460 }
1461 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1462 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1463 ++failure_count;
1464 }
1465 ATRACE_END();
1466 }
1467 return failure_count;
1468 }
1469
1470 // Returns true if dex_files has a dex with the named location.
1471 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1472 const std::string& location) {
1473 for (size_t i = 0; i < dex_files.size(); ++i) {
1474 if (dex_files[i]->GetLocation() == location) {
1475 return true;
1476 }
1477 }
1478 return false;
1479 }
1480
1481 // Appends to dex_files any elements of class_path that it doesn't already
1482 // contain. This will open those dex files as necessary.
1483 static void OpenClassPathFiles(const std::string& class_path,
1484 std::vector<const DexFile*>& dex_files) {
1485 std::vector<std::string> parsed;
1486 Split(class_path, ':', &parsed);
1487 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1488 ScopedObjectAccess soa(Thread::Current());
1489 for (size_t i = 0; i < parsed.size(); ++i) {
1490 if (DexFilesContains(dex_files, parsed[i])) {
1491 continue;
1492 }
1493 std::string error_msg;
1494 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1495 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1496 }
1497 }
1498 }
1499
1500 // Create a runtime necessary for compilation.
1501 bool CreateRuntime(const RuntimeOptions& runtime_options)
1502 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1503 if (!Runtime::Create(runtime_options, false)) {
1504 LOG(ERROR) << "Failed to create runtime";
1505 return false;
1506 }
1507 Runtime* runtime = Runtime::Current();
1508 runtime->SetInstructionSet(instruction_set_);
1509 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1510 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1511 if (!runtime->HasCalleeSaveMethod(type)) {
1512 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1513 }
1514 }
1515 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1516 runtime->GetClassLinker()->RunRootClinits();
1517 runtime_ = runtime;
1518 return true;
1519 }
1520
1521 void PrepareImageWriter(uintptr_t image_base) {
1522 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1523 }
1524
1525 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1526 bool CreateImageFile()
1527 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1528 CHECK(image_writer_ != nullptr);
1529 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1530 LOG(ERROR) << "Failed to create image file " << image_filename_;
1531 return false;
1532 }
1533 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1534
1535 // Destroy ImageWriter before doing FixupElf.
1536 image_writer_.reset();
1537
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001538 // Do not fix up the ELF file if we are --compile-pic
1539 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001540 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1541 if (oat_file.get() == nullptr) {
1542 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1543 return false;
1544 }
1545
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001546 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001547 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001548 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1549 return false;
1550 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001551
1552 if (oat_file->FlushCloseOrErase()) {
1553 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1554 return false;
1555 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001556 }
1557
1558 return true;
1559 }
1560
1561 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1562 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1563 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1564 std::ifstream::in));
1565 if (image_classes_file.get() == nullptr) {
1566 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1567 return nullptr;
1568 }
1569 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1570 image_classes_file->close();
1571 return result.release();
1572 }
1573
1574 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1575 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1576 while (image_classes_stream.good()) {
1577 std::string dot;
1578 std::getline(image_classes_stream, dot);
1579 if (StartsWith(dot, "#") || dot.empty()) {
1580 continue;
1581 }
1582 std::string descriptor(DotToDescriptor(dot.c_str()));
1583 image_classes->insert(descriptor);
1584 }
1585 return image_classes.release();
1586 }
1587
1588 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1589 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1590 const char* image_classes_filename,
1591 std::string* error_msg) {
1592 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1593 if (zip_archive.get() == nullptr) {
1594 return nullptr;
1595 }
1596 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1597 if (zip_entry.get() == nullptr) {
1598 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1599 zip_filename, error_msg->c_str());
1600 return nullptr;
1601 }
1602 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1603 image_classes_filename,
1604 error_msg));
1605 if (image_classes_file.get() == nullptr) {
1606 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1607 zip_filename, error_msg->c_str());
1608 return nullptr;
1609 }
1610 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1611 image_classes_file->Size());
1612 std::istringstream image_classes_stream(image_classes_string);
1613 return ReadImageClasses(image_classes_stream);
1614 }
1615
Mathieu Chartier49285c52014-12-02 15:43:48 -08001616 void LogCompletionTime() {
1617 std::ostringstream mallinfostr;
1618#ifdef HAVE_MALLOC_H
1619 struct mallinfo info = mallinfo();
1620 const size_t allocated_space = static_cast<size_t>(info.uordblks);
1621 const size_t free_space = static_cast<size_t>(info.fordblks);
1622 mallinfostr << " native alloc=" << PrettySize(allocated_space) << " free="
1623 << PrettySize(free_space);
1624#endif
1625 const ArenaPool* arena_pool = driver_->GetArenaPool();
1626 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001627 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartier49285c52014-12-02 15:43:48 -08001628 << " (threads: " << thread_count_ << ")"
1629 << " arena alloc=" << PrettySize(arena_pool->GetBytesAllocated())
1630 << " java alloc=" << PrettySize(heap->GetBytesAllocated()) << mallinfostr.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001631 }
1632
1633 std::unique_ptr<CompilerOptions> compiler_options_;
1634 Compiler::Kind compiler_kind_;
1635
1636 InstructionSet instruction_set_;
1637 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1638
1639 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1640
1641 std::unique_ptr<VerificationResults> verification_results_;
1642 DexFileToMethodInlinerMap method_inliner_map_;
1643 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1644
1645 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1646 // in an orderly fashion. The destructor takes care of deleting this.
1647 Runtime* runtime_;
1648
1649 size_t thread_count_;
1650 uint64_t start_ns_;
1651 std::unique_ptr<WatchDog> watchdog_;
1652 std::unique_ptr<File> oat_file_;
1653 std::string oat_stripped_;
1654 std::string oat_unstripped_;
1655 std::string oat_location_;
1656 std::string oat_filename_;
1657 int oat_fd_;
1658 std::string bitcode_filename_;
1659 std::vector<const char*> dex_filenames_;
1660 std::vector<const char*> dex_locations_;
1661 int zip_fd_;
1662 std::string zip_location_;
1663 std::string boot_image_option_;
1664 std::vector<const char*> runtime_args_;
1665 std::string image_filename_;
1666 uintptr_t image_base_;
1667 const char* image_classes_zip_filename_;
1668 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001669 const char* compiled_classes_zip_filename_;
1670 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001671 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001672 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001673 bool image_;
1674 std::unique_ptr<ImageWriter> image_writer_;
1675 bool is_host_;
1676 std::string android_root_;
1677 std::vector<const DexFile*> dex_files_;
1678 std::unique_ptr<CompilerDriver> driver_;
1679 std::vector<std::string> verbose_methods_;
1680 bool dump_stats_;
1681 bool dump_passes_;
1682 bool dump_timing_;
1683 bool dump_slow_timing_;
1684 std::string profile_file_; // Profile file to use
1685 TimingLogger* timings_;
1686 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001687 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001688
1689 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1690};
1691
1692const unsigned int WatchDog::kWatchDogWarningSeconds;
1693const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1694
1695static void b13564922() {
1696#if defined(__linux__) && defined(__arm__)
1697 int major, minor;
1698 struct utsname uts;
1699 if (uname(&uts) != -1 &&
1700 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1701 ((major < 3) || ((major == 3) && (minor < 4)))) {
1702 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1703 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1704 int old_personality = personality(0xffffffff);
1705 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1706 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1707 if (new_personality == -1) {
1708 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1709 }
1710 }
1711 }
1712#endif
1713}
1714
Andreas Gampe10e477d2014-11-19 12:57:42 -08001715static int CompileImage(Dex2Oat& dex2oat) {
1716 dex2oat.Compile();
1717
1718 // Create the boot.oat.
1719 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001720 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001721 return EXIT_FAILURE;
1722 }
1723
1724 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1725 // re-opened from the unstripped name.
1726 if (!dex2oat.FlushCloseOatFile()) {
1727 return EXIT_FAILURE;
1728 }
1729
1730 // Creates the boot.art and patches the boot.oat.
1731 if (!dex2oat.HandleImage()) {
1732 return EXIT_FAILURE;
1733 }
1734
1735 // When given --host, finish early without stripping.
1736 if (dex2oat.IsHost()) {
1737 dex2oat.DumpTiming();
1738 return EXIT_SUCCESS;
1739 }
1740
1741 // Copy unstripped to stripped location, if necessary.
1742 if (!dex2oat.CopyUnstrippedToStripped()) {
1743 return EXIT_FAILURE;
1744 }
1745
1746 // Strip, if necessary.
1747 if (!dex2oat.Strip()) {
1748 return EXIT_FAILURE;
1749 }
1750
1751 // FlushClose again, as stripping might have re-opened the oat file.
1752 if (!dex2oat.FlushCloseOatFile()) {
1753 return EXIT_FAILURE;
1754 }
1755
1756 dex2oat.DumpTiming();
1757 return EXIT_SUCCESS;
1758}
1759
1760static int CompileApp(Dex2Oat& dex2oat) {
1761 dex2oat.Compile();
1762
1763 // Create the app oat.
1764 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001765 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001766 return EXIT_FAILURE;
1767 }
1768
1769 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1770 // which we would lose.
1771 if (!dex2oat.FlushOatFile()) {
1772 return EXIT_FAILURE;
1773 }
1774
1775 // When given --host, finish early without stripping.
1776 if (dex2oat.IsHost()) {
1777 if (!dex2oat.FlushCloseOatFile()) {
1778 return EXIT_FAILURE;
1779 }
1780
1781 dex2oat.DumpTiming();
1782 return EXIT_SUCCESS;
1783 }
1784
1785 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1786 // unstripped version. If this is given, we expect to be able to open writable files by name.
1787 if (!dex2oat.CopyUnstrippedToStripped()) {
1788 return EXIT_FAILURE;
1789 }
1790
1791 // Strip, if necessary.
1792 if (!dex2oat.Strip()) {
1793 return EXIT_FAILURE;
1794 }
1795
1796 // Flush and close the file.
1797 if (!dex2oat.FlushCloseOatFile()) {
1798 return EXIT_FAILURE;
1799 }
1800
1801 dex2oat.DumpTiming();
1802 return EXIT_SUCCESS;
1803}
1804
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001805static int dex2oat(int argc, char** argv) {
1806 b13564922();
1807
1808 TimingLogger timings("compiler", false, false);
1809
1810 Dex2Oat dex2oat(&timings);
1811
1812 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1813 dex2oat.ParseArgs(argc, argv);
1814
1815 // Check early that the result of compilation can be written
1816 if (!dex2oat.OpenFile()) {
1817 return EXIT_FAILURE;
1818 }
1819
1820 LOG(INFO) << CommandLine();
1821
1822 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001823 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001824 return EXIT_FAILURE;
1825 }
1826
Andreas Gampe10e477d2014-11-19 12:57:42 -08001827 if (dex2oat.IsImage()) {
1828 return CompileImage(dex2oat);
1829 } else {
1830 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001831 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001832}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001833} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001834
1835int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001836 int result = art::dex2oat(argc, argv);
1837 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1838 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1839 // should not destruct the runtime in this case.
1840 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1841 exit(result);
1842 }
1843 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001844}