blob: 75d6137eae8b26d0618d0231839c06af2cde2a5e [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
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000053#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick_compiler_callbacks.h"
55#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080058#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070059#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "gc/space/image_space.h"
61#include "gc/space/space-inl.h"
62#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070063#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/class-inl.h"
66#include "mirror/class_loader.h"
67#include "mirror/object-inl.h"
68#include "mirror/object_array-inl.h"
69#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "os.h"
71#include "runtime.h"
72#include "ScopedLocalRef.h"
73#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070074#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "vector_output_stream.h"
76#include "well_known_classes.h"
77#include "zip_archive.h"
78
79namespace art {
80
Brian Carlstrom6449c622014-02-10 23:48:36 -080081static int original_argc;
82static char** original_argv;
83
84static std::string CommandLine() {
85 std::vector<std::string> command;
86 for (int i = 0; i < original_argc; ++i) {
87 command.push_back(original_argv[i]);
88 }
89 return Join(command, ' ');
90}
91
Andreas Gampe046c7062015-05-18 23:22:54 -070092// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
93// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
94// locations are all staged).
95static std::string StrippedCommandLine() {
96 std::vector<std::string> command;
97
98 // Do a pre-pass to look for zip-fd.
99 bool saw_zip_fd = false;
100 for (int i = 0; i < original_argc; ++i) {
101 if (StartsWith(original_argv[i], "--zip-fd=")) {
102 saw_zip_fd = true;
103 break;
104 }
105 }
106
107 // Now filter out things.
108 for (int i = 0; i < original_argc; ++i) {
109 // All runtime-arg parameters are dropped.
110 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
111 i++; // Drop the next part, too.
112 continue;
113 }
114
115 // Any instruction-setXXX is dropped.
116 if (StartsWith(original_argv[i], "--instruction-set")) {
117 continue;
118 }
119
120 // The boot image is dropped.
121 if (StartsWith(original_argv[i], "--boot-image=")) {
122 continue;
123 }
124
125 // This should leave any dex-file and oat-file options, describing what we compiled.
126
127 // However, we prefer to drop this when we saw --zip-fd.
128 if (saw_zip_fd) {
129 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X.
130 if (StartsWith(original_argv[i], "--zip-") ||
131 StartsWith(original_argv[i], "--dex-") ||
132 StartsWith(original_argv[i], "--oat-") ||
133 StartsWith(original_argv[i], "--swap-")) {
134 continue;
135 }
136 }
137
138 command.push_back(original_argv[i]);
139 }
140
141 // Construct the final output.
142 if (command.size() <= 1U) {
143 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
144 return "Starting dex2oat.";
145 }
146 return Join(command, ' ');
147}
148
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149static void UsageErrorV(const char* fmt, va_list ap) {
150 std::string error;
151 StringAppendV(&error, fmt, ap);
152 LOG(ERROR) << error;
153}
154
155static void UsageError(const char* fmt, ...) {
156 va_list ap;
157 va_start(ap, fmt);
158 UsageErrorV(fmt, ap);
159 va_end(ap);
160}
161
Andreas Gampe794ad762015-02-23 08:12:24 -0800162NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 va_list ap;
164 va_start(ap, fmt);
165 UsageErrorV(fmt, ap);
166 va_end(ap);
167
Brian Carlstrom6449c622014-02-10 23:48:36 -0800168 UsageError("Command: %s", CommandLine().c_str());
169
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError("Usage: dex2oat [options]...");
171 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100172 UsageError(" -j<number>: specifies the number of threads used for compilation.");
173 UsageError(" Default is the number of detected hardware threads available on the");
174 UsageError(" host system.");
175 UsageError(" Example: -j12");
176 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700177 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 UsageError(" Example: --dex-file=/system/framework/core.jar");
179 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700180 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
181 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
182 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
183 UsageError(" --dex-location=/system/framework/core.jar");
184 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
186 UsageError(" containing a classes.dex file to compile.");
187 UsageError(" Example: --zip-fd=5");
188 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700189 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
190 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
192 UsageError("");
193 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
194 UsageError(" Example: --oat-file=/system/framework/boot.oat");
195 UsageError("");
196 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900197 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 UsageError("");
199 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
200 UsageError(" to the file descriptor specified by --oat-fd.");
201 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
202 UsageError("");
203 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
204 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
205 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 UsageError(" --image=<file.art>: specifies the output image filename.");
207 UsageError(" Example: --image=/system/framework/boot.art");
208 UsageError("");
209 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
210 UsageError(" Example: --image=frameworks/base/preloaded-classes");
211 UsageError("");
212 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
213 UsageError(" Example: --base=0x50000000");
214 UsageError("");
215 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
216 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000217 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 UsageError("");
219 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
220 UsageError(" Example: --android-root=out/host/linux-x86");
221 UsageError(" Default: $ANDROID_ROOT");
222 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800223 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700224 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" Example: --instruction-set=x86");
226 UsageError(" Default: arm");
227 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700228 UsageError(" --instruction-set-features=...,: Specify instruction set features");
229 UsageError(" Example: --instruction-set-features=div");
230 UsageError(" Default: default");
231 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700232 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
233 UsageError(" Default: disabled");
234 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800235 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800237 UsageError(" Example: --compiler-backend=Optimizing");
238 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000239 UsageError(" Default: Optimizing");
240 } else {
241 UsageError(" Default: Quick");
242 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100244 UsageError(" --compiler-filter="
245 "(verify-none"
246 "|interpret-only"
247 "|space"
248 "|balanced"
249 "|speed"
250 "|everything"
251 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700252 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800253 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800254 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800255 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800256 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
257 UsageError(" method for compiler filter tuning.");
258 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
259 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
260 UsageError("");
261 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
262 UsageError(" method for compiler filter tuning.");
263 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
264 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
265 UsageError("");
266 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
267 UsageError(" method for compiler filter tuning.");
268 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
269 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
270 UsageError("");
271 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
272 UsageError(" method for compiler filter tuning.");
273 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
274 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
275 UsageError("");
276 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
277 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700278 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
279 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800280 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
281 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
282 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100283 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
284 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
285 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
286 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
287 UsageError("");
288 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
289 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
290 UsageError(" Honored only by Optimizing.");
291 UsageError(" Example: --inline-max-code-units=%d",
292 CompilerOptions::kDefaultInlineMaxCodeUnits);
293 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
294 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700295 UsageError(" --dump-timing: display a breakdown of where time was spent");
296 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700297 UsageError(" --include-patch-information: Include patching information so the generated code");
298 UsageError(" can have its base address moved without full recompilation.");
299 UsageError("");
300 UsageError(" --no-include-patch-information: Do not include patching information.");
301 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100302 UsageError(" -g");
303 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
304 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
305 UsageError(" This generates all the available information. Unneeded parts can be");
306 UsageError(" stripped using standard command line tools such as strip or objcopy.");
307 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700308 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100309 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100310 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700311 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
312 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
313 UsageError(" Use a separate --runtime-arg switch for each argument.");
314 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700315 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000316 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700318 UsageError(" --print-pass-names: print a list of pass names");
319 UsageError("");
320 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
321 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
322 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700323 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
324 "with the setting.");
325 UsageError(" Will print default if no overridden setting exists.");
326 UsageError("");
327 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
328 "Pass2Name:Pass2OptionName:Pass2Option#");
329 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
330 UsageError(" Separator used between options is a comma.");
331 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800332 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
333 UsageError(" Example: --swap-file=/data/tmp/swap.001");
334 UsageError("");
335 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
336 UsageError(" Example: --swap-fd=10");
337 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 std::cerr << "See log for usage error information\n";
339 exit(EXIT_FAILURE);
340}
341
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342// The primary goal of the watchdog is to prevent stuck build servers
343// during development when fatal aborts lead to a cascade of failures
344// that result in a deadlock.
345class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800346// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347#undef CHECK_PTHREAD_CALL
348#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
349 do { \
350 int rc = call args; \
351 if (rc != 0) { \
352 errno = rc; \
353 std::string message(# call); \
354 message += " failed for "; \
355 message += reason; \
356 Fatal(message); \
357 } \
358 } while (false)
359
360 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700361 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700362 is_watch_dog_enabled_ = is_watch_dog_enabled;
363 if (!is_watch_dog_enabled_) {
364 return;
365 }
366 shutting_down_ = false;
367 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700368 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
369 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
371 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
372 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
373 }
374 ~WatchDog() {
375 if (!is_watch_dog_enabled_) {
376 return;
377 }
378 const char* reason = "dex2oat watch dog thread shutdown";
379 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
380 shutting_down_ = true;
381 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
382 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
383
Kenny Root51316382014-05-13 14:59:37 -0700384 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385
386 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
387 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
388 }
389
390 private:
391 static void* CallBack(void* arg) {
392 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
393 ::art::SetThreadName("dex2oat watch dog");
394 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700395 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 }
397
Andreas Gampe794ad762015-02-23 08:12:24 -0800398 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700399 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
400 // it's rather easy to hang in unwinding.
401 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
402 // logcat logging or stderr output.
403 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 exit(1);
405 }
406
407 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700408 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
409 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700410 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700411 timespec timeout_ts;
412 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
413 const char* reason = "dex2oat watch dog thread waiting";
414 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
415 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800416 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700417 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700418 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
419 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420 } else if (rc != 0) {
421 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
422 strerror(errno)));
423 Fatal(message.c_str());
424 }
425 }
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
427 }
428
429 // 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 -0700430 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700431 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800432
Andreas Gamped687e372015-04-28 23:16:03 -0700433 // 10 minutes scaled by kSlowdownFactor.
434 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * 10 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700435
436 bool is_watch_dog_enabled_;
437 bool shutting_down_;
438 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
439 pthread_mutex_t mutex_;
440 pthread_cond_t cond_;
441 pthread_attr_t attr_;
442 pthread_t pthread_;
443};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100446 std::string::size_type colon = s.find(c);
447 if (colon == std::string::npos) {
448 Usage("Missing char %c in option %s\n", c, s.c_str());
449 }
450 // Add one to remove the char we were trimming until.
451 *parsed_value = s.substr(colon + 1);
452}
453
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800454static void ParseDouble(const std::string& option, char after_char, double min, double max,
455 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100456 std::string substring;
457 ParseStringAfterChar(option, after_char, &substring);
458 bool sane_val = true;
459 double value;
460 if (false) {
461 // TODO: this doesn't seem to work on the emulator. b/15114595
462 std::stringstream iss(substring);
463 iss >> value;
464 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
465 sane_val = iss.eof() && (value >= min) && (value <= max);
466 } else {
467 char* end = nullptr;
468 value = strtod(substring.c_str(), &end);
469 sane_val = *end == '\0' && value >= min && value <= max;
470 }
471 if (!sane_val) {
472 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
473 }
474 *parsed_value = value;
475}
476
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800477static constexpr size_t kMinDexFilesForSwap = 2;
478static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
479
480static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
481 if (is_image) {
482 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
483 return false;
484 }
485 if (dex_files.size() < kMinDexFilesForSwap) {
486 // If there are less dex files than the threshold, assume it's gonna be fine.
487 return false;
488 }
489 size_t dex_files_size = 0;
490 for (const auto* dex_file : dex_files) {
491 dex_files_size += dex_file->GetHeader().file_size_;
492 }
493 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
494}
495
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800496class Dex2Oat FINAL {
497 public:
498 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800499 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800500 instruction_set_(kRuntimeISA),
501 // Take the default set of instruction features from the build.
502 method_inliner_map_(),
503 runtime_(nullptr),
504 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
505 start_ns_(NanoTime()),
506 oat_fd_(-1),
507 zip_fd_(-1),
508 image_base_(0U),
509 image_classes_zip_filename_(nullptr),
510 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800511 compiled_classes_zip_filename_(nullptr),
512 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700513 compiled_methods_zip_filename_(nullptr),
514 compiled_methods_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800515 image_(false),
516 is_host_(false),
517 dump_stats_(false),
518 dump_passes_(false),
519 dump_timing_(false),
520 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800521 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800522 timings_(timings) {}
523
524 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800525 // Free opened dex files before deleting the runtime_, because ~DexFile
526 // uses MemMap, which is shut down by ~Runtime.
527 class_path_files_.clear();
528 opened_dex_files_.clear();
529
530 // Log completion time before deleting the runtime_, because this accesses
531 // the runtime.
532 LogCompletionTime();
533
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700534 if (kIsDebugBuild || (RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800535 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100536 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700537 }
538
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800539 // Parse the arguments from the command line. In case of an unrecognized option or impossible
540 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
541 // returns, arguments have been successfully parsed.
542 void ParseArgs(int argc, char** argv) {
543 original_argc = argc;
544 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700545
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800546 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700547
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800548 // Skip over argv[0].
549 argv++;
550 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700551
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800552 if (argc == 0) {
553 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700554 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800555
556 std::string oat_symbols;
557 std::string boot_image_filename;
558 const char* compiler_filter_string = nullptr;
559 bool compile_pic = false;
560 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
561 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
562 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
563 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
564 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
Calin Juravleec748352015-07-29 13:52:12 +0100565 int inline_depth_limit = CompilerOptions::kDefaultInlineDepthLimit;
566 int inline_max_code_units = CompilerOptions::kDefaultInlineMaxCodeUnits;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800567
568 // Profile file to use
569 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
570
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800571 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800572 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
David Srbecky8363c772015-05-28 16:12:43 +0100573 bool generate_debug_info = kIsDebugBuild;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800574 bool watch_dog_enabled = true;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800575 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000576 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800577
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800578 PassManagerOptions pass_manager_options;
579
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800580 std::string error_msg;
581
582 for (int i = 0; i < argc; i++) {
583 const StringPiece option(argv[i]);
584 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700585 if (log_options) {
586 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
587 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800588 if (option.starts_with("--dex-file=")) {
589 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
590 } else if (option.starts_with("--dex-location=")) {
591 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
592 } else if (option.starts_with("--zip-fd=")) {
593 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
594 if (!ParseInt(zip_fd_str, &zip_fd_)) {
595 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
596 }
597 if (zip_fd_ < 0) {
598 Usage("--zip-fd passed a negative value %d", zip_fd_);
599 }
600 } else if (option.starts_with("--zip-location=")) {
601 zip_location_ = option.substr(strlen("--zip-location=")).data();
602 } else if (option.starts_with("--oat-file=")) {
603 oat_filename_ = option.substr(strlen("--oat-file=")).data();
604 } else if (option.starts_with("--oat-symbols=")) {
605 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
606 } else if (option.starts_with("--oat-fd=")) {
607 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
608 if (!ParseInt(oat_fd_str, &oat_fd_)) {
609 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
610 }
611 if (oat_fd_ < 0) {
612 Usage("--oat-fd passed a negative value %d", oat_fd_);
613 }
614 } else if (option == "--watch-dog") {
615 watch_dog_enabled = true;
616 } else if (option == "--no-watch-dog") {
617 watch_dog_enabled = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800618 } else if (option.starts_with("-j")) {
619 const char* thread_count_str = option.substr(strlen("-j")).data();
620 if (!ParseUint(thread_count_str, &thread_count_)) {
621 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
622 }
623 } else if (option.starts_with("--oat-location=")) {
624 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800625 } else if (option.starts_with("--image=")) {
626 image_filename_ = option.substr(strlen("--image=")).data();
627 } else if (option.starts_with("--image-classes=")) {
628 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
629 } else if (option.starts_with("--image-classes-zip=")) {
630 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800631 } else if (option.starts_with("--compiled-classes=")) {
632 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
633 } else if (option.starts_with("--compiled-classes-zip=")) {
634 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700635 } else if (option.starts_with("--compiled-methods=")) {
636 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
637 } else if (option.starts_with("--compiled-methods-zip=")) {
638 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800639 } else if (option.starts_with("--base=")) {
640 const char* image_base_str = option.substr(strlen("--base=")).data();
641 char* end;
642 image_base_ = strtoul(image_base_str, &end, 16);
643 if (end == image_base_str || *end != '\0') {
644 Usage("Failed to parse hexadecimal value for option %s", option.data());
645 }
646 } else if (option.starts_with("--boot-image=")) {
647 boot_image_filename = option.substr(strlen("--boot-image=")).data();
648 } else if (option.starts_with("--android-root=")) {
649 android_root_ = option.substr(strlen("--android-root=")).data();
650 } else if (option.starts_with("--instruction-set=")) {
651 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
652 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800653 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800654 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
655 buf.get()[instruction_set_str.length()] = 0;
656 instruction_set_ = GetInstructionSetFromString(buf.get());
657 // arm actually means thumb2.
658 if (instruction_set_ == InstructionSet::kArm) {
659 instruction_set_ = InstructionSet::kThumb2;
660 }
661 } else if (option.starts_with("--instruction-set-variant=")) {
662 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
663 instruction_set_features_.reset(
664 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
665 if (instruction_set_features_.get() == nullptr) {
666 Usage("%s", error_msg.c_str());
667 }
668 } else if (option.starts_with("--instruction-set-features=")) {
669 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800670 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800671 instruction_set_features_.reset(
672 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
673 if (instruction_set_features_.get() == nullptr) {
674 Usage("Problem initializing default instruction set features variant: %s",
675 error_msg.c_str());
676 }
677 }
678 instruction_set_features_.reset(
679 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
680 if (instruction_set_features_.get() == nullptr) {
681 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682 }
683 } else if (option.starts_with("--compiler-backend=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000684 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800685 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
686 if (backend_str == "Quick") {
687 compiler_kind_ = Compiler::kQuick;
688 } else if (backend_str == "Optimizing") {
689 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 } else {
691 Usage("Unknown compiler backend: %s", backend_str.data());
692 }
693 } else if (option.starts_with("--compiler-filter=")) {
694 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
695 } else if (option == "--compile-pic") {
696 compile_pic = true;
697 } else if (option.starts_with("--huge-method-max=")) {
698 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
699 if (!ParseInt(threshold, &huge_method_threshold)) {
700 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
701 }
702 if (huge_method_threshold < 0) {
703 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
704 }
705 } else if (option.starts_with("--large-method-max=")) {
706 const char* threshold = option.substr(strlen("--large-method-max=")).data();
707 if (!ParseInt(threshold, &large_method_threshold)) {
708 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
709 }
710 if (large_method_threshold < 0) {
711 Usage("--large-method-max passed a negative value %s", large_method_threshold);
712 }
713 } else if (option.starts_with("--small-method-max=")) {
714 const char* threshold = option.substr(strlen("--small-method-max=")).data();
715 if (!ParseInt(threshold, &small_method_threshold)) {
716 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
717 }
718 if (small_method_threshold < 0) {
719 Usage("--small-method-max passed a negative value %s", small_method_threshold);
720 }
721 } else if (option.starts_with("--tiny-method-max=")) {
722 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
723 if (!ParseInt(threshold, &tiny_method_threshold)) {
724 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
725 }
726 if (tiny_method_threshold < 0) {
727 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
728 }
729 } else if (option.starts_with("--num-dex-methods=")) {
730 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
731 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
732 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
733 }
734 if (num_dex_methods_threshold < 0) {
735 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
736 }
Calin Juravleec748352015-07-29 13:52:12 +0100737 } else if (option.starts_with("--inline-depth-limit=")) {
738 const char* limit = option.substr(strlen("--inline-depth-limit=")).data();
739 if (!ParseInt(limit, &inline_depth_limit)) {
740 Usage("Failed to parse --inline-depth-limit '%s' as an integer", limit);
741 }
742 if (inline_depth_limit < 0) {
743 Usage("--inline-depth-limit passed a negative value %s", inline_depth_limit);
744 }
745 } else if (option.starts_with("--inline-max-code-units=")) {
746 const char* code_units = option.substr(strlen("--inline-max-code-units=")).data();
747 if (!ParseInt(code_units, &inline_max_code_units)) {
748 Usage("Failed to parse --inline-max-code-units '%s' as an integer", code_units);
749 }
750 if (inline_max_code_units < 0) {
751 Usage("--inline-max-code-units passed a negative value %s", inline_max_code_units);
752 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800753 } else if (option == "--host") {
754 is_host_ = true;
755 } else if (option == "--runtime-arg") {
756 if (++i >= argc) {
757 Usage("Missing required argument for --runtime-arg");
758 }
759 if (log_options) {
760 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
761 }
762 runtime_args_.push_back(argv[i]);
763 } else if (option == "--dump-timing") {
764 dump_timing_ = true;
765 } else if (option == "--dump-passes") {
766 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000767 } else if (option.starts_with("--dump-cfg=")) {
768 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800769 } else if (option == "--dump-stats") {
770 dump_stats_ = true;
David Srbecky8363c772015-05-28 16:12:43 +0100771 } else if (option == "--generate-debug-info" || option == "-g") {
772 generate_debug_info = true;
773 } else if (option == "--no-generate-debug-info") {
774 generate_debug_info = false;
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800775 } else if (option == "--debuggable") {
776 debuggable = true;
David Srbecky8363c772015-05-28 16:12:43 +0100777 generate_debug_info = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800778 } else if (option.starts_with("--profile-file=")) {
779 profile_file_ = option.substr(strlen("--profile-file=")).data();
780 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
781 } else if (option == "--no-profile-file") {
782 // No profile
783 } else if (option.starts_with("--top-k-profile-threshold=")) {
784 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
785 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800786 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800787 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800788 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
789 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800790 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800791 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
792 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800793 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800794 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800796 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
797 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800799 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800800 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800801 const std::string options = option.substr(strlen("--pass-options=")).data();
802 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800803 } else if (option == "--include-patch-information") {
804 include_patch_information = true;
805 } else if (option == "--no-include-patch-information") {
806 include_patch_information = false;
807 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800808 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
809 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800810 gLogVerbosity.compiler = false;
811 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800812 } else if (option.starts_with("--dump-init-failures=")) {
813 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
814 init_failure_output_.reset(new std::ofstream(file_name));
815 if (init_failure_output_.get() == nullptr) {
816 LOG(ERROR) << "Failed to allocate ofstream";
817 } else if (init_failure_output_->fail()) {
818 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
819 << "failures.";
820 init_failure_output_.reset();
821 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800822 } else if (option.starts_with("--swap-file=")) {
823 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
824 } else if (option.starts_with("--swap-fd=")) {
825 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
826 if (!ParseInt(swap_fd_str, &swap_fd_)) {
827 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
828 }
829 if (swap_fd_ < 0) {
830 Usage("--swap-fd passed a negative value %d", swap_fd_);
831 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800832 } else if (option == "--abort-on-hard-verifier-error") {
833 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800834 } else {
835 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800837 }
838
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000839 image_ = (!image_filename_.empty());
840 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
841 // If no specific compiler is requested, the current behavior is
842 // to compile the boot image with Quick, and the rest with Optimizing.
843 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
844 }
845
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000846 if (compiler_kind_ == Compiler::kOptimizing) {
847 // Optimizing only supports PIC mode.
848 compile_pic = true;
849 }
850
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800851 if (oat_filename_.empty() && oat_fd_ == -1) {
852 Usage("Output must be supplied with either --oat-file or --oat-fd");
853 }
854
855 if (!oat_filename_.empty() && oat_fd_ != -1) {
856 Usage("--oat-file should not be used with --oat-fd");
857 }
858
859 if (!oat_symbols.empty() && oat_fd_ != -1) {
860 Usage("--oat-symbols should not be used with --oat-fd");
861 }
862
863 if (!oat_symbols.empty() && is_host_) {
864 Usage("--oat-symbols should not be used with --host");
865 }
866
867 if (oat_fd_ != -1 && !image_filename_.empty()) {
868 Usage("--oat-fd should not be used with --image");
869 }
870
871 if (android_root_.empty()) {
872 const char* android_root_env_var = getenv("ANDROID_ROOT");
873 if (android_root_env_var == nullptr) {
874 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800876 android_root_ += android_root_env_var;
877 }
878
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800879 if (!image_ && boot_image_filename.empty()) {
880 boot_image_filename += android_root_;
881 boot_image_filename += "/framework/boot.art";
882 }
883 if (!boot_image_filename.empty()) {
884 boot_image_option_ += "-Ximage:";
885 boot_image_option_ += boot_image_filename;
886 }
887
888 if (image_classes_filename_ != nullptr && !image_) {
889 Usage("--image-classes should only be used with --image");
890 }
891
892 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
893 Usage("--image-classes should not be used with --boot-image");
894 }
895
896 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
897 Usage("--image-classes-zip should be used with --image-classes");
898 }
899
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800900 if (compiled_classes_filename_ != nullptr && !image_) {
901 Usage("--compiled-classes should only be used with --image");
902 }
903
904 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
905 Usage("--compiled-classes should not be used with --boot-image");
906 }
907
908 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
909 Usage("--compiled-classes-zip should be used with --compiled-classes");
910 }
911
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800912 if (dex_filenames_.empty() && zip_fd_ == -1) {
913 Usage("Input must be supplied with either --dex-file or --zip-fd");
914 }
915
916 if (!dex_filenames_.empty() && zip_fd_ != -1) {
917 Usage("--dex-file should not be used with --zip-fd");
918 }
919
920 if (!dex_filenames_.empty() && !zip_location_.empty()) {
921 Usage("--dex-file should not be used with --zip-location");
922 }
923
924 if (dex_locations_.empty()) {
925 for (const char* dex_file_name : dex_filenames_) {
926 dex_locations_.push_back(dex_file_name);
927 }
928 } else if (dex_locations_.size() != dex_filenames_.size()) {
929 Usage("--dex-location arguments do not match --dex-file arguments");
930 }
931
932 if (zip_fd_ != -1 && zip_location_.empty()) {
933 Usage("--zip-location should be supplied with --zip-fd");
934 }
935
936 if (boot_image_option_.empty()) {
937 if (image_base_ == 0) {
938 Usage("Non-zero --base not specified");
939 }
940 }
941
942 oat_stripped_ = oat_filename_;
943 if (!oat_symbols.empty()) {
944 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700945 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800946 oat_unstripped_ = oat_filename_;
947 }
948
949 // If no instruction set feature was given, use the default one for the target
950 // instruction set.
951 if (instruction_set_features_.get() == nullptr) {
952 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800953 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
954 if (instruction_set_features_.get() == nullptr) {
955 Usage("Problem initializing default instruction set features variant: %s",
956 error_msg.c_str());
957 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800958 }
959
960 if (instruction_set_ == kRuntimeISA) {
961 std::unique_ptr<const InstructionSetFeatures> runtime_features(
962 InstructionSetFeatures::FromCppDefines());
963 if (!instruction_set_features_->Equals(runtime_features.get())) {
964 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
965 << *instruction_set_features_ << ") and those of dex2oat executable ("
966 << *runtime_features <<") for the command line:\n"
967 << CommandLine();
968 }
969 }
970
971 if (compiler_filter_string == nullptr) {
Douglas Leung027f0ff2015-02-27 19:05:03 -0800972 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100974
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800975 CHECK(compiler_filter_string != nullptr);
976 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
977 if (strcmp(compiler_filter_string, "verify-none") == 0) {
978 compiler_filter = CompilerOptions::kVerifyNone;
979 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
980 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700981 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
982 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800983 } else if (strcmp(compiler_filter_string, "space") == 0) {
984 compiler_filter = CompilerOptions::kSpace;
985 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
986 compiler_filter = CompilerOptions::kBalanced;
987 } else if (strcmp(compiler_filter_string, "speed") == 0) {
988 compiler_filter = CompilerOptions::kSpeed;
989 } else if (strcmp(compiler_filter_string, "everything") == 0) {
990 compiler_filter = CompilerOptions::kEverything;
991 } else if (strcmp(compiler_filter_string, "time") == 0) {
992 compiler_filter = CompilerOptions::kTime;
993 } else {
994 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
995 }
996
997 // Checks are all explicit until we know the architecture.
998 bool implicit_null_checks = false;
999 bool implicit_so_checks = false;
1000 bool implicit_suspend_checks = false;
1001 // Set the compilation target's implicit checks options.
1002 switch (instruction_set_) {
1003 case kArm:
1004 case kThumb2:
1005 case kArm64:
1006 case kX86:
1007 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -07001008 case kMips:
1009 case kMips64:
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001010 implicit_null_checks = true;
1011 implicit_so_checks = true;
1012 break;
1013
1014 default:
1015 // Defaults are correct.
1016 break;
1017 }
1018
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001019 compiler_options_.reset(new CompilerOptions(compiler_filter,
1020 huge_method_threshold,
1021 large_method_threshold,
1022 small_method_threshold,
1023 tiny_method_threshold,
1024 num_dex_methods_threshold,
Calin Juravleec748352015-07-29 13:52:12 +01001025 inline_depth_limit,
1026 inline_max_code_units,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001027 include_patch_information,
1028 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -08001029 debuggable,
David Srbecky8363c772015-05-28 16:12:43 +01001030 generate_debug_info,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001031 implicit_null_checks,
1032 implicit_so_checks,
1033 implicit_suspend_checks,
1034 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001035 verbose_methods_.empty() ?
1036 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -08001037 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -08001038 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -08001039 init_failure_output_.get(),
1040 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001041
1042 // Done with usage checks, enable watchdog if requested
1043 if (watch_dog_enabled) {
1044 watchdog_.reset(new WatchDog(true));
1045 }
1046
1047 // Fill some values into the key-value store for the oat header.
1048 key_value_store_.reset(new SafeMap<std::string, std::string>());
1049
1050 // Insert some compiler things.
1051 {
1052 std::ostringstream oss;
1053 for (int i = 0; i < argc; ++i) {
1054 if (i > 0) {
1055 oss << ' ';
1056 }
1057 oss << argv[i];
1058 }
1059 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1060 oss.str(""); // Reset.
1061 oss << kRuntimeISA;
1062 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
Sebastien Hertz0de11332015-05-13 12:14:05 +02001063 key_value_store_->Put(OatHeader::kPicKey,
1064 compile_pic ? OatHeader::kTrueValue : OatHeader::kFalseValue);
1065 key_value_store_->Put(OatHeader::kDebuggableKey,
1066 debuggable ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001067 }
1068 }
1069
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001070 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
1071 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001072 bool OpenFile() {
1073 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
1074 if (create_file) {
1075 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
1076 if (oat_location_.empty()) {
1077 oat_location_ = oat_filename_;
1078 }
1079 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001080 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001081 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001082 if (oat_file_->SetLength(0) != 0) {
1083 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1084 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001085 }
1086 if (oat_file_.get() == nullptr) {
1087 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1088 return false;
1089 }
1090 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1091 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001092 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001093 return false;
1094 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001095
1096 // Swap file handling.
1097 //
1098 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1099 // that we can use for swap.
1100 //
1101 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1102 // will immediately unlink to satisfy the swap fd assumption.
1103 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1104 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1105 if (swap_file.get() == nullptr) {
1106 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1107 return false;
1108 }
1109 swap_fd_ = swap_file->Fd();
1110 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1111 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1112 // released immediately.
1113 unlink(swap_file_name_.c_str());
1114 }
1115
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001116 return true;
1117 }
1118
Andreas Gampea650e702014-12-03 14:28:02 -08001119 void EraseOatFile() {
1120 DCHECK(oat_file_.get() != nullptr);
1121 oat_file_->Erase();
1122 oat_file_.reset();
1123 }
1124
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001125 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1126 // boot class path.
1127 bool Setup() {
1128 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1129 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1131 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001132 std::string boot_class_path = "-Xbootclasspath:";
1133 boot_class_path += Join(dex_filenames_, ':');
1134 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1135 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1136 boot_class_path_locations += Join(dex_locations_, ':');
1137 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001138 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001139 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 }
1141 for (size_t i = 0; i < runtime_args_.size(); i++) {
1142 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001143 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001144
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001145 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001146 callbacks_.reset(new QuickCompilerCallbacks(
1147 verification_results_.get(),
1148 &method_inliner_map_,
1149 image_ ?
1150 CompilerCallbacks::CallbackMode::kCompileBootImage :
1151 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001152 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1153 runtime_options.push_back(
1154 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1155
Andreas Gampe1d00add2015-02-27 19:35:46 -08001156 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1157 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1158 // have been stripped in preopting, anyways).
1159 if (!image_) {
1160 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1161 }
Calin Juravle01aaf6e2015-06-19 22:05:39 +01001162 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1163 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1164 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Andreas Gampe1d00add2015-02-27 19:35:46 -08001165
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001166 if (!CreateRuntime(runtime_options)) {
1167 return false;
1168 }
1169
1170 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1171 // Runtime::Start, give it away now so that we don't starve GC.
1172 Thread* self = Thread::Current();
1173 self->TransitionFromRunnableToSuspended(kNative);
1174 // If we're doing the image, override the compiler filter to force full compilation. Must be
1175 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1176 // compilation of class initializers.
1177 // Whilst we're in native take the opportunity to initialize well known classes.
1178 WellKnownClasses::Init(self->GetJniEnv());
1179
1180 // If --image-classes was specified, calculate the full list of classes to include in the image
1181 if (image_classes_filename_ != nullptr) {
1182 std::string error_msg;
1183 if (image_classes_zip_filename_ != nullptr) {
1184 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001185 image_classes_filename_,
1186 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001187 } else {
1188 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1189 }
1190 if (image_classes_.get() == nullptr) {
1191 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1192 "': " << error_msg;
1193 return false;
1194 }
1195 } else if (image_) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001196 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001197 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001198 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1199 // image.
1200 if (compiled_classes_filename_ != nullptr) {
1201 std::string error_msg;
1202 if (compiled_classes_zip_filename_ != nullptr) {
1203 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1204 compiled_classes_filename_,
1205 &error_msg));
1206 } else {
1207 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1208 }
1209 if (compiled_classes_.get() == nullptr) {
1210 LOG(ERROR) << "Failed to create list of compiled classes from '"
1211 << compiled_classes_filename_ << "': " << error_msg;
1212 return false;
1213 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001214 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001215 compiled_classes_.reset(nullptr); // By default compile everything.
1216 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001217 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1218 if (compiled_methods_filename_ != nullptr) {
1219 std::string error_msg;
1220 if (compiled_methods_zip_filename_ != nullptr) {
1221 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1222 compiled_methods_filename_,
1223 nullptr, // No post-processing.
1224 &error_msg));
1225 } else {
1226 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1227 nullptr)); // No post-processing.
1228 }
1229 if (compiled_methods_.get() == nullptr) {
1230 LOG(ERROR) << "Failed to create list of compiled methods from '"
1231 << compiled_methods_filename_ << "': " << error_msg;
1232 return false;
1233 }
1234 } else {
1235 compiled_methods_.reset(nullptr); // By default compile everything.
1236 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001237
1238 if (boot_image_option_.empty()) {
1239 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1240 } else {
1241 if (dex_filenames_.empty()) {
1242 ATRACE_BEGIN("Opening zip archive from file descriptor");
1243 std::string error_msg;
1244 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1245 zip_location_.c_str(),
1246 &error_msg));
1247 if (zip_archive.get() == nullptr) {
1248 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1249 << error_msg;
1250 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001251 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001252 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1254 << "': " << error_msg;
1255 return false;
1256 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001257 for (auto& dex_file : opened_dex_files_) {
1258 dex_files_.push_back(dex_file.get());
1259 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001260 ATRACE_END();
1261 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001262 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001263 if (failure_count > 0) {
1264 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1265 return false;
1266 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001267 for (auto& dex_file : opened_dex_files_) {
1268 dex_files_.push_back(dex_file.get());
1269 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001270 }
1271
1272 constexpr bool kSaveDexInput = false;
1273 if (kSaveDexInput) {
1274 for (size_t i = 0; i < dex_files_.size(); ++i) {
1275 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001276 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1277 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001278 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1279 if (tmp_file.get() == nullptr) {
1280 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1281 << ". Try: adb shell chmod 777 /data/local/tmp";
1282 continue;
1283 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001284 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1285 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1286 UNUSED(tmp_file->Flush());
1287 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001288 LOG(INFO) << "Wrote input to " << tmp_file_name;
1289 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001290 }
1291 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001292 // Ensure opened dex files are writable for dex-to-dex transformations.
1293 for (const auto& dex_file : dex_files_) {
1294 if (!dex_file->EnableWrite()) {
1295 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001296 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001297 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001298
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001299 // If we use a swap file, ensure we are above the threshold to make it necessary.
1300 if (swap_fd_ != -1) {
1301 if (!UseSwap(image_, dex_files_)) {
1302 close(swap_fd_);
1303 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001304 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001305 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001306 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001307 }
1308 }
1309 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1310
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001311 /*
1312 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1313 * Don't bother to check if we're doing the image.
1314 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001315 if (!image_ &&
1316 compiler_options_->IsCompilationEnabled() &&
1317 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001318 size_t num_methods = 0;
1319 for (size_t i = 0; i != dex_files_.size(); ++i) {
1320 const DexFile* dex_file = dex_files_[i];
1321 CHECK(dex_file != nullptr);
1322 num_methods += dex_file->NumMethodIds();
1323 }
1324 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1325 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1326 VLOG(compiler) << "Below method threshold, compiling anyways";
1327 }
1328 }
1329
1330 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001331 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001332
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001333 // Create and invoke the compiler driver. This will compile all the dex files.
1334 void Compile() {
1335 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1336 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001337
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001338 // Handle and ClassLoader creation needs to come after Runtime::Create
1339 jobject class_loader = nullptr;
1340 Thread* self = Thread::Current();
1341 if (!boot_image_option_.empty()) {
1342 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001343 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001344 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001345
1346 // Classpath: first the class-path given.
1347 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001348 for (auto& class_path_file : class_path_files_) {
1349 class_path_files.push_back(class_path_file.get());
1350 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001351
1352 // Store the classpath we have right now.
1353 key_value_store_->Put(OatHeader::kClassPathKey,
1354 OatFile::EncodeDexFileDependencies(class_path_files));
1355
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001356 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1357 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001358
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001359 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001360 }
1361
1362 driver_.reset(new CompilerDriver(compiler_options_.get(),
1363 verification_results_.get(),
1364 &method_inliner_map_,
1365 compiler_kind_,
1366 instruction_set_,
1367 instruction_set_features_.get(),
1368 image_,
1369 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001370 compiled_classes_.release(),
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001371 nullptr,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001372 thread_count_,
1373 dump_stats_,
1374 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001375 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001376 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001377 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001378 profile_file_));
1379
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001380 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001381 }
1382
Brian Carlstrom7940e442013-07-12 13:46:57 -07001383 // Notes on the interleaving of creating the image and oat file to
1384 // ensure the references between the two are correct.
1385 //
1386 // Currently we have a memory layout that looks something like this:
1387 //
1388 // +--------------+
1389 // | image |
1390 // +--------------+
1391 // | boot oat |
1392 // +--------------+
1393 // | alloc spaces |
1394 // +--------------+
1395 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001396 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397 //
1398 // 1. The image is expected to be loaded at an absolute address and
1399 // contains Objects with absolute pointers within the image.
1400 //
1401 // 2. There are absolute pointers from Methods in the image to their
1402 // code in the oat.
1403 //
1404 // 3. There are absolute pointers from the code in the oat to Methods
1405 // in the image.
1406 //
1407 // 4. There are absolute pointers from code in the oat to other code
1408 // in the oat.
1409 //
1410 // To get this all correct, we go through several steps.
1411 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001412 // 1. We prepare offsets for all data in the oat file and calculate
1413 // the oat data size and code size. During this stage, we also set
1414 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001415 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001416 // 2. We prepare offsets for the objects in the image and calculate
1417 // the image size.
1418 //
1419 // 3. We create the oat file. Originally this was just our own proprietary
1420 // file but now it is contained within an ELF dynamic object (aka an .so
1421 // file). Since we know the image size and oat data size and code size we
1422 // can prepare the ELF headers and we then know the ELF memory segment
1423 // layout and we can now resolve all references. The compiler provides
1424 // LinkerPatch information in each CompiledMethod and we resolve these,
1425 // using the layout information and image object locations provided by
1426 // image writer, as we're writing the method code.
1427 //
1428 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 // will be loaded after itself. Originally when oat file was simply
1430 // memory mapped so we could predict where its contents were based
1431 // on the file size. Now that it is an ELF file, we need to inspect
1432 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001433 // where the oat header is located within.
1434 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001435 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001436 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001437 // load the .so at the desired location at runtime by offsetting the
1438 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001439 // TODO: Do this in step 3. We already know the layout there.
1440 //
1441 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1442 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001443
1444
1445 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1446 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001447 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1448 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001449 bool CreateOatFile() {
1450 CHECK(key_value_store_.get() != nullptr);
1451
1452 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1453
1454 std::unique_ptr<OatWriter> oat_writer;
1455 {
1456 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1457 std::string image_file_location;
1458 uint32_t image_file_location_oat_checksum = 0;
1459 uintptr_t image_file_location_oat_data_begin = 0;
1460 int32_t image_patch_delta = 0;
1461 if (image_) {
1462 PrepareImageWriter(image_base_);
1463 } else {
1464 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1465 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1466 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1467 image_file_location_oat_data_begin =
1468 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1469 image_file_location = image_space->GetImageFilename();
1470 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1471 }
1472
1473 if (!image_file_location.empty()) {
1474 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1475 }
1476
1477 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1478 image_file_location_oat_data_begin,
1479 image_patch_delta,
1480 driver_.get(),
1481 image_writer_.get(),
1482 timings_,
1483 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001484 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001485
1486 if (image_) {
1487 // The OatWriter constructor has already updated offsets in methods and we need to
1488 // prepare method offsets in the image address space for direct method patching.
1489 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1490 if (!image_writer_->PrepareImageAddressSpace()) {
1491 LOG(ERROR) << "Failed to prepare image address space.";
1492 return false;
1493 }
1494 }
1495
1496 {
1497 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1498 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1499 oat_file_.get())) {
1500 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1501 return false;
1502 }
1503 }
1504
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001505 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1506 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001507 }
1508
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001509 // If we are compiling an image, invoke the image creation routine. Else just skip.
1510 bool HandleImage() {
1511 if (image_) {
1512 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1513 if (!CreateImageFile()) {
1514 return false;
1515 }
1516 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001517 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001518 return true;
1519 }
1520
Andreas Gampe10e477d2014-11-19 12:57:42 -08001521 // Create a copy from unstripped to stripped.
1522 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001523 // If we don't want to strip in place, copy from unstripped location to stripped location.
1524 // We need to strip after image creation because FixupElf needs to use .strtab.
1525 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001526 // If the oat file is still open, flush it.
1527 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1528 if (!FlushCloseOatFile()) {
1529 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001530 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001531 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001532
1533 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001534 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1535 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1536 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001537 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001538 while (true) {
1539 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1540 if (bytes_read <= 0) {
1541 break;
1542 }
1543 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1544 CHECK(write_ok);
1545 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001546 if (out->FlushCloseOrErase() != 0) {
1547 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1548 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001549 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001550 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001551 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001552 return true;
1553 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001554
Andreas Gampe10e477d2014-11-19 12:57:42 -08001555 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001556 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001557 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1558 if (oat_file_->Flush() != 0) {
1559 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1560 << oat_filename_;
1561 oat_file_->Erase();
1562 return false;
1563 }
1564 }
1565 return true;
1566 }
1567
1568 bool FlushCloseOatFile() {
1569 if (oat_file_.get() != nullptr) {
1570 std::unique_ptr<File> tmp(oat_file_.release());
1571 if (tmp->FlushCloseOrErase() != 0) {
1572 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1573 << oat_filename_;
1574 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001575 }
1576 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001577 return true;
1578 }
1579
1580 void DumpTiming() {
1581 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1582 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1583 }
1584 if (dump_passes_) {
1585 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1586 }
1587 }
1588
1589 CompilerOptions* GetCompilerOptions() const {
1590 return compiler_options_.get();
1591 }
1592
Andreas Gampe10e477d2014-11-19 12:57:42 -08001593 bool IsImage() const {
1594 return image_;
1595 }
1596
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001597 bool IsHost() const {
1598 return is_host_;
1599 }
1600
1601 private:
1602 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1603 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001604 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001605 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001606 size_t failure_count = 0;
1607 for (size_t i = 0; i < dex_filenames.size(); i++) {
1608 const char* dex_filename = dex_filenames[i];
1609 const char* dex_location = dex_locations[i];
1610 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1611 std::string error_msg;
1612 if (!OS::FileExists(dex_filename)) {
1613 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1614 continue;
1615 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001616 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001617 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1618 ++failure_count;
1619 }
1620 ATRACE_END();
1621 }
1622 return failure_count;
1623 }
1624
Andreas Gampee3712d02015-04-09 14:46:31 -07001625 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1626 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1627 // efficient, but under normal circumstances the list is neither large nor is this part too
1628 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001629 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1630 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001631 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001633 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1634 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001635 return true;
1636 }
1637 }
1638 return false;
1639 }
1640
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001641 // Appends to opened_dex_files any elements of class_path that dex_files
1642 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001643 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001644 std::vector<const DexFile*> dex_files,
1645 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001646 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001647 std::vector<std::string> parsed;
1648 Split(class_path, ':', &parsed);
1649 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1650 ScopedObjectAccess soa(Thread::Current());
1651 for (size_t i = 0; i < parsed.size(); ++i) {
1652 if (DexFilesContains(dex_files, parsed[i])) {
1653 continue;
1654 }
1655 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001656 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001657 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1658 }
1659 }
1660 }
1661
1662 // Create a runtime necessary for compilation.
1663 bool CreateRuntime(const RuntimeOptions& runtime_options)
1664 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1665 if (!Runtime::Create(runtime_options, false)) {
1666 LOG(ERROR) << "Failed to create runtime";
1667 return false;
1668 }
1669 Runtime* runtime = Runtime::Current();
1670 runtime->SetInstructionSet(instruction_set_);
1671 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1672 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1673 if (!runtime->HasCalleeSaveMethod(type)) {
1674 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1675 }
1676 }
1677 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001678
1679 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1680 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001681 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001682
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001683 runtime->GetClassLinker()->RunRootClinits();
1684 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001685
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001686 return true;
1687 }
1688
1689 void PrepareImageWriter(uintptr_t image_base) {
1690 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1691 }
1692
1693 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1694 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001695 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001696 CHECK(image_writer_ != nullptr);
1697 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1698 LOG(ERROR) << "Failed to create image file " << image_filename_;
1699 return false;
1700 }
1701 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1702
1703 // Destroy ImageWriter before doing FixupElf.
1704 image_writer_.reset();
1705
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001706 // Do not fix up the ELF file if we are --compile-pic
1707 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001708 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1709 if (oat_file.get() == nullptr) {
1710 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1711 return false;
1712 }
1713
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001714 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001715 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001716 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1717 return false;
1718 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001719
1720 if (oat_file->FlushCloseOrErase()) {
1721 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1722 return false;
1723 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001724 }
1725
1726 return true;
1727 }
1728
1729 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001730 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1731 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001732 std::function<std::string(const char*)> process = DotToDescriptor;
1733 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001734 }
1735
1736 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001737 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001738 const char* zip_filename,
1739 const char* image_classes_filename,
1740 std::string* error_msg) {
1741 std::function<std::string(const char*)> process = DotToDescriptor;
1742 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1743 }
1744
1745 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1746 // the given function.
1747 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1748 const char* input_filename, std::function<std::string(const char*)>* process) {
1749 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1750 if (input_file.get() == nullptr) {
1751 LOG(ERROR) << "Failed to open input file " << input_filename;
1752 return nullptr;
1753 }
1754 std::unique_ptr<std::unordered_set<std::string>> result(
1755 ReadCommentedInputStream(*input_file, process));
1756 input_file->close();
1757 return result.release();
1758 }
1759
1760 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1761 // Post-process each line with the given function.
1762 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001763 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001764 const char* input_filename,
1765 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001766 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001767 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1768 if (zip_archive.get() == nullptr) {
1769 return nullptr;
1770 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001771 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001772 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001773 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001774 zip_filename, error_msg->c_str());
1775 return nullptr;
1776 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001777 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1778 input_filename,
1779 error_msg));
1780 if (input_file.get() == nullptr) {
1781 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001782 zip_filename, error_msg->c_str());
1783 return nullptr;
1784 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001785 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1786 input_file->Size());
1787 std::istringstream input_stream(input_string);
1788 return ReadCommentedInputStream(input_stream, process);
1789 }
1790
1791 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1792 // with the given function.
1793 static std::unordered_set<std::string>* ReadCommentedInputStream(
1794 std::istream& in_stream,
1795 std::function<std::string(const char*)>* process) {
1796 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1797 new std::unordered_set<std::string>);
1798 while (in_stream.good()) {
1799 std::string dot;
1800 std::getline(in_stream, dot);
1801 if (StartsWith(dot, "#") || dot.empty()) {
1802 continue;
1803 }
1804 if (process != nullptr) {
1805 std::string descriptor((*process)(dot.c_str()));
1806 image_classes->insert(descriptor);
1807 } else {
1808 image_classes->insert(dot);
1809 }
1810 }
1811 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001812 }
1813
Mathieu Chartier49285c52014-12-02 15:43:48 -08001814 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001815 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1816 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001817 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001818 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001819 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001820 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001821 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1822 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001823 }
1824
1825 std::unique_ptr<CompilerOptions> compiler_options_;
1826 Compiler::Kind compiler_kind_;
1827
1828 InstructionSet instruction_set_;
1829 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1830
1831 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1832
1833 std::unique_ptr<VerificationResults> verification_results_;
1834 DexFileToMethodInlinerMap method_inliner_map_;
1835 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1836
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001837 // Ownership for the class path files.
1838 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1839
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001840 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1841 // in an orderly fashion. The destructor takes care of deleting this.
1842 Runtime* runtime_;
1843
1844 size_t thread_count_;
1845 uint64_t start_ns_;
1846 std::unique_ptr<WatchDog> watchdog_;
1847 std::unique_ptr<File> oat_file_;
1848 std::string oat_stripped_;
1849 std::string oat_unstripped_;
1850 std::string oat_location_;
1851 std::string oat_filename_;
1852 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001853 std::vector<const char*> dex_filenames_;
1854 std::vector<const char*> dex_locations_;
1855 int zip_fd_;
1856 std::string zip_location_;
1857 std::string boot_image_option_;
1858 std::vector<const char*> runtime_args_;
1859 std::string image_filename_;
1860 uintptr_t image_base_;
1861 const char* image_classes_zip_filename_;
1862 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001863 const char* compiled_classes_zip_filename_;
1864 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001865 const char* compiled_methods_zip_filename_;
1866 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001867 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1868 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001869 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001870 bool image_;
1871 std::unique_ptr<ImageWriter> image_writer_;
1872 bool is_host_;
1873 std::string android_root_;
1874 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001875 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001876 std::unique_ptr<CompilerDriver> driver_;
1877 std::vector<std::string> verbose_methods_;
1878 bool dump_stats_;
1879 bool dump_passes_;
1880 bool dump_timing_;
1881 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001882 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001883 std::string swap_file_name_;
1884 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001885 std::string profile_file_; // Profile file to use
1886 TimingLogger* timings_;
1887 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001888 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001889
1890 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1891};
1892
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001893static void b13564922() {
1894#if defined(__linux__) && defined(__arm__)
1895 int major, minor;
1896 struct utsname uts;
1897 if (uname(&uts) != -1 &&
1898 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1899 ((major < 3) || ((major == 3) && (minor < 4)))) {
1900 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1901 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1902 int old_personality = personality(0xffffffff);
1903 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1904 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1905 if (new_personality == -1) {
1906 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1907 }
1908 }
1909 }
1910#endif
1911}
1912
Andreas Gampe10e477d2014-11-19 12:57:42 -08001913static int CompileImage(Dex2Oat& dex2oat) {
1914 dex2oat.Compile();
1915
1916 // Create the boot.oat.
1917 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001918 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001919 return EXIT_FAILURE;
1920 }
1921
1922 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1923 // re-opened from the unstripped name.
1924 if (!dex2oat.FlushCloseOatFile()) {
1925 return EXIT_FAILURE;
1926 }
1927
1928 // Creates the boot.art and patches the boot.oat.
1929 if (!dex2oat.HandleImage()) {
1930 return EXIT_FAILURE;
1931 }
1932
1933 // When given --host, finish early without stripping.
1934 if (dex2oat.IsHost()) {
1935 dex2oat.DumpTiming();
1936 return EXIT_SUCCESS;
1937 }
1938
1939 // Copy unstripped to stripped location, if necessary.
1940 if (!dex2oat.CopyUnstrippedToStripped()) {
1941 return EXIT_FAILURE;
1942 }
1943
Andreas Gampe10e477d2014-11-19 12:57:42 -08001944 // FlushClose again, as stripping might have re-opened the oat file.
1945 if (!dex2oat.FlushCloseOatFile()) {
1946 return EXIT_FAILURE;
1947 }
1948
1949 dex2oat.DumpTiming();
1950 return EXIT_SUCCESS;
1951}
1952
1953static int CompileApp(Dex2Oat& dex2oat) {
1954 dex2oat.Compile();
1955
1956 // Create the app oat.
1957 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001958 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001959 return EXIT_FAILURE;
1960 }
1961
1962 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1963 // which we would lose.
1964 if (!dex2oat.FlushOatFile()) {
1965 return EXIT_FAILURE;
1966 }
1967
1968 // When given --host, finish early without stripping.
1969 if (dex2oat.IsHost()) {
1970 if (!dex2oat.FlushCloseOatFile()) {
1971 return EXIT_FAILURE;
1972 }
1973
1974 dex2oat.DumpTiming();
1975 return EXIT_SUCCESS;
1976 }
1977
1978 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1979 // unstripped version. If this is given, we expect to be able to open writable files by name.
1980 if (!dex2oat.CopyUnstrippedToStripped()) {
1981 return EXIT_FAILURE;
1982 }
1983
Andreas Gampe10e477d2014-11-19 12:57:42 -08001984 // Flush and close the file.
1985 if (!dex2oat.FlushCloseOatFile()) {
1986 return EXIT_FAILURE;
1987 }
1988
1989 dex2oat.DumpTiming();
1990 return EXIT_SUCCESS;
1991}
1992
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001993static int dex2oat(int argc, char** argv) {
1994 b13564922();
1995
1996 TimingLogger timings("compiler", false, false);
1997
1998 Dex2Oat dex2oat(&timings);
1999
2000 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2001 dex2oat.ParseArgs(argc, argv);
2002
2003 // Check early that the result of compilation can be written
2004 if (!dex2oat.OpenFile()) {
2005 return EXIT_FAILURE;
2006 }
2007
Andreas Gampe046c7062015-05-18 23:22:54 -07002008 // Print the complete line when any of the following is true:
2009 // 1) Debug build
2010 // 2) Compiling an image
2011 // 3) Compiling with --host
2012 // 4) Compiling on the host (not a target build)
2013 // Otherwise, print a stripped command line.
2014 if (kIsDebugBuild || dex2oat.IsImage() || dex2oat.IsHost() || !kIsTargetBuild) {
2015 LOG(INFO) << CommandLine();
2016 } else {
2017 LOG(INFO) << StrippedCommandLine();
2018 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002019
2020 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002021 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002022 return EXIT_FAILURE;
2023 }
2024
Andreas Gampe10e477d2014-11-19 12:57:42 -08002025 if (dex2oat.IsImage()) {
2026 return CompileImage(dex2oat);
2027 } else {
2028 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002029 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002030}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002031} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002032
2033int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002034 int result = art::dex2oat(argc, argv);
2035 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2036 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2037 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002038 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002039 exit(result);
2040 }
2041 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002042}