blob: d957d27cf657c2011e7808f9ff86b98f751ad300 [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>
Mathieu Chartier49285c52014-12-02 15:43:48 -080024#include <malloc.h> // For mallinfo
Brian Carlstrom7940e442013-07-12 13:46:57 -070025#include <sstream>
26#include <string>
27#include <vector>
28
Vladimir Markof94b7812014-06-05 15:48:04 +010029#if defined(__linux__) && defined(__arm__)
30#include <sys/personality.h>
31#include <sys/utsname.h>
32#endif
33
Ian Rogerscf7f1912014-10-22 22:06:39 -070034#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080035#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070036
Ian Rogersd582fa42014-11-05 23:46:43 -080037#include "arch/instruction_set_features.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "base/stl_util.h"
40#include "base/stringpiece.h"
41#include "base/timing_logger.h"
42#include "base/unix_file/fd_file.h"
43#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000044#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000045#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070047#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000048#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "dex/quick_compiler_callbacks.h"
50#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080052#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080053#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070054#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/image_space.h"
56#include "gc/space/space-inl.h"
57#include "image_writer.h"
58#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070059#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/class-inl.h"
61#include "mirror/class_loader.h"
62#include "mirror/object-inl.h"
63#include "mirror/object_array-inl.h"
64#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "os.h"
66#include "runtime.h"
67#include "ScopedLocalRef.h"
68#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070069#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "vector_output_stream.h"
71#include "well_known_classes.h"
72#include "zip_archive.h"
73
74namespace art {
75
Brian Carlstrom6449c622014-02-10 23:48:36 -080076static int original_argc;
77static char** original_argv;
78
79static std::string CommandLine() {
80 std::vector<std::string> command;
81 for (int i = 0; i < original_argc; ++i) {
82 command.push_back(original_argv[i]);
83 }
84 return Join(command, ' ');
85}
86
Brian Carlstrom7940e442013-07-12 13:46:57 -070087static void UsageErrorV(const char* fmt, va_list ap) {
88 std::string error;
89 StringAppendV(&error, fmt, ap);
90 LOG(ERROR) << error;
91}
92
93static void UsageError(const char* fmt, ...) {
94 va_list ap;
95 va_start(ap, fmt);
96 UsageErrorV(fmt, ap);
97 va_end(ap);
98}
99
Ian Rogers7223d442014-10-10 20:05:39 -0700100[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101 va_list ap;
102 va_start(ap, fmt);
103 UsageErrorV(fmt, ap);
104 va_end(ap);
105
Brian Carlstrom6449c622014-02-10 23:48:36 -0800106 UsageError("Command: %s", CommandLine().c_str());
107
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108 UsageError("Usage: dex2oat [options]...");
109 UsageError("");
110 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
111 UsageError(" Example: --dex-file=/system/framework/core.jar");
112 UsageError("");
113 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
114 UsageError(" containing a classes.dex file to compile.");
115 UsageError(" Example: --zip-fd=5");
116 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700117 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
118 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700119 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
120 UsageError("");
121 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
122 UsageError(" Example: --oat-file=/system/framework/boot.oat");
123 UsageError("");
124 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900125 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700126 UsageError("");
127 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
128 UsageError(" to the file descriptor specified by --oat-fd.");
129 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
130 UsageError("");
131 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
132 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
133 UsageError("");
134 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename.");
135 UsageError(" Example: --bitcode=/system/framework/boot.bc");
136 UsageError("");
137 UsageError(" --image=<file.art>: specifies the output image filename.");
138 UsageError(" Example: --image=/system/framework/boot.art");
139 UsageError("");
140 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
141 UsageError(" Example: --image=frameworks/base/preloaded-classes");
142 UsageError("");
143 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
144 UsageError(" Example: --base=0x50000000");
145 UsageError("");
146 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
147 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000148 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149 UsageError("");
150 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
151 UsageError(" Example: --android-root=out/host/linux-x86");
152 UsageError(" Default: $ANDROID_ROOT");
153 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700154 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
155 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700156 UsageError(" Example: --instruction-set=x86");
157 UsageError(" Default: arm");
158 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700159 UsageError(" --instruction-set-features=...,: Specify instruction set features");
160 UsageError(" Example: --instruction-set-features=div");
161 UsageError(" Default: default");
162 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700163 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
164 UsageError(" Default: disabled");
165 UsageError("");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000166 UsageError(" --compiler-backend=(Quick|Optimizing|Portable): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700167 UsageError(" set.");
Brian Carlstrom635733d2013-10-30 23:19:31 -0700168 UsageError(" Example: --compiler-backend=Portable");
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000169 if (kUsePortableCompiler) {
170 UsageError(" Default: Portable");
171 } else if (kUseOptimizingCompiler) {
172 UsageError(" Default: Optimizing");
173 } else {
174 UsageError(" Default: Quick");
175 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100177 UsageError(" --compiler-filter="
178 "(verify-none"
179 "|interpret-only"
180 "|space"
181 "|balanced"
182 "|speed"
183 "|everything"
184 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700185 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800186 UsageError(" Example: --compiler-filter=everything");
187#if ART_SMALL_MODE
188 UsageError(" Default: interpret-only");
189#else
190 UsageError(" Default: speed");
191#endif
192 UsageError("");
193 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
194 UsageError(" method for compiler filter tuning.");
195 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
196 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
197 UsageError("");
198 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
199 UsageError(" method for compiler filter tuning.");
200 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
201 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
202 UsageError("");
203 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
204 UsageError(" method for compiler filter tuning.");
205 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
206 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
207 UsageError("");
208 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
209 UsageError(" method for compiler filter tuning.");
210 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
211 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
212 UsageError("");
213 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
214 UsageError(" method for compiler filter tuning.");
215 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
216 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
217 UsageError("");
218 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
219 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700220 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
221 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800222 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
223 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
224 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" --host: used with Portable backend to link against host runtime libraries");
226 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700227 UsageError(" --dump-timing: display a breakdown of where time was spent");
228 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700229 UsageError(" --include-patch-information: Include patching information so the generated code");
230 UsageError(" can have its base address moved without full recompilation.");
231 UsageError("");
232 UsageError(" --no-include-patch-information: Do not include patching information.");
233 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700234 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
235 UsageError("");
236 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
237 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
239 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
240 UsageError(" Use a separate --runtime-arg switch for each argument.");
241 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700242 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000243 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700244 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700245 UsageError(" --print-pass-names: print a list of pass names");
246 UsageError("");
247 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
248 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
249 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700250 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
251 "with the setting.");
252 UsageError(" Will print default if no overridden setting exists.");
253 UsageError("");
254 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
255 "Pass2Name:Pass2OptionName:Pass2Option#");
256 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
257 UsageError(" Separator used between options is a comma.");
258 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700259 std::cerr << "See log for usage error information\n";
260 exit(EXIT_FAILURE);
261}
262
Brian Carlstrom7940e442013-07-12 13:46:57 -0700263// The primary goal of the watchdog is to prevent stuck build servers
264// during development when fatal aborts lead to a cascade of failures
265// that result in a deadlock.
266class WatchDog {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700267// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks
268#undef CHECK_PTHREAD_CALL
269#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
270 do { \
271 int rc = call args; \
272 if (rc != 0) { \
273 errno = rc; \
274 std::string message(# call); \
275 message += " failed for "; \
276 message += reason; \
277 Fatal(message); \
278 } \
279 } while (false)
280
281 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700282 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700283 is_watch_dog_enabled_ = is_watch_dog_enabled;
284 if (!is_watch_dog_enabled_) {
285 return;
286 }
287 shutting_down_ = false;
288 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
293 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
294 }
295 ~WatchDog() {
296 if (!is_watch_dog_enabled_) {
297 return;
298 }
299 const char* reason = "dex2oat watch dog thread shutdown";
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
301 shutting_down_ = true;
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
304
Kenny Root51316382014-05-13 14:59:37 -0700305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700306
307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
308 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
309 }
310
311 private:
312 static void* CallBack(void* arg) {
313 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
314 ::art::SetThreadName("dex2oat watch dog");
315 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700316 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317 }
318
319 static void Message(char severity, const std::string& message) {
320 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
321 // cases.
322 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
323 kIsDebugBuild ? "d" : "",
324 severity,
325 getpid(),
326 GetTid(),
327 message.c_str());
328 }
329
330 static void Warn(const std::string& message) {
331 Message('W', message);
332 }
333
Ian Rogers7223d442014-10-10 20:05:39 -0700334 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 Message('F', message);
336 exit(1);
337 }
338
339 void Wait() {
340 bool warning = true;
341 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds);
342 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
343 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800344 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 timespec warning_ts;
346 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts);
347 timespec timeout_ts;
348 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
349 const char* reason = "dex2oat watch dog thread waiting";
350 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
351 while (!shutting_down_) {
352 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_,
353 warning ? &warning_ts
354 : &timeout_ts));
355 if (rc == ETIMEDOUT) {
356 std::string message(StringPrintf("dex2oat did not finish after %d seconds",
357 warning ? kWatchDogWarningSeconds
358 : kWatchDogTimeoutSeconds));
359 if (warning) {
360 Warn(message.c_str());
361 warning = false;
362 } else {
363 Fatal(message.c_str());
364 }
365 } else if (rc != 0) {
366 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
367 strerror(errno)));
368 Fatal(message.c_str());
369 }
370 }
371 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
372 }
373
374 // 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 -0700375 // Debug builds are slower so they have larger timeouts.
376 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800377
378 static const unsigned int kWatchDogWarningSeconds = kUsePortableCompiler ?
379 kSlowdownFactor * 2 * 60 : // 2 minutes scaled by kSlowdownFactor (portable).
380 kSlowdownFactor * 1 * 60; // 1 minute scaled by kSlowdownFactor (not-portable).
381 static const unsigned int kWatchDogTimeoutSeconds = kUsePortableCompiler ?
382 kSlowdownFactor * 30 * 60 : // 30 minutes scaled by kSlowdownFactor (portable).
383 kSlowdownFactor * 6 * 60; // 6 minutes scaled by kSlowdownFactor (not-portable).
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384
385 bool is_watch_dog_enabled_;
386 bool shutting_down_;
387 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
388 pthread_mutex_t mutex_;
389 pthread_cond_t cond_;
390 pthread_attr_t attr_;
391 pthread_t pthread_;
392};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800394static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100395 std::string::size_type colon = s.find(c);
396 if (colon == std::string::npos) {
397 Usage("Missing char %c in option %s\n", c, s.c_str());
398 }
399 // Add one to remove the char we were trimming until.
400 *parsed_value = s.substr(colon + 1);
401}
402
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800403static void ParseDouble(const std::string& option, char after_char, double min, double max,
404 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100405 std::string substring;
406 ParseStringAfterChar(option, after_char, &substring);
407 bool sane_val = true;
408 double value;
409 if (false) {
410 // TODO: this doesn't seem to work on the emulator. b/15114595
411 std::stringstream iss(substring);
412 iss >> value;
413 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
414 sane_val = iss.eof() && (value >= min) && (value <= max);
415 } else {
416 char* end = nullptr;
417 value = strtod(substring.c_str(), &end);
418 sane_val = *end == '\0' && value >= min && value <= max;
419 }
420 if (!sane_val) {
421 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
422 }
423 *parsed_value = value;
424}
425
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800426class Dex2Oat FINAL {
427 public:
428 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000429 compiler_kind_(kUsePortableCompiler
430 ? Compiler::kPortable
431 : (kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick)),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800432 instruction_set_(kRuntimeISA),
433 // Take the default set of instruction features from the build.
434 method_inliner_map_(),
435 runtime_(nullptr),
436 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
437 start_ns_(NanoTime()),
438 oat_fd_(-1),
439 zip_fd_(-1),
440 image_base_(0U),
441 image_classes_zip_filename_(nullptr),
442 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800443 compiled_classes_zip_filename_(nullptr),
444 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445 image_(false),
446 is_host_(false),
447 dump_stats_(false),
448 dump_passes_(false),
449 dump_timing_(false),
450 dump_slow_timing_(kIsDebugBuild),
451 timings_(timings) {}
452
453 ~Dex2Oat() {
Mathieu Chartier49285c52014-12-02 15:43:48 -0800454 LogCompletionTime(); // Needs to be before since it accesses the runtime.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
456 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100457 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 }
459
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800460 // Parse the arguments from the command line. In case of an unrecognized option or impossible
461 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
462 // returns, arguments have been successfully parsed.
463 void ParseArgs(int argc, char** argv) {
464 original_argc = argc;
465 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700466
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700468
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469 // Skip over argv[0].
470 argv++;
471 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700472
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800473 if (argc == 0) {
474 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476
477 std::string oat_symbols;
478 std::string boot_image_filename;
479 const char* compiler_filter_string = nullptr;
480 bool compile_pic = false;
481 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
482 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
483 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
484 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
485 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
486
487 // Profile file to use
488 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
489
490 bool print_pass_options = false;
491 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
492 bool include_debug_symbols = kIsDebugBuild;
493 bool watch_dog_enabled = true;
494 bool generate_gdb_information = kIsDebugBuild;
495
496 std::string error_msg;
497
498 for (int i = 0; i < argc; i++) {
499 const StringPiece option(argv[i]);
500 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501 if (log_options) {
502 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
503 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800504 if (option.starts_with("--dex-file=")) {
505 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
506 } else if (option.starts_with("--dex-location=")) {
507 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
508 } else if (option.starts_with("--zip-fd=")) {
509 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
510 if (!ParseInt(zip_fd_str, &zip_fd_)) {
511 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
512 }
513 if (zip_fd_ < 0) {
514 Usage("--zip-fd passed a negative value %d", zip_fd_);
515 }
516 } else if (option.starts_with("--zip-location=")) {
517 zip_location_ = option.substr(strlen("--zip-location=")).data();
518 } else if (option.starts_with("--oat-file=")) {
519 oat_filename_ = option.substr(strlen("--oat-file=")).data();
520 } else if (option.starts_with("--oat-symbols=")) {
521 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
522 } else if (option.starts_with("--oat-fd=")) {
523 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
524 if (!ParseInt(oat_fd_str, &oat_fd_)) {
525 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
526 }
527 if (oat_fd_ < 0) {
528 Usage("--oat-fd passed a negative value %d", oat_fd_);
529 }
530 } else if (option == "--watch-dog") {
531 watch_dog_enabled = true;
532 } else if (option == "--no-watch-dog") {
533 watch_dog_enabled = false;
534 } else if (option == "--gen-gdb-info") {
535 generate_gdb_information = true;
536 // Debug symbols are needed for gdb information.
537 include_debug_symbols = true;
538 } else if (option == "--no-gen-gdb-info") {
539 generate_gdb_information = false;
540 } else if (option.starts_with("-j")) {
541 const char* thread_count_str = option.substr(strlen("-j")).data();
542 if (!ParseUint(thread_count_str, &thread_count_)) {
543 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
544 }
545 } else if (option.starts_with("--oat-location=")) {
546 oat_location_ = option.substr(strlen("--oat-location=")).data();
547 } else if (option.starts_with("--bitcode=")) {
548 bitcode_filename_ = option.substr(strlen("--bitcode=")).data();
549 } else if (option.starts_with("--image=")) {
550 image_filename_ = option.substr(strlen("--image=")).data();
551 } else if (option.starts_with("--image-classes=")) {
552 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
553 } else if (option.starts_with("--image-classes-zip=")) {
554 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800555 } else if (option.starts_with("--compiled-classes=")) {
556 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
557 } else if (option.starts_with("--compiled-classes-zip=")) {
558 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800559 } else if (option.starts_with("--base=")) {
560 const char* image_base_str = option.substr(strlen("--base=")).data();
561 char* end;
562 image_base_ = strtoul(image_base_str, &end, 16);
563 if (end == image_base_str || *end != '\0') {
564 Usage("Failed to parse hexadecimal value for option %s", option.data());
565 }
566 } else if (option.starts_with("--boot-image=")) {
567 boot_image_filename = option.substr(strlen("--boot-image=")).data();
568 } else if (option.starts_with("--android-root=")) {
569 android_root_ = option.substr(strlen("--android-root=")).data();
570 } else if (option.starts_with("--instruction-set=")) {
571 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
572 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
573 std::unique_ptr<char> buf(new char[instruction_set_str.length() + 1]);
574 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
575 buf.get()[instruction_set_str.length()] = 0;
576 instruction_set_ = GetInstructionSetFromString(buf.get());
577 // arm actually means thumb2.
578 if (instruction_set_ == InstructionSet::kArm) {
579 instruction_set_ = InstructionSet::kThumb2;
580 }
581 } else if (option.starts_with("--instruction-set-variant=")) {
582 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
583 instruction_set_features_.reset(
584 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
585 if (instruction_set_features_.get() == nullptr) {
586 Usage("%s", error_msg.c_str());
587 }
588 } else if (option.starts_with("--instruction-set-features=")) {
589 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800590 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800591 instruction_set_features_.reset(
592 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
593 if (instruction_set_features_.get() == nullptr) {
594 Usage("Problem initializing default instruction set features variant: %s",
595 error_msg.c_str());
596 }
597 }
598 instruction_set_features_.reset(
599 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
600 if (instruction_set_features_.get() == nullptr) {
601 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800602 }
603 } else if (option.starts_with("--compiler-backend=")) {
604 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
605 if (backend_str == "Quick") {
606 compiler_kind_ = Compiler::kQuick;
607 } else if (backend_str == "Optimizing") {
608 compiler_kind_ = Compiler::kOptimizing;
609 } else if (backend_str == "Portable") {
610 compiler_kind_ = Compiler::kPortable;
611 } else {
612 Usage("Unknown compiler backend: %s", backend_str.data());
613 }
614 } else if (option.starts_with("--compiler-filter=")) {
615 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
616 } else if (option == "--compile-pic") {
617 compile_pic = true;
618 } else if (option.starts_with("--huge-method-max=")) {
619 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
620 if (!ParseInt(threshold, &huge_method_threshold)) {
621 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
622 }
623 if (huge_method_threshold < 0) {
624 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
625 }
626 } else if (option.starts_with("--large-method-max=")) {
627 const char* threshold = option.substr(strlen("--large-method-max=")).data();
628 if (!ParseInt(threshold, &large_method_threshold)) {
629 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
630 }
631 if (large_method_threshold < 0) {
632 Usage("--large-method-max passed a negative value %s", large_method_threshold);
633 }
634 } else if (option.starts_with("--small-method-max=")) {
635 const char* threshold = option.substr(strlen("--small-method-max=")).data();
636 if (!ParseInt(threshold, &small_method_threshold)) {
637 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
638 }
639 if (small_method_threshold < 0) {
640 Usage("--small-method-max passed a negative value %s", small_method_threshold);
641 }
642 } else if (option.starts_with("--tiny-method-max=")) {
643 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
644 if (!ParseInt(threshold, &tiny_method_threshold)) {
645 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
646 }
647 if (tiny_method_threshold < 0) {
648 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
649 }
650 } else if (option.starts_with("--num-dex-methods=")) {
651 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
652 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
653 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
654 }
655 if (num_dex_methods_threshold < 0) {
656 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
657 }
658 } else if (option == "--host") {
659 is_host_ = true;
660 } else if (option == "--runtime-arg") {
661 if (++i >= argc) {
662 Usage("Missing required argument for --runtime-arg");
663 }
664 if (log_options) {
665 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
666 }
667 runtime_args_.push_back(argv[i]);
668 } else if (option == "--dump-timing") {
669 dump_timing_ = true;
670 } else if (option == "--dump-passes") {
671 dump_passes_ = true;
672 } else if (option == "--dump-stats") {
673 dump_stats_ = true;
674 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
675 include_debug_symbols = true;
676 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
677 include_debug_symbols = false;
678 generate_gdb_information = false; // Depends on debug symbols, see above.
679 } else if (option.starts_with("--profile-file=")) {
680 profile_file_ = option.substr(strlen("--profile-file=")).data();
681 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
682 } else if (option == "--no-profile-file") {
683 // No profile
684 } else if (option.starts_with("--top-k-profile-threshold=")) {
685 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
686 } else if (option == "--print-pass-names") {
687 PassDriverMEOpts::PrintPassNames();
688 } else if (option.starts_with("--disable-passes=")) {
689 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
690 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
691 } else if (option.starts_with("--print-passes=")) {
692 std::string print_passes = option.substr(strlen("--print-passes=")).data();
693 PassDriverMEOpts::SetPrintPassList(print_passes);
694 } else if (option == "--print-all-passes") {
695 PassDriverMEOpts::SetPrintAllPasses();
696 } else if (option.starts_with("--dump-cfg-passes=")) {
697 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
698 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
699 } else if (option == "--print-pass-options") {
700 print_pass_options = true;
701 } else if (option.starts_with("--pass-options=")) {
702 std::string options = option.substr(strlen("--pass-options=")).data();
703 PassDriverMEOpts::SetOverriddenPassOptions(options);
704 } else if (option == "--include-patch-information") {
705 include_patch_information = true;
706 } else if (option == "--no-include-patch-information") {
707 include_patch_information = false;
708 } else if (option.starts_with("--verbose-methods=")) {
709 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages conditional
710 // on having verbost methods.
711 gLogVerbosity.compiler = false;
712 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800713 } else if (option.starts_with("--dump-init-failures=")) {
714 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
715 init_failure_output_.reset(new std::ofstream(file_name));
716 if (init_failure_output_.get() == nullptr) {
717 LOG(ERROR) << "Failed to allocate ofstream";
718 } else if (init_failure_output_->fail()) {
719 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
720 << "failures.";
721 init_failure_output_.reset();
722 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 } else {
724 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800726 }
727
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000728 if (compiler_kind_ == Compiler::kOptimizing) {
729 // Optimizing only supports PIC mode.
730 compile_pic = true;
731 }
732
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800733 if (oat_filename_.empty() && oat_fd_ == -1) {
734 Usage("Output must be supplied with either --oat-file or --oat-fd");
735 }
736
737 if (!oat_filename_.empty() && oat_fd_ != -1) {
738 Usage("--oat-file should not be used with --oat-fd");
739 }
740
741 if (!oat_symbols.empty() && oat_fd_ != -1) {
742 Usage("--oat-symbols should not be used with --oat-fd");
743 }
744
745 if (!oat_symbols.empty() && is_host_) {
746 Usage("--oat-symbols should not be used with --host");
747 }
748
749 if (oat_fd_ != -1 && !image_filename_.empty()) {
750 Usage("--oat-fd should not be used with --image");
751 }
752
753 if (android_root_.empty()) {
754 const char* android_root_env_var = getenv("ANDROID_ROOT");
755 if (android_root_env_var == nullptr) {
756 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800758 android_root_ += android_root_env_var;
759 }
760
761 image_ = (!image_filename_.empty());
762 if (!image_ && boot_image_filename.empty()) {
763 boot_image_filename += android_root_;
764 boot_image_filename += "/framework/boot.art";
765 }
766 if (!boot_image_filename.empty()) {
767 boot_image_option_ += "-Ximage:";
768 boot_image_option_ += boot_image_filename;
769 }
770
771 if (image_classes_filename_ != nullptr && !image_) {
772 Usage("--image-classes should only be used with --image");
773 }
774
775 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
776 Usage("--image-classes should not be used with --boot-image");
777 }
778
779 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
780 Usage("--image-classes-zip should be used with --image-classes");
781 }
782
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800783 if (compiled_classes_filename_ != nullptr && !image_) {
784 Usage("--compiled-classes should only be used with --image");
785 }
786
787 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
788 Usage("--compiled-classes should not be used with --boot-image");
789 }
790
791 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
792 Usage("--compiled-classes-zip should be used with --compiled-classes");
793 }
794
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 if (dex_filenames_.empty() && zip_fd_ == -1) {
796 Usage("Input must be supplied with either --dex-file or --zip-fd");
797 }
798
799 if (!dex_filenames_.empty() && zip_fd_ != -1) {
800 Usage("--dex-file should not be used with --zip-fd");
801 }
802
803 if (!dex_filenames_.empty() && !zip_location_.empty()) {
804 Usage("--dex-file should not be used with --zip-location");
805 }
806
807 if (dex_locations_.empty()) {
808 for (const char* dex_file_name : dex_filenames_) {
809 dex_locations_.push_back(dex_file_name);
810 }
811 } else if (dex_locations_.size() != dex_filenames_.size()) {
812 Usage("--dex-location arguments do not match --dex-file arguments");
813 }
814
815 if (zip_fd_ != -1 && zip_location_.empty()) {
816 Usage("--zip-location should be supplied with --zip-fd");
817 }
818
819 if (boot_image_option_.empty()) {
820 if (image_base_ == 0) {
821 Usage("Non-zero --base not specified");
822 }
823 }
824
825 oat_stripped_ = oat_filename_;
826 if (!oat_symbols.empty()) {
827 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700828 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800829 oat_unstripped_ = oat_filename_;
830 }
831
832 // If no instruction set feature was given, use the default one for the target
833 // instruction set.
834 if (instruction_set_features_.get() == nullptr) {
835 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800836 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
837 if (instruction_set_features_.get() == nullptr) {
838 Usage("Problem initializing default instruction set features variant: %s",
839 error_msg.c_str());
840 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800841 }
842
843 if (instruction_set_ == kRuntimeISA) {
844 std::unique_ptr<const InstructionSetFeatures> runtime_features(
845 InstructionSetFeatures::FromCppDefines());
846 if (!instruction_set_features_->Equals(runtime_features.get())) {
847 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
848 << *instruction_set_features_ << ") and those of dex2oat executable ("
849 << *runtime_features <<") for the command line:\n"
850 << CommandLine();
851 }
852 }
853
854 if (compiler_filter_string == nullptr) {
855 if (instruction_set_ == kMips64) {
856 // TODO: fix compiler for Mips64.
857 compiler_filter_string = "interpret-only";
858 } else if (image_) {
859 compiler_filter_string = "speed";
860 } else {
861 // TODO: Migrate SMALL mode to command line option.
862 #if ART_SMALL_MODE
863 compiler_filter_string = "interpret-only";
864 #else
865 compiler_filter_string = "speed";
866 #endif
867 }
868 }
869 CHECK(compiler_filter_string != nullptr);
870 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
871 if (strcmp(compiler_filter_string, "verify-none") == 0) {
872 compiler_filter = CompilerOptions::kVerifyNone;
873 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
874 compiler_filter = CompilerOptions::kInterpretOnly;
875 } else if (strcmp(compiler_filter_string, "space") == 0) {
876 compiler_filter = CompilerOptions::kSpace;
877 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
878 compiler_filter = CompilerOptions::kBalanced;
879 } else if (strcmp(compiler_filter_string, "speed") == 0) {
880 compiler_filter = CompilerOptions::kSpeed;
881 } else if (strcmp(compiler_filter_string, "everything") == 0) {
882 compiler_filter = CompilerOptions::kEverything;
883 } else if (strcmp(compiler_filter_string, "time") == 0) {
884 compiler_filter = CompilerOptions::kTime;
885 } else {
886 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
887 }
888
889 // Checks are all explicit until we know the architecture.
890 bool implicit_null_checks = false;
891 bool implicit_so_checks = false;
892 bool implicit_suspend_checks = false;
893 // Set the compilation target's implicit checks options.
894 switch (instruction_set_) {
895 case kArm:
896 case kThumb2:
897 case kArm64:
898 case kX86:
899 case kX86_64:
900 implicit_null_checks = true;
901 implicit_so_checks = true;
902 break;
903
904 default:
905 // Defaults are correct.
906 break;
907 }
908
909 if (print_pass_options) {
910 PassDriverMEOpts::PrintPassOptions();
911 }
912
913 compiler_options_.reset(new CompilerOptions(compiler_filter,
914 huge_method_threshold,
915 large_method_threshold,
916 small_method_threshold,
917 tiny_method_threshold,
918 num_dex_methods_threshold,
919 generate_gdb_information,
920 include_patch_information,
921 top_k_profile_threshold,
922 include_debug_symbols,
923 implicit_null_checks,
924 implicit_so_checks,
925 implicit_suspend_checks,
926 compile_pic,
927 #ifdef ART_SEA_IR_MODE
928 true,
929 #endif
930 verbose_methods_.empty() ?
931 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800932 &verbose_methods_,
933 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800934
935 // Done with usage checks, enable watchdog if requested
936 if (watch_dog_enabled) {
937 watchdog_.reset(new WatchDog(true));
938 }
939
940 // Fill some values into the key-value store for the oat header.
941 key_value_store_.reset(new SafeMap<std::string, std::string>());
942
943 // Insert some compiler things.
944 {
945 std::ostringstream oss;
946 for (int i = 0; i < argc; ++i) {
947 if (i > 0) {
948 oss << ' ';
949 }
950 oss << argv[i];
951 }
952 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
953 oss.str(""); // Reset.
954 oss << kRuntimeISA;
955 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
956 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
957 }
958 }
959
960 // Check whether the oat output file is writable, and open it for later.
961 bool OpenFile() {
962 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
963 if (create_file) {
964 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
965 if (oat_location_.empty()) {
966 oat_location_ = oat_filename_;
967 }
968 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800969 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800970 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800971 if (oat_file_->SetLength(0) != 0) {
972 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
973 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800974 }
975 if (oat_file_.get() == nullptr) {
976 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
977 return false;
978 }
979 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
980 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800981 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800982 return false;
983 }
984 return true;
985 }
986
987 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
988 // boot class path.
989 bool Setup() {
990 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
991 RuntimeOptions runtime_options;
992 std::vector<const DexFile*> boot_class_path;
993 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
994 if (boot_image_option_.empty()) {
995 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800996 if (failure_count > 0) {
997 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800998 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -0800999 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001000 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
1001 } else {
1002 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
1003 }
1004 for (size_t i = 0; i < runtime_args_.size(); i++) {
1005 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001007
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001008 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1009 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1010 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1011 runtime_options.push_back(
1012 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1013
1014 if (!CreateRuntime(runtime_options)) {
1015 return false;
1016 }
1017
1018 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1019 // Runtime::Start, give it away now so that we don't starve GC.
1020 Thread* self = Thread::Current();
1021 self->TransitionFromRunnableToSuspended(kNative);
1022 // If we're doing the image, override the compiler filter to force full compilation. Must be
1023 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1024 // compilation of class initializers.
1025 // Whilst we're in native take the opportunity to initialize well known classes.
1026 WellKnownClasses::Init(self->GetJniEnv());
1027
1028 // If --image-classes was specified, calculate the full list of classes to include in the image
1029 if (image_classes_filename_ != nullptr) {
1030 std::string error_msg;
1031 if (image_classes_zip_filename_ != nullptr) {
1032 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1033 image_classes_filename_,
1034 &error_msg));
1035 } else {
1036 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1037 }
1038 if (image_classes_.get() == nullptr) {
1039 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1040 "': " << error_msg;
1041 return false;
1042 }
1043 } else if (image_) {
1044 image_classes_.reset(new std::set<std::string>);
1045 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001046 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1047 // image.
1048 if (compiled_classes_filename_ != nullptr) {
1049 std::string error_msg;
1050 if (compiled_classes_zip_filename_ != nullptr) {
1051 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1052 compiled_classes_filename_,
1053 &error_msg));
1054 } else {
1055 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1056 }
1057 if (compiled_classes_.get() == nullptr) {
1058 LOG(ERROR) << "Failed to create list of compiled classes from '"
1059 << compiled_classes_filename_ << "': " << error_msg;
1060 return false;
1061 }
1062 } else if (image_) {
1063 compiled_classes_.reset(nullptr); // By default compile everything.
1064 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001065
1066 if (boot_image_option_.empty()) {
1067 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1068 } else {
1069 if (dex_filenames_.empty()) {
1070 ATRACE_BEGIN("Opening zip archive from file descriptor");
1071 std::string error_msg;
1072 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1073 zip_location_.c_str(),
1074 &error_msg));
1075 if (zip_archive.get() == nullptr) {
1076 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1077 << error_msg;
1078 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001079 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001080 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1081 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1082 << "': " << error_msg;
1083 return false;
1084 }
1085 ATRACE_END();
1086 } else {
1087 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1088 if (failure_count > 0) {
1089 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1090 return false;
1091 }
1092 }
1093
1094 constexpr bool kSaveDexInput = false;
1095 if (kSaveDexInput) {
1096 for (size_t i = 0; i < dex_files_.size(); ++i) {
1097 const DexFile* dex_file = dex_files_[i];
1098 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", getpid(), i));
1099 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1100 if (tmp_file.get() == nullptr) {
1101 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1102 << ". Try: adb shell chmod 777 /data/local/tmp";
1103 continue;
1104 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001105 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1106 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1107 UNUSED(tmp_file->Flush());
1108 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001109 LOG(INFO) << "Wrote input to " << tmp_file_name;
1110 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001111 }
1112 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001113 // Ensure opened dex files are writable for dex-to-dex transformations.
1114 for (const auto& dex_file : dex_files_) {
1115 if (!dex_file->EnableWrite()) {
1116 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001117 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001118 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001119
1120 /*
1121 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1122 * Don't bother to check if we're doing the image.
1123 */
1124 if (!image_ && compiler_options_->IsCompilationEnabled() && compiler_kind_ == Compiler::kQuick) {
1125 size_t num_methods = 0;
1126 for (size_t i = 0; i != dex_files_.size(); ++i) {
1127 const DexFile* dex_file = dex_files_[i];
1128 CHECK(dex_file != nullptr);
1129 num_methods += dex_file->NumMethodIds();
1130 }
1131 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1132 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1133 VLOG(compiler) << "Below method threshold, compiling anyways";
1134 }
1135 }
1136
1137 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001138 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001139
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 // Create and invoke the compiler driver. This will compile all the dex files.
1141 void Compile() {
1142 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1143 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001144
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001145 // Handle and ClassLoader creation needs to come after Runtime::Create
1146 jobject class_loader = nullptr;
1147 Thread* self = Thread::Current();
1148 if (!boot_image_option_.empty()) {
1149 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1150 std::vector<const DexFile*> class_path_files(dex_files_);
1151 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1152 ScopedObjectAccess soa(self);
1153 for (size_t i = 0; i < class_path_files.size(); i++) {
1154 class_linker->RegisterDexFile(*class_path_files[i]);
1155 }
1156 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1157 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1158 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1159 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1160 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1161 }
1162
1163 driver_.reset(new CompilerDriver(compiler_options_.get(),
1164 verification_results_.get(),
1165 &method_inliner_map_,
1166 compiler_kind_,
1167 instruction_set_,
1168 instruction_set_features_.get(),
1169 image_,
1170 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001171 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172 thread_count_,
1173 dump_stats_,
1174 dump_passes_,
1175 compiler_phases_timings_.get(),
1176 profile_file_));
1177
1178 driver_->GetCompiler()->SetBitcodeFileName(*driver_, bitcode_filename_);
1179
1180 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001181 }
1182
Brian Carlstrom7940e442013-07-12 13:46:57 -07001183 // Notes on the interleaving of creating the image and oat file to
1184 // ensure the references between the two are correct.
1185 //
1186 // Currently we have a memory layout that looks something like this:
1187 //
1188 // +--------------+
1189 // | image |
1190 // +--------------+
1191 // | boot oat |
1192 // +--------------+
1193 // | alloc spaces |
1194 // +--------------+
1195 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001196 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 //
1198 // 1. The image is expected to be loaded at an absolute address and
1199 // contains Objects with absolute pointers within the image.
1200 //
1201 // 2. There are absolute pointers from Methods in the image to their
1202 // code in the oat.
1203 //
1204 // 3. There are absolute pointers from the code in the oat to Methods
1205 // in the image.
1206 //
1207 // 4. There are absolute pointers from code in the oat to other code
1208 // in the oat.
1209 //
1210 // To get this all correct, we go through several steps.
1211 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001212 // 1. We prepare offsets for all data in the oat file and calculate
1213 // the oat data size and code size. During this stage, we also set
1214 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001216 // 2. We prepare offsets for the objects in the image and calculate
1217 // the image size.
1218 //
1219 // 3. We create the oat file. Originally this was just our own proprietary
1220 // file but now it is contained within an ELF dynamic object (aka an .so
1221 // file). Since we know the image size and oat data size and code size we
1222 // can prepare the ELF headers and we then know the ELF memory segment
1223 // layout and we can now resolve all references. The compiler provides
1224 // LinkerPatch information in each CompiledMethod and we resolve these,
1225 // using the layout information and image object locations provided by
1226 // image writer, as we're writing the method code.
1227 //
1228 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229 // will be loaded after itself. Originally when oat file was simply
1230 // memory mapped so we could predict where its contents were based
1231 // on the file size. Now that it is an ELF file, we need to inspect
1232 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001233 // where the oat header is located within.
1234 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237 // load the .so at the desired location at runtime by offsetting the
1238 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001239 // TODO: Do this in step 3. We already know the layout there.
1240 //
1241 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1242 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001243
1244
1245 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1246 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001247 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1248 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001249 bool CreateOatFile() {
1250 CHECK(key_value_store_.get() != nullptr);
1251
1252 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1253
1254 std::unique_ptr<OatWriter> oat_writer;
1255 {
1256 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1257 std::string image_file_location;
1258 uint32_t image_file_location_oat_checksum = 0;
1259 uintptr_t image_file_location_oat_data_begin = 0;
1260 int32_t image_patch_delta = 0;
1261 if (image_) {
1262 PrepareImageWriter(image_base_);
1263 } else {
1264 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1265 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1266 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1267 image_file_location_oat_data_begin =
1268 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1269 image_file_location = image_space->GetImageFilename();
1270 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1271 }
1272
1273 if (!image_file_location.empty()) {
1274 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1275 }
1276
1277 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1278 image_file_location_oat_data_begin,
1279 image_patch_delta,
1280 driver_.get(),
1281 image_writer_.get(),
1282 timings_,
1283 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001284 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001285
1286 if (image_) {
1287 // The OatWriter constructor has already updated offsets in methods and we need to
1288 // prepare method offsets in the image address space for direct method patching.
1289 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1290 if (!image_writer_->PrepareImageAddressSpace()) {
1291 LOG(ERROR) << "Failed to prepare image address space.";
1292 return false;
1293 }
1294 }
1295
1296 {
1297 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1298 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1299 oat_file_.get())) {
1300 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001301 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001302 return false;
1303 }
1304 }
1305
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001306 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1307 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308 }
1309
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001310 // If we are compiling an image, invoke the image creation routine. Else just skip.
1311 bool HandleImage() {
1312 if (image_) {
1313 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1314 if (!CreateImageFile()) {
1315 return false;
1316 }
1317 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001318 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001319 return true;
1320 }
1321
Andreas Gampe10e477d2014-11-19 12:57:42 -08001322 // Create a copy from unstripped to stripped.
1323 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001324 // If we don't want to strip in place, copy from unstripped location to stripped location.
1325 // We need to strip after image creation because FixupElf needs to use .strtab.
1326 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001327 // If the oat file is still open, flush it.
1328 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1329 if (!FlushCloseOatFile()) {
1330 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001331 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001332 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001333
1334 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001335 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1336 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1337 size_t buffer_size = 8192;
1338 std::unique_ptr<uint8_t> buffer(new uint8_t[buffer_size]);
1339 while (true) {
1340 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1341 if (bytes_read <= 0) {
1342 break;
1343 }
1344 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1345 CHECK(write_ok);
1346 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001347 if (kUsePortableCompiler) {
1348 oat_file_.reset(out.release());
1349 } else {
1350 if (out->FlushCloseOrErase() != 0) {
1351 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1352 return false;
1353 }
1354 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001355 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001356 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001357 return true;
1358 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001359
Andreas Gampe10e477d2014-11-19 12:57:42 -08001360 // Run the ElfStripper. Currently only relevant for the portable compiler.
1361 bool Strip() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001362 if (kUsePortableCompiler) {
1363 // Portable includes debug symbols unconditionally. If we are not supposed to create them,
1364 // strip them now. Quick generates debug symbols only when the flag(s) are set.
1365 if (!compiler_options_->GetIncludeDebugSymbols()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001366 CHECK(oat_file_.get() != nullptr && oat_file_->IsOpened());
1367
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001368 TimingLogger::ScopedTiming t("dex2oat ElfStripper", timings_);
1369 // Strip unneeded sections for target
1370 off_t seek_actual = lseek(oat_file_->Fd(), 0, SEEK_SET);
1371 CHECK_EQ(0, seek_actual);
1372 std::string error_msg;
1373 if (!ElfFile::Strip(oat_file_.get(), &error_msg)) {
1374 LOG(ERROR) << "Failed to strip elf file: " << error_msg;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001375 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001376 return false;
1377 }
1378
Andreas Gampe10e477d2014-11-19 12:57:42 -08001379 if (!FlushCloseOatFile()) {
1380 return false;
1381 }
1382
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001383 // We wrote the oat file successfully, and want to keep it.
1384 VLOG(compiler) << "Oat file written successfully (stripped): " << oat_location_;
1385 } else {
1386 VLOG(compiler) << "Oat file written successfully without stripping: " << oat_location_;
1387 }
1388 }
1389
Andreas Gampe10e477d2014-11-19 12:57:42 -08001390 return true;
1391 }
1392
1393 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001394 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001395 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1396 if (oat_file_->Flush() != 0) {
1397 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1398 << oat_filename_;
1399 oat_file_->Erase();
1400 return false;
1401 }
1402 }
1403 return true;
1404 }
1405
1406 bool FlushCloseOatFile() {
1407 if (oat_file_.get() != nullptr) {
1408 std::unique_ptr<File> tmp(oat_file_.release());
1409 if (tmp->FlushCloseOrErase() != 0) {
1410 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1411 << oat_filename_;
1412 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001413 }
1414 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001415 return true;
1416 }
1417
1418 void DumpTiming() {
1419 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1420 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1421 }
1422 if (dump_passes_) {
1423 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1424 }
1425 }
1426
1427 CompilerOptions* GetCompilerOptions() const {
1428 return compiler_options_.get();
1429 }
1430
Andreas Gampe10e477d2014-11-19 12:57:42 -08001431 bool IsImage() const {
1432 return image_;
1433 }
1434
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001435 bool IsHost() const {
1436 return is_host_;
1437 }
1438
1439 private:
1440 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1441 const std::vector<const char*>& dex_locations,
1442 std::vector<const DexFile*>& dex_files) {
1443 size_t failure_count = 0;
1444 for (size_t i = 0; i < dex_filenames.size(); i++) {
1445 const char* dex_filename = dex_filenames[i];
1446 const char* dex_location = dex_locations[i];
1447 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1448 std::string error_msg;
1449 if (!OS::FileExists(dex_filename)) {
1450 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1451 continue;
1452 }
1453 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1454 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1455 ++failure_count;
1456 }
1457 ATRACE_END();
1458 }
1459 return failure_count;
1460 }
1461
1462 // Returns true if dex_files has a dex with the named location.
1463 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1464 const std::string& location) {
1465 for (size_t i = 0; i < dex_files.size(); ++i) {
1466 if (dex_files[i]->GetLocation() == location) {
1467 return true;
1468 }
1469 }
1470 return false;
1471 }
1472
1473 // Appends to dex_files any elements of class_path that it doesn't already
1474 // contain. This will open those dex files as necessary.
1475 static void OpenClassPathFiles(const std::string& class_path,
1476 std::vector<const DexFile*>& dex_files) {
1477 std::vector<std::string> parsed;
1478 Split(class_path, ':', &parsed);
1479 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1480 ScopedObjectAccess soa(Thread::Current());
1481 for (size_t i = 0; i < parsed.size(); ++i) {
1482 if (DexFilesContains(dex_files, parsed[i])) {
1483 continue;
1484 }
1485 std::string error_msg;
1486 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1487 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1488 }
1489 }
1490 }
1491
1492 // Create a runtime necessary for compilation.
1493 bool CreateRuntime(const RuntimeOptions& runtime_options)
1494 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1495 if (!Runtime::Create(runtime_options, false)) {
1496 LOG(ERROR) << "Failed to create runtime";
1497 return false;
1498 }
1499 Runtime* runtime = Runtime::Current();
1500 runtime->SetInstructionSet(instruction_set_);
1501 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1502 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1503 if (!runtime->HasCalleeSaveMethod(type)) {
1504 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1505 }
1506 }
1507 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1508 runtime->GetClassLinker()->RunRootClinits();
1509 runtime_ = runtime;
1510 return true;
1511 }
1512
1513 void PrepareImageWriter(uintptr_t image_base) {
1514 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1515 }
1516
1517 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1518 bool CreateImageFile()
1519 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1520 CHECK(image_writer_ != nullptr);
1521 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1522 LOG(ERROR) << "Failed to create image file " << image_filename_;
1523 return false;
1524 }
1525 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1526
1527 // Destroy ImageWriter before doing FixupElf.
1528 image_writer_.reset();
1529
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001530 // Do not fix up the ELF file if we are --compile-pic
1531 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001532 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1533 if (oat_file.get() == nullptr) {
1534 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1535 return false;
1536 }
1537
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001538 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001539 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001540 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1541 return false;
1542 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001543
1544 if (oat_file->FlushCloseOrErase()) {
1545 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1546 return false;
1547 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001548 }
1549
1550 return true;
1551 }
1552
1553 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1554 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1555 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1556 std::ifstream::in));
1557 if (image_classes_file.get() == nullptr) {
1558 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1559 return nullptr;
1560 }
1561 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1562 image_classes_file->close();
1563 return result.release();
1564 }
1565
1566 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1567 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1568 while (image_classes_stream.good()) {
1569 std::string dot;
1570 std::getline(image_classes_stream, dot);
1571 if (StartsWith(dot, "#") || dot.empty()) {
1572 continue;
1573 }
1574 std::string descriptor(DotToDescriptor(dot.c_str()));
1575 image_classes->insert(descriptor);
1576 }
1577 return image_classes.release();
1578 }
1579
1580 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1581 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1582 const char* image_classes_filename,
1583 std::string* error_msg) {
1584 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1585 if (zip_archive.get() == nullptr) {
1586 return nullptr;
1587 }
1588 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1589 if (zip_entry.get() == nullptr) {
1590 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1591 zip_filename, error_msg->c_str());
1592 return nullptr;
1593 }
1594 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1595 image_classes_filename,
1596 error_msg));
1597 if (image_classes_file.get() == nullptr) {
1598 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1599 zip_filename, error_msg->c_str());
1600 return nullptr;
1601 }
1602 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1603 image_classes_file->Size());
1604 std::istringstream image_classes_stream(image_classes_string);
1605 return ReadImageClasses(image_classes_stream);
1606 }
1607
Mathieu Chartier49285c52014-12-02 15:43:48 -08001608 void LogCompletionTime() {
1609 std::ostringstream mallinfostr;
1610#ifdef HAVE_MALLOC_H
1611 struct mallinfo info = mallinfo();
1612 const size_t allocated_space = static_cast<size_t>(info.uordblks);
1613 const size_t free_space = static_cast<size_t>(info.fordblks);
1614 mallinfostr << " native alloc=" << PrettySize(allocated_space) << " free="
1615 << PrettySize(free_space);
1616#endif
1617 const ArenaPool* arena_pool = driver_->GetArenaPool();
1618 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001619 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartier49285c52014-12-02 15:43:48 -08001620 << " (threads: " << thread_count_ << ")"
1621 << " arena alloc=" << PrettySize(arena_pool->GetBytesAllocated())
1622 << " java alloc=" << PrettySize(heap->GetBytesAllocated()) << mallinfostr.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001623 }
1624
1625 std::unique_ptr<CompilerOptions> compiler_options_;
1626 Compiler::Kind compiler_kind_;
1627
1628 InstructionSet instruction_set_;
1629 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1630
1631 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1632
1633 std::unique_ptr<VerificationResults> verification_results_;
1634 DexFileToMethodInlinerMap method_inliner_map_;
1635 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1636
1637 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1638 // in an orderly fashion. The destructor takes care of deleting this.
1639 Runtime* runtime_;
1640
1641 size_t thread_count_;
1642 uint64_t start_ns_;
1643 std::unique_ptr<WatchDog> watchdog_;
1644 std::unique_ptr<File> oat_file_;
1645 std::string oat_stripped_;
1646 std::string oat_unstripped_;
1647 std::string oat_location_;
1648 std::string oat_filename_;
1649 int oat_fd_;
1650 std::string bitcode_filename_;
1651 std::vector<const char*> dex_filenames_;
1652 std::vector<const char*> dex_locations_;
1653 int zip_fd_;
1654 std::string zip_location_;
1655 std::string boot_image_option_;
1656 std::vector<const char*> runtime_args_;
1657 std::string image_filename_;
1658 uintptr_t image_base_;
1659 const char* image_classes_zip_filename_;
1660 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001661 const char* compiled_classes_zip_filename_;
1662 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001663 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001664 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001665 bool image_;
1666 std::unique_ptr<ImageWriter> image_writer_;
1667 bool is_host_;
1668 std::string android_root_;
1669 std::vector<const DexFile*> dex_files_;
1670 std::unique_ptr<CompilerDriver> driver_;
1671 std::vector<std::string> verbose_methods_;
1672 bool dump_stats_;
1673 bool dump_passes_;
1674 bool dump_timing_;
1675 bool dump_slow_timing_;
1676 std::string profile_file_; // Profile file to use
1677 TimingLogger* timings_;
1678 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001679 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001680
1681 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1682};
1683
1684const unsigned int WatchDog::kWatchDogWarningSeconds;
1685const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1686
1687static void b13564922() {
1688#if defined(__linux__) && defined(__arm__)
1689 int major, minor;
1690 struct utsname uts;
1691 if (uname(&uts) != -1 &&
1692 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1693 ((major < 3) || ((major == 3) && (minor < 4)))) {
1694 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1695 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1696 int old_personality = personality(0xffffffff);
1697 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1698 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1699 if (new_personality == -1) {
1700 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1701 }
1702 }
1703 }
1704#endif
1705}
1706
Andreas Gampe10e477d2014-11-19 12:57:42 -08001707static int CompileImage(Dex2Oat& dex2oat) {
1708 dex2oat.Compile();
1709
1710 // Create the boot.oat.
1711 if (!dex2oat.CreateOatFile()) {
1712 return EXIT_FAILURE;
1713 }
1714
1715 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1716 // re-opened from the unstripped name.
1717 if (!dex2oat.FlushCloseOatFile()) {
1718 return EXIT_FAILURE;
1719 }
1720
1721 // Creates the boot.art and patches the boot.oat.
1722 if (!dex2oat.HandleImage()) {
1723 return EXIT_FAILURE;
1724 }
1725
1726 // When given --host, finish early without stripping.
1727 if (dex2oat.IsHost()) {
1728 dex2oat.DumpTiming();
1729 return EXIT_SUCCESS;
1730 }
1731
1732 // Copy unstripped to stripped location, if necessary.
1733 if (!dex2oat.CopyUnstrippedToStripped()) {
1734 return EXIT_FAILURE;
1735 }
1736
1737 // Strip, if necessary.
1738 if (!dex2oat.Strip()) {
1739 return EXIT_FAILURE;
1740 }
1741
1742 // FlushClose again, as stripping might have re-opened the oat file.
1743 if (!dex2oat.FlushCloseOatFile()) {
1744 return EXIT_FAILURE;
1745 }
1746
1747 dex2oat.DumpTiming();
1748 return EXIT_SUCCESS;
1749}
1750
1751static int CompileApp(Dex2Oat& dex2oat) {
1752 dex2oat.Compile();
1753
1754 // Create the app oat.
1755 if (!dex2oat.CreateOatFile()) {
1756 return EXIT_FAILURE;
1757 }
1758
1759 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1760 // which we would lose.
1761 if (!dex2oat.FlushOatFile()) {
1762 return EXIT_FAILURE;
1763 }
1764
1765 // When given --host, finish early without stripping.
1766 if (dex2oat.IsHost()) {
1767 if (!dex2oat.FlushCloseOatFile()) {
1768 return EXIT_FAILURE;
1769 }
1770
1771 dex2oat.DumpTiming();
1772 return EXIT_SUCCESS;
1773 }
1774
1775 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1776 // unstripped version. If this is given, we expect to be able to open writable files by name.
1777 if (!dex2oat.CopyUnstrippedToStripped()) {
1778 return EXIT_FAILURE;
1779 }
1780
1781 // Strip, if necessary.
1782 if (!dex2oat.Strip()) {
1783 return EXIT_FAILURE;
1784 }
1785
1786 // Flush and close the file.
1787 if (!dex2oat.FlushCloseOatFile()) {
1788 return EXIT_FAILURE;
1789 }
1790
1791 dex2oat.DumpTiming();
1792 return EXIT_SUCCESS;
1793}
1794
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001795static int dex2oat(int argc, char** argv) {
1796 b13564922();
1797
1798 TimingLogger timings("compiler", false, false);
1799
1800 Dex2Oat dex2oat(&timings);
1801
1802 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1803 dex2oat.ParseArgs(argc, argv);
1804
1805 // Check early that the result of compilation can be written
1806 if (!dex2oat.OpenFile()) {
1807 return EXIT_FAILURE;
1808 }
1809
1810 LOG(INFO) << CommandLine();
1811
1812 if (!dex2oat.Setup()) {
1813 return EXIT_FAILURE;
1814 }
1815
Andreas Gampe10e477d2014-11-19 12:57:42 -08001816 if (dex2oat.IsImage()) {
1817 return CompileImage(dex2oat);
1818 } else {
1819 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001820 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001821}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001822} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823
1824int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001825 int result = art::dex2oat(argc, argv);
1826 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1827 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1828 // should not destruct the runtime in this case.
1829 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1830 exit(result);
1831 }
1832 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001833}