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