blob: 26538073693dd9e9488b588e01e483a38ee7fcdf [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) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700129 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700130 if (StartsWith(original_argv[i], "--zip-") ||
131 StartsWith(original_argv[i], "--dex-") ||
132 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700133 StartsWith(original_argv[i], "--swap-") ||
134 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700135 continue;
136 }
137 }
138
139 command.push_back(original_argv[i]);
140 }
141
142 // Construct the final output.
143 if (command.size() <= 1U) {
144 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
145 return "Starting dex2oat.";
146 }
147 return Join(command, ' ');
148}
149
Brian Carlstrom7940e442013-07-12 13:46:57 -0700150static void UsageErrorV(const char* fmt, va_list ap) {
151 std::string error;
152 StringAppendV(&error, fmt, ap);
153 LOG(ERROR) << error;
154}
155
156static void UsageError(const char* fmt, ...) {
157 va_list ap;
158 va_start(ap, fmt);
159 UsageErrorV(fmt, ap);
160 va_end(ap);
161}
162
Andreas Gampe794ad762015-02-23 08:12:24 -0800163NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 va_list ap;
165 va_start(ap, fmt);
166 UsageErrorV(fmt, ap);
167 va_end(ap);
168
Brian Carlstrom6449c622014-02-10 23:48:36 -0800169 UsageError("Command: %s", CommandLine().c_str());
170
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 UsageError("Usage: dex2oat [options]...");
172 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100173 UsageError(" -j<number>: specifies the number of threads used for compilation.");
174 UsageError(" Default is the number of detected hardware threads available on the");
175 UsageError(" host system.");
176 UsageError(" Example: -j12");
177 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700178 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 UsageError(" Example: --dex-file=/system/framework/core.jar");
180 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700181 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
182 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
183 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
184 UsageError(" --dex-location=/system/framework/core.jar");
185 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
187 UsageError(" containing a classes.dex file to compile.");
188 UsageError(" Example: --zip-fd=5");
189 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700190 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
191 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
193 UsageError("");
194 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
195 UsageError(" Example: --oat-file=/system/framework/boot.oat");
196 UsageError("");
197 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900198 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 UsageError("");
200 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
201 UsageError(" to the file descriptor specified by --oat-fd.");
202 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
203 UsageError("");
204 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
205 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
206 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700207 UsageError(" --image=<file.art>: specifies the output image filename.");
208 UsageError(" Example: --image=/system/framework/boot.art");
209 UsageError("");
210 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
211 UsageError(" Example: --image=frameworks/base/preloaded-classes");
212 UsageError("");
213 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
214 UsageError(" Example: --base=0x50000000");
215 UsageError("");
216 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
217 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000218 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 UsageError("");
220 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
221 UsageError(" Example: --android-root=out/host/linux-x86");
222 UsageError(" Default: $ANDROID_ROOT");
223 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800224 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700225 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 UsageError(" Example: --instruction-set=x86");
227 UsageError(" Default: arm");
228 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700229 UsageError(" --instruction-set-features=...,: Specify instruction set features");
230 UsageError(" Example: --instruction-set-features=div");
231 UsageError(" Default: default");
232 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700233 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
234 UsageError(" Default: disabled");
235 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800236 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800238 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100239 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100241 UsageError(" --compiler-filter="
242 "(verify-none"
243 "|interpret-only"
244 "|space"
245 "|balanced"
246 "|speed"
247 "|everything"
248 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700249 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800250 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800251 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800252 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800253 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
254 UsageError(" method for compiler filter tuning.");
255 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
256 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
257 UsageError("");
258 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
259 UsageError(" method for compiler filter tuning.");
260 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
261 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
262 UsageError("");
263 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
264 UsageError(" method for compiler filter tuning.");
265 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
266 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
267 UsageError("");
268 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
269 UsageError(" method for compiler filter tuning.");
270 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
271 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
272 UsageError("");
273 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
274 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700275 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
276 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800277 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
278 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
279 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100280 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
281 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100282 UsageError(" Has priority over the --compiler-filter option. Intended for ");
283 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100284 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
285 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
286 UsageError("");
287 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
288 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100289 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
290 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100291 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("");
Roland Levillainb2872da2015-09-02 09:35:25 +0100309 UsageError(" --debuggable: Produce debuggable code. Implies --generate-debug-info.");
310 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100311 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100312 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
314 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
315 UsageError(" Use a separate --runtime-arg switch for each argument.");
316 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700317 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000318 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700319 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700320 UsageError(" --print-pass-names: print a list of pass names");
321 UsageError("");
322 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
323 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
324 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700325 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
326 "with the setting.");
327 UsageError(" Will print default if no overridden setting exists.");
328 UsageError("");
329 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
330 "Pass2Name:Pass2OptionName:Pass2Option#");
331 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
332 UsageError(" Separator used between options is a comma.");
333 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800334 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
335 UsageError(" Example: --swap-file=/data/tmp/swap.001");
336 UsageError("");
337 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
338 UsageError(" Example: --swap-fd=10");
339 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700340 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
341 UsageError(" Example: --app-image-fd=10");
342 UsageError("");
343 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
344 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
345 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 std::cerr << "See log for usage error information\n";
347 exit(EXIT_FAILURE);
348}
349
Brian Carlstrom7940e442013-07-12 13:46:57 -0700350// The primary goal of the watchdog is to prevent stuck build servers
351// during development when fatal aborts lead to a cascade of failures
352// that result in a deadlock.
353class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800354// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355#undef CHECK_PTHREAD_CALL
356#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
357 do { \
358 int rc = call args; \
359 if (rc != 0) { \
360 errno = rc; \
361 std::string message(# call); \
362 message += " failed for "; \
363 message += reason; \
364 Fatal(message); \
365 } \
366 } while (false)
367
368 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700369 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370 is_watch_dog_enabled_ = is_watch_dog_enabled;
371 if (!is_watch_dog_enabled_) {
372 return;
373 }
374 shutting_down_ = false;
375 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700376 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
377 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
379 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
380 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
381 }
382 ~WatchDog() {
383 if (!is_watch_dog_enabled_) {
384 return;
385 }
386 const char* reason = "dex2oat watch dog thread shutdown";
387 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
388 shutting_down_ = true;
389 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
390 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
391
Kenny Root51316382014-05-13 14:59:37 -0700392 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393
394 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
395 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
396 }
397
398 private:
399 static void* CallBack(void* arg) {
400 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
401 ::art::SetThreadName("dex2oat watch dog");
402 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700403 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 }
405
Andreas Gampe794ad762015-02-23 08:12:24 -0800406 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700407 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
408 // it's rather easy to hang in unwinding.
409 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
410 // logcat logging or stderr output.
411 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 exit(1);
413 }
414
415 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
417 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700418 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419 timespec timeout_ts;
420 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
421 const char* reason = "dex2oat watch dog thread waiting";
422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
423 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800424 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700426 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
427 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428 } else if (rc != 0) {
429 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
430 strerror(errno)));
431 Fatal(message.c_str());
432 }
433 }
434 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
435 }
436
437 // 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 -0700438 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700439 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800440
Andreas Gampe540138a2015-09-14 15:34:38 -0700441 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
442 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
443 // itself before that watchdog would take down the system server.
444 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445
446 bool is_watch_dog_enabled_;
447 bool shutting_down_;
448 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
449 pthread_mutex_t mutex_;
450 pthread_cond_t cond_;
451 pthread_attr_t attr_;
452 pthread_t pthread_;
453};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800455static constexpr size_t kMinDexFilesForSwap = 2;
456static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
457
458static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
459 if (is_image) {
460 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
461 return false;
462 }
463 if (dex_files.size() < kMinDexFilesForSwap) {
464 // If there are less dex files than the threshold, assume it's gonna be fine.
465 return false;
466 }
467 size_t dex_files_size = 0;
468 for (const auto* dex_file : dex_files) {
469 dex_files_size += dex_file->GetHeader().file_size_;
470 }
471 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
472}
473
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800474class Dex2Oat FINAL {
475 public:
476 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100477 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800478 instruction_set_(kRuntimeISA),
479 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700480 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800481 method_inliner_map_(),
482 runtime_(nullptr),
483 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
484 start_ns_(NanoTime()),
485 oat_fd_(-1),
486 zip_fd_(-1),
487 image_base_(0U),
488 image_classes_zip_filename_(nullptr),
489 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800490 compiled_classes_zip_filename_(nullptr),
491 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700492 compiled_methods_zip_filename_(nullptr),
493 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700494 app_image_(false),
495 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800496 is_host_(false),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700497 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800498 dump_stats_(false),
499 dump_passes_(false),
500 dump_timing_(false),
501 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100502 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800503 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700504 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505 timings_(timings) {}
506
507 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800508 // Free opened dex files before deleting the runtime_, because ~DexFile
509 // uses MemMap, which is shut down by ~Runtime.
510 class_path_files_.clear();
511 opened_dex_files_.clear();
512
513 // Log completion time before deleting the runtime_, because this accesses
514 // the runtime.
515 LogCompletionTime();
516
Vladimir Marko307dac92015-10-20 11:20:09 +0100517 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
518 // We want to just exit on non-debug builds, not bringing the runtime down
519 // in an orderly fashion. So release the following fields.
520 driver_.release();
521 image_writer_.release();
522 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
523 dex_file.release();
524 }
525 oat_file_.release();
526 runtime_.release();
527 verification_results_.release();
528 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100529 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700530 }
531
Roland Levillain9ec5e222015-08-17 20:18:41 +0100532 struct ParserOptions {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800533 std::string oat_symbols;
534 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800535 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000536 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800537 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100538 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800539
Roland Levillain9ec5e222015-08-17 20:18:41 +0100540 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000541 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100542 }
543
544 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000545 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100546 }
547
548 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000549 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100550 }
551
552 void ParseBase(const StringPiece& option) {
553 DCHECK(option.starts_with("--base="));
554 const char* image_base_str = option.substr(strlen("--base=")).data();
555 char* end;
556 image_base_ = strtoul(image_base_str, &end, 16);
557 if (end == image_base_str || *end != '\0') {
558 Usage("Failed to parse hexadecimal value for option %s", option.data());
559 }
560 }
561
562 void ParseInstructionSet(const StringPiece& option) {
563 DCHECK(option.starts_with("--instruction-set="));
564 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
565 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
566 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
567 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
568 buf.get()[instruction_set_str.length()] = 0;
569 instruction_set_ = GetInstructionSetFromString(buf.get());
570 // arm actually means thumb2.
571 if (instruction_set_ == InstructionSet::kArm) {
572 instruction_set_ = InstructionSet::kThumb2;
573 }
574 }
575
576 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
577 DCHECK(option.starts_with("--instruction-set-variant="));
578 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
579 instruction_set_features_.reset(
580 InstructionSetFeatures::FromVariant(
581 instruction_set_, str.as_string(), &parser_options->error_msg));
582 if (instruction_set_features_.get() == nullptr) {
583 Usage("%s", parser_options->error_msg.c_str());
584 }
585 }
586
587 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
588 DCHECK(option.starts_with("--instruction-set-features="));
589 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
590 if (instruction_set_features_.get() == nullptr) {
591 instruction_set_features_.reset(
592 InstructionSetFeatures::FromVariant(
593 instruction_set_, "default", &parser_options->error_msg));
594 if (instruction_set_features_.get() == nullptr) {
595 Usage("Problem initializing default instruction set features variant: %s",
596 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700597 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800598 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100599 instruction_set_features_.reset(
600 instruction_set_features_->AddFeaturesFromString(str.as_string(),
601 &parser_options->error_msg));
602 if (instruction_set_features_.get() == nullptr) {
603 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
604 }
605 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800606
Roland Levillain9ec5e222015-08-17 20:18:41 +0100607 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
608 DCHECK(option.starts_with("--compiler-backend="));
609 parser_options->requested_specific_compiler = true;
610 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
611 if (backend_str == "Quick") {
612 compiler_kind_ = Compiler::kQuick;
613 } else if (backend_str == "Optimizing") {
614 compiler_kind_ = Compiler::kOptimizing;
615 } else {
616 Usage("Unknown compiler backend: %s", backend_str.data());
617 }
618 }
619
Roland Levillain9ec5e222015-08-17 20:18:41 +0100620 void ProcessOptions(ParserOptions* parser_options) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700621 boot_image_ = !image_filename_.empty();
622 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
623
624 if (IsAppImage() && IsBootImage()) {
625 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
626 }
627
628 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100629 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000630 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000631 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000632
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800633 if (oat_filename_.empty() && oat_fd_ == -1) {
634 Usage("Output must be supplied with either --oat-file or --oat-fd");
635 }
636
637 if (!oat_filename_.empty() && oat_fd_ != -1) {
638 Usage("--oat-file should not be used with --oat-fd");
639 }
640
Roland Levillain9ec5e222015-08-17 20:18:41 +0100641 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800642 Usage("--oat-symbols should not be used with --oat-fd");
643 }
644
Roland Levillain9ec5e222015-08-17 20:18:41 +0100645 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800646 Usage("--oat-symbols should not be used with --host");
647 }
648
649 if (oat_fd_ != -1 && !image_filename_.empty()) {
650 Usage("--oat-fd should not be used with --image");
651 }
652
653 if (android_root_.empty()) {
654 const char* android_root_env_var = getenv("ANDROID_ROOT");
655 if (android_root_env_var == nullptr) {
656 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800658 android_root_ += android_root_env_var;
659 }
660
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700661 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100662 parser_options->boot_image_filename += android_root_;
663 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800664 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100665 if (!parser_options->boot_image_filename.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800666 boot_image_option_ += "-Ximage:";
Roland Levillain9ec5e222015-08-17 20:18:41 +0100667 boot_image_option_ += parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800668 }
669
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700670 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800671 Usage("--image-classes should only be used with --image");
672 }
673
674 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
675 Usage("--image-classes should not be used with --boot-image");
676 }
677
678 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
679 Usage("--image-classes-zip should be used with --image-classes");
680 }
681
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700682 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800683 Usage("--compiled-classes should only be used with --image");
684 }
685
686 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
687 Usage("--compiled-classes should not be used with --boot-image");
688 }
689
690 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
691 Usage("--compiled-classes-zip should be used with --compiled-classes");
692 }
693
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 if (dex_filenames_.empty() && zip_fd_ == -1) {
695 Usage("Input must be supplied with either --dex-file or --zip-fd");
696 }
697
698 if (!dex_filenames_.empty() && zip_fd_ != -1) {
699 Usage("--dex-file should not be used with --zip-fd");
700 }
701
702 if (!dex_filenames_.empty() && !zip_location_.empty()) {
703 Usage("--dex-file should not be used with --zip-location");
704 }
705
706 if (dex_locations_.empty()) {
707 for (const char* dex_file_name : dex_filenames_) {
708 dex_locations_.push_back(dex_file_name);
709 }
710 } else if (dex_locations_.size() != dex_filenames_.size()) {
711 Usage("--dex-location arguments do not match --dex-file arguments");
712 }
713
714 if (zip_fd_ != -1 && zip_location_.empty()) {
715 Usage("--zip-location should be supplied with --zip-fd");
716 }
717
718 if (boot_image_option_.empty()) {
719 if (image_base_ == 0) {
720 Usage("Non-zero --base not specified");
721 }
722 }
723
724 oat_stripped_ = oat_filename_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100725 if (!parser_options->oat_symbols.empty()) {
726 oat_unstripped_ = parser_options->oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 oat_unstripped_ = oat_filename_;
729 }
730
731 // If no instruction set feature was given, use the default one for the target
732 // instruction set.
733 if (instruction_set_features_.get() == nullptr) {
734 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100735 InstructionSetFeatures::FromVariant(
736 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800737 if (instruction_set_features_.get() == nullptr) {
738 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100739 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800740 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800741 }
742
743 if (instruction_set_ == kRuntimeISA) {
744 std::unique_ptr<const InstructionSetFeatures> runtime_features(
745 InstructionSetFeatures::FromCppDefines());
746 if (!instruction_set_features_->Equals(runtime_features.get())) {
747 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
748 << *instruction_set_features_ << ") and those of dex2oat executable ("
749 << *runtime_features <<") for the command line:\n"
750 << CommandLine();
751 }
752 }
753
Roland Levillaina215b952015-08-07 11:38:32 +0100754 // It they are not set, use default values for inlining settings.
755 // TODO: We should rethink the compiler filter. We mostly save
756 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000757 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
758 compiler_options_->inline_depth_limit_ =
759 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100760 // Implementation of the space filter: limit inlining depth.
761 ? CompilerOptions::kSpaceFilterInlineDepthLimit
762 : CompilerOptions::kDefaultInlineDepthLimit;
763 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000764 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
765 compiler_options_->inline_max_code_units_ =
766 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100767 // Implementation of the space filter: limit inlining max code units.
768 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
769 : CompilerOptions::kDefaultInlineMaxCodeUnits;
770 }
771
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800772 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800773 // Set the compilation target's implicit checks options.
774 switch (instruction_set_) {
775 case kArm:
776 case kThumb2:
777 case kArm64:
778 case kX86:
779 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700780 case kMips:
781 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000782 compiler_options_->implicit_null_checks_ = true;
783 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800784 break;
785
786 default:
787 // Defaults are correct.
788 break;
789 }
790
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000791 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800792
793 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100794 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 watchdog_.reset(new WatchDog(true));
796 }
797
798 // Fill some values into the key-value store for the oat header.
799 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100800 }
801
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000802 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100803 std::ostringstream oss;
804 for (int i = 0; i < argc; ++i) {
805 if (i > 0) {
806 oss << ' ';
807 }
808 oss << argv[i];
809 }
810 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
811 oss.str(""); // Reset.
812 oss << kRuntimeISA;
813 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
814 key_value_store_->Put(
815 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000816 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100817 key_value_store_->Put(
818 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000819 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100820 }
821
822 // Parse the arguments from the command line. In case of an unrecognized option or impossible
823 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
824 // returns, arguments have been successfully parsed.
825 void ParseArgs(int argc, char** argv) {
826 original_argc = argc;
827 original_argv = argv;
828
829 InitLogging(argv);
830
831 // Skip over argv[0].
832 argv++;
833 argc--;
834
835 if (argc == 0) {
836 Usage("No arguments specified");
837 }
838
839 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000840 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100841
842 for (int i = 0; i < argc; i++) {
843 const StringPiece option(argv[i]);
844 const bool log_options = false;
845 if (log_options) {
846 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
847 }
848 if (option.starts_with("--dex-file=")) {
849 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
850 } else if (option.starts_with("--dex-location=")) {
851 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
852 } else if (option.starts_with("--zip-fd=")) {
853 ParseZipFd(option);
854 } else if (option.starts_with("--zip-location=")) {
855 zip_location_ = option.substr(strlen("--zip-location=")).data();
856 } else if (option.starts_with("--oat-file=")) {
857 oat_filename_ = option.substr(strlen("--oat-file=")).data();
858 } else if (option.starts_with("--oat-symbols=")) {
859 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data();
860 } else if (option.starts_with("--oat-fd=")) {
861 ParseOatFd(option);
862 } else if (option == "--watch-dog") {
863 parser_options->watch_dog_enabled = true;
864 } else if (option == "--no-watch-dog") {
865 parser_options->watch_dog_enabled = false;
866 } else if (option.starts_with("-j")) {
867 ParseJ(option);
868 } else if (option.starts_with("--oat-location=")) {
869 oat_location_ = option.substr(strlen("--oat-location=")).data();
870 } else if (option.starts_with("--image=")) {
871 image_filename_ = option.substr(strlen("--image=")).data();
872 } else if (option.starts_with("--image-classes=")) {
873 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
874 } else if (option.starts_with("--image-classes-zip=")) {
875 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
876 } else if (option.starts_with("--compiled-classes=")) {
877 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
878 } else if (option.starts_with("--compiled-classes-zip=")) {
879 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
880 } else if (option.starts_with("--compiled-methods=")) {
881 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
882 } else if (option.starts_with("--compiled-methods-zip=")) {
883 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
884 } else if (option.starts_with("--base=")) {
885 ParseBase(option);
886 } else if (option.starts_with("--boot-image=")) {
887 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
888 } else if (option.starts_with("--android-root=")) {
889 android_root_ = option.substr(strlen("--android-root=")).data();
890 } else if (option.starts_with("--instruction-set=")) {
891 ParseInstructionSet(option);
892 } else if (option.starts_with("--instruction-set-variant=")) {
893 ParseInstructionSetVariant(option, parser_options.get());
894 } else if (option.starts_with("--instruction-set-features=")) {
895 ParseInstructionSetFeatures(option, parser_options.get());
896 } else if (option.starts_with("--compiler-backend=")) {
897 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000898 } else if (option.starts_with("--profile-file=")) {
899 profile_file_ = option.substr(strlen("--profile-file=")).data();
900 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
901 } else if (option == "--no-profile-file") {
902 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +0100903 } else if (option == "--host") {
904 is_host_ = true;
905 } else if (option == "--runtime-arg") {
906 if (++i >= argc) {
907 Usage("Missing required argument for --runtime-arg");
908 }
909 if (log_options) {
910 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
911 }
912 runtime_args_.push_back(argv[i]);
913 } else if (option == "--dump-timing") {
914 dump_timing_ = true;
915 } else if (option == "--dump-passes") {
916 dump_passes_ = true;
917 } else if (option.starts_with("--dump-cfg=")) {
918 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +0100919 } else if (option.starts_with("--dump-cfg-append")) {
920 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100921 } else if (option == "--dump-stats") {
922 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000923 } else if (option.starts_with("--swap-file=")) {
924 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
925 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700926 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
927 } else if (option.starts_with("--app-image-file=")) {
928 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
929 } else if (option.starts_with("--app-image-fd=")) {
930 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100931 } else if (option.starts_with("--verbose-methods=")) {
932 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
933 // conditional on having verbost methods.
934 gLogVerbosity.compiler = false;
935 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000936 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100937 Usage("Unknown argument %s", option.data());
938 }
939 }
940
941 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800942
943 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000944 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945 }
946
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800947 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
948 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800949 bool OpenFile() {
950 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
951 if (create_file) {
952 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
953 if (oat_location_.empty()) {
954 oat_location_ = oat_filename_;
955 }
956 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800957 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800958 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800959 if (oat_file_->SetLength(0) != 0) {
960 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
961 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800962 }
963 if (oat_file_.get() == nullptr) {
964 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
965 return false;
966 }
967 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
968 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800969 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800970 return false;
971 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800972
973 // Swap file handling.
974 //
975 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
976 // that we can use for swap.
977 //
978 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
979 // will immediately unlink to satisfy the swap fd assumption.
980 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
981 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
982 if (swap_file.get() == nullptr) {
983 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
984 return false;
985 }
986 swap_fd_ = swap_file->Fd();
987 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
988 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
989 // released immediately.
990 unlink(swap_file_name_.c_str());
991 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800992 return true;
993 }
994
Andreas Gampea650e702014-12-03 14:28:02 -0800995 void EraseOatFile() {
996 DCHECK(oat_file_.get() != nullptr);
997 oat_file_->Erase();
998 oat_file_.reset();
999 }
1000
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001001 void Shutdown() {
1002 ScopedObjectAccess soa(Thread::Current());
1003 for (jobject dex_cache : dex_caches_) {
1004 soa.Env()->DeleteLocalRef(dex_cache);
1005 }
1006 dex_caches_.clear();
1007 }
1008
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001009 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1010 // boot class path.
1011 bool Setup() {
1012 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1013 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001014 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1015 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001016 std::string boot_class_path = "-Xbootclasspath:";
1017 boot_class_path += Join(dex_filenames_, ':');
1018 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1019 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1020 boot_class_path_locations += Join(dex_locations_, ':');
1021 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001022 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001023 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001024 }
1025 for (size_t i = 0; i < runtime_args_.size(); i++) {
1026 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001028
Vladimir Marko307dac92015-10-20 11:20:09 +01001029 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001030 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001031 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001032 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001033 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001034 CompilerCallbacks::CallbackMode::kCompileBootImage :
1035 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001036 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1037 runtime_options.push_back(
1038 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1039
Andreas Gampe1d00add2015-02-27 19:35:46 -08001040 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1041 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1042 // have been stripped in preopting, anyways).
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001043 if (!IsBootImage()) {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001044 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1045 }
Calin Juravle01aaf6e2015-06-19 22:05:39 +01001046 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1047 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1048 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Andreas Gampe1d00add2015-02-27 19:35:46 -08001049
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001050 {
1051 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
1052 if (!CreateRuntime(runtime_options)) {
1053 return false;
1054 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001055 }
1056
1057 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1058 // Runtime::Start, give it away now so that we don't starve GC.
1059 Thread* self = Thread::Current();
1060 self->TransitionFromRunnableToSuspended(kNative);
1061 // If we're doing the image, override the compiler filter to force full compilation. Must be
1062 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1063 // compilation of class initializers.
1064 // Whilst we're in native take the opportunity to initialize well known classes.
1065 WellKnownClasses::Init(self->GetJniEnv());
1066
1067 // If --image-classes was specified, calculate the full list of classes to include in the image
1068 if (image_classes_filename_ != nullptr) {
1069 std::string error_msg;
1070 if (image_classes_zip_filename_ != nullptr) {
1071 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001072 image_classes_filename_,
1073 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001074 } else {
1075 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1076 }
1077 if (image_classes_.get() == nullptr) {
1078 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1079 "': " << error_msg;
1080 return false;
1081 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001082 } else if (IsBootImage()) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001083 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001084 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001085 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1086 // image.
1087 if (compiled_classes_filename_ != nullptr) {
1088 std::string error_msg;
1089 if (compiled_classes_zip_filename_ != nullptr) {
1090 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1091 compiled_classes_filename_,
1092 &error_msg));
1093 } else {
1094 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1095 }
1096 if (compiled_classes_.get() == nullptr) {
1097 LOG(ERROR) << "Failed to create list of compiled classes from '"
1098 << compiled_classes_filename_ << "': " << error_msg;
1099 return false;
1100 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001101 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001102 compiled_classes_.reset(nullptr); // By default compile everything.
1103 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001104 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1105 if (compiled_methods_filename_ != nullptr) {
1106 std::string error_msg;
1107 if (compiled_methods_zip_filename_ != nullptr) {
1108 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1109 compiled_methods_filename_,
1110 nullptr, // No post-processing.
1111 &error_msg));
1112 } else {
1113 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1114 nullptr)); // No post-processing.
1115 }
1116 if (compiled_methods_.get() == nullptr) {
1117 LOG(ERROR) << "Failed to create list of compiled methods from '"
1118 << compiled_methods_filename_ << "': " << error_msg;
1119 return false;
1120 }
1121 } else {
1122 compiled_methods_.reset(nullptr); // By default compile everything.
1123 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001124
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001125 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001126 if (boot_image_option_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001127 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001128 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001129 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 if (dex_filenames_.empty()) {
1131 ATRACE_BEGIN("Opening zip archive from file descriptor");
1132 std::string error_msg;
1133 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1134 zip_location_.c_str(),
1135 &error_msg));
1136 if (zip_archive.get() == nullptr) {
1137 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1138 << error_msg;
1139 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001140 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001141 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001142 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1143 << "': " << error_msg;
1144 return false;
1145 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001146 for (auto& dex_file : opened_dex_files_) {
1147 dex_files_.push_back(dex_file.get());
1148 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149 ATRACE_END();
1150 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001151 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001152 if (failure_count > 0) {
1153 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1154 return false;
1155 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001156 for (auto& dex_file : opened_dex_files_) {
1157 dex_files_.push_back(dex_file.get());
1158 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001159 }
1160
1161 constexpr bool kSaveDexInput = false;
1162 if (kSaveDexInput) {
1163 for (size_t i = 0; i < dex_files_.size(); ++i) {
1164 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001165 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1166 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001167 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1168 if (tmp_file.get() == nullptr) {
1169 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1170 << ". Try: adb shell chmod 777 /data/local/tmp";
1171 continue;
1172 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001173 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1174 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1175 UNUSED(tmp_file->Flush());
1176 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001177 LOG(INFO) << "Wrote input to " << tmp_file_name;
1178 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001179 }
1180 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001181 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1182 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001183 for (const auto& dex_file : dex_files_) {
1184 if (!dex_file->EnableWrite()) {
1185 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001186 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001187 ScopedObjectAccess soa(self);
1188 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001189 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001190 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001191 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001192
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001193 // If we use a swap file, ensure we are above the threshold to make it necessary.
1194 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001195 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001196 close(swap_fd_);
1197 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001198 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001199 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001200 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001201 }
1202 }
1203 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1204
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001205 /*
1206 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1207 * Don't bother to check if we're doing the image.
1208 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001209 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001210 compiler_options_->IsCompilationEnabled() &&
1211 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 size_t num_methods = 0;
1213 for (size_t i = 0; i != dex_files_.size(); ++i) {
1214 const DexFile* dex_file = dex_files_[i];
1215 CHECK(dex_file != nullptr);
1216 num_methods += dex_file->NumMethodIds();
1217 }
1218 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1219 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1220 VLOG(compiler) << "Below method threshold, compiling anyways";
1221 }
1222 }
1223
1224 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001225 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001226
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001227 // Create and invoke the compiler driver. This will compile all the dex files.
1228 void Compile() {
1229 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1230 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001231
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001232 // Handle and ClassLoader creation needs to come after Runtime::Create
1233 jobject class_loader = nullptr;
1234 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001235
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001236 if (!boot_image_option_.empty()) {
1237 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001238 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001239 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001240
1241 // Classpath: first the class-path given.
1242 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001243 for (auto& class_path_file : class_path_files_) {
1244 class_path_files.push_back(class_path_file.get());
1245 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001246
1247 // Store the classpath we have right now.
1248 key_value_store_->Put(OatHeader::kClassPathKey,
1249 OatFile::EncodeDexFileDependencies(class_path_files));
1250
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001251 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1252 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001253
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001254 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001255 }
1256
Vladimir Marko307dac92015-10-20 11:20:09 +01001257 driver_.reset(new CompilerDriver(compiler_options_.get(),
1258 verification_results_.get(),
1259 &method_inliner_map_,
1260 compiler_kind_,
1261 instruction_set_,
1262 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001263 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001264 image_classes_.release(),
1265 compiled_classes_.release(),
1266 nullptr,
1267 thread_count_,
1268 dump_stats_,
1269 dump_passes_,
1270 dump_cfg_file_name_,
1271 dump_cfg_append_,
1272 compiler_phases_timings_.get(),
1273 swap_fd_,
1274 profile_file_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001275
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001276 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001277 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001278 }
1279
Brian Carlstrom7940e442013-07-12 13:46:57 -07001280 // Notes on the interleaving of creating the image and oat file to
1281 // ensure the references between the two are correct.
1282 //
1283 // Currently we have a memory layout that looks something like this:
1284 //
1285 // +--------------+
1286 // | image |
1287 // +--------------+
1288 // | boot oat |
1289 // +--------------+
1290 // | alloc spaces |
1291 // +--------------+
1292 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001293 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001294 //
1295 // 1. The image is expected to be loaded at an absolute address and
1296 // contains Objects with absolute pointers within the image.
1297 //
1298 // 2. There are absolute pointers from Methods in the image to their
1299 // code in the oat.
1300 //
1301 // 3. There are absolute pointers from the code in the oat to Methods
1302 // in the image.
1303 //
1304 // 4. There are absolute pointers from code in the oat to other code
1305 // in the oat.
1306 //
1307 // To get this all correct, we go through several steps.
1308 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001309 // 1. We prepare offsets for all data in the oat file and calculate
1310 // the oat data size and code size. During this stage, we also set
1311 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001313 // 2. We prepare offsets for the objects in the image and calculate
1314 // the image size.
1315 //
1316 // 3. We create the oat file. Originally this was just our own proprietary
1317 // file but now it is contained within an ELF dynamic object (aka an .so
1318 // file). Since we know the image size and oat data size and code size we
1319 // can prepare the ELF headers and we then know the ELF memory segment
1320 // layout and we can now resolve all references. The compiler provides
1321 // LinkerPatch information in each CompiledMethod and we resolve these,
1322 // using the layout information and image object locations provided by
1323 // image writer, as we're writing the method code.
1324 //
1325 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326 // will be loaded after itself. Originally when oat file was simply
1327 // memory mapped so we could predict where its contents were based
1328 // on the file size. Now that it is an ELF file, we need to inspect
1329 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001330 // where the oat header is located within.
1331 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001332 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001333 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001334 // load the .so at the desired location at runtime by offsetting the
1335 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001336 // TODO: Do this in step 3. We already know the layout there.
1337 //
1338 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1339 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001340
1341
1342 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1343 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001344 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1345 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001346 bool CreateOatFile() {
1347 CHECK(key_value_store_.get() != nullptr);
1348
1349 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1350
1351 std::unique_ptr<OatWriter> oat_writer;
1352 {
1353 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1354 std::string image_file_location;
1355 uint32_t image_file_location_oat_checksum = 0;
1356 uintptr_t image_file_location_oat_data_begin = 0;
1357 int32_t image_patch_delta = 0;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001358 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001359 PrepareImageWriter(image_base_);
1360 } else {
1361 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1362 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1363 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1364 image_file_location_oat_data_begin =
1365 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1366 image_file_location = image_space->GetImageFilename();
1367 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1368 }
1369
1370 if (!image_file_location.empty()) {
1371 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1372 }
1373
1374 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1375 image_file_location_oat_data_begin,
1376 image_patch_delta,
Vladimir Marko307dac92015-10-20 11:20:09 +01001377 driver_.get(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001378 image_writer_.get(),
1379 timings_,
1380 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001381 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001382
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001383 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001384 // The OatWriter constructor has already updated offsets in methods and we need to
1385 // prepare method offsets in the image address space for direct method patching.
1386 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1387 if (!image_writer_->PrepareImageAddressSpace()) {
1388 LOG(ERROR) << "Failed to prepare image address space.";
1389 return false;
1390 }
1391 }
1392
1393 {
1394 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1395 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1396 oat_file_.get())) {
1397 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1398 return false;
1399 }
1400 }
1401
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001402 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1403 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404 }
1405
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 // If we are compiling an image, invoke the image creation routine. Else just skip.
1407 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001408 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001409 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1410 if (!CreateImageFile()) {
1411 return false;
1412 }
1413 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001414 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001415 return true;
1416 }
1417
Andreas Gampe10e477d2014-11-19 12:57:42 -08001418 // Create a copy from unstripped to stripped.
1419 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001420 // If we don't want to strip in place, copy from unstripped location to stripped location.
1421 // We need to strip after image creation because FixupElf needs to use .strtab.
1422 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001423 // If the oat file is still open, flush it.
1424 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1425 if (!FlushCloseOatFile()) {
1426 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001427 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001428 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001429
1430 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001431 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1432 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1433 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001434 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001435 while (true) {
1436 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1437 if (bytes_read <= 0) {
1438 break;
1439 }
1440 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1441 CHECK(write_ok);
1442 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001443 if (out->FlushCloseOrErase() != 0) {
1444 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1445 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001446 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001447 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001448 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001449 return true;
1450 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001451
Andreas Gampe10e477d2014-11-19 12:57:42 -08001452 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001453 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001454 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1455 if (oat_file_->Flush() != 0) {
1456 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1457 << oat_filename_;
1458 oat_file_->Erase();
1459 return false;
1460 }
1461 }
1462 return true;
1463 }
1464
1465 bool FlushCloseOatFile() {
1466 if (oat_file_.get() != nullptr) {
1467 std::unique_ptr<File> tmp(oat_file_.release());
1468 if (tmp->FlushCloseOrErase() != 0) {
1469 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1470 << oat_filename_;
1471 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001472 }
1473 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001474 return true;
1475 }
1476
1477 void DumpTiming() {
1478 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1479 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1480 }
1481 if (dump_passes_) {
1482 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1483 }
1484 }
1485
1486 CompilerOptions* GetCompilerOptions() const {
1487 return compiler_options_.get();
1488 }
1489
Andreas Gampe10e477d2014-11-19 12:57:42 -08001490 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001491 return IsAppImage() || IsBootImage();
1492 }
1493
1494 bool IsAppImage() const {
1495 return app_image_;
1496 }
1497
1498 bool IsBootImage() const {
1499 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001500 }
1501
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001502 bool IsHost() const {
1503 return is_host_;
1504 }
1505
1506 private:
1507 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1508 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001509 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001510 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001511 size_t failure_count = 0;
1512 for (size_t i = 0; i < dex_filenames.size(); i++) {
1513 const char* dex_filename = dex_filenames[i];
1514 const char* dex_location = dex_locations[i];
1515 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1516 std::string error_msg;
1517 if (!OS::FileExists(dex_filename)) {
1518 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1519 continue;
1520 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001521 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001522 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1523 ++failure_count;
1524 }
1525 ATRACE_END();
1526 }
1527 return failure_count;
1528 }
1529
Andreas Gampee3712d02015-04-09 14:46:31 -07001530 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1531 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1532 // efficient, but under normal circumstances the list is neither large nor is this part too
1533 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001534 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1535 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001536 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001537 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001538 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1539 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001540 return true;
1541 }
1542 }
1543 return false;
1544 }
1545
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001546 // Appends to opened_dex_files any elements of class_path that dex_files
1547 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001548 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001549 std::vector<const DexFile*> dex_files,
1550 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001551 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001552 std::vector<std::string> parsed;
1553 Split(class_path, ':', &parsed);
1554 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1555 ScopedObjectAccess soa(Thread::Current());
1556 for (size_t i = 0; i < parsed.size(); ++i) {
1557 if (DexFilesContains(dex_files, parsed[i])) {
1558 continue;
1559 }
1560 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001561 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001562 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1563 }
1564 }
1565 }
1566
1567 // Create a runtime necessary for compilation.
1568 bool CreateRuntime(const RuntimeOptions& runtime_options)
1569 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1570 if (!Runtime::Create(runtime_options, false)) {
1571 LOG(ERROR) << "Failed to create runtime";
1572 return false;
1573 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001574 runtime_.reset(Runtime::Current());
1575 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001576 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1577 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001578 if (!runtime_->HasCalleeSaveMethod(type)) {
1579 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001580 }
1581 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001582 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001583
1584 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1585 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001586 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001587
Vladimir Marko307dac92015-10-20 11:20:09 +01001588 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001589
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001590 return true;
1591 }
1592
1593 void PrepareImageWriter(uintptr_t image_base) {
1594 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1595 }
1596
1597 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1598 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001599 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001600 CHECK(image_writer_ != nullptr);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001601 if (!image_writer_->Write(app_image_fd_,
1602 IsBootImage() ? image_filename_ : app_image_file_name_,
1603 oat_unstripped_,
1604 oat_location_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001605 LOG(ERROR) << "Failed to create image file " << image_filename_;
1606 return false;
1607 }
1608 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1609
1610 // Destroy ImageWriter before doing FixupElf.
1611 image_writer_.reset();
1612
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001613 // Do not fix up the ELF file if we are --compile-pic or compiing the app image
1614 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001615 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1616 if (oat_file.get() == nullptr) {
1617 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1618 return false;
1619 }
1620
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001621 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001622 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001623 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1624 return false;
1625 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001626
1627 if (oat_file->FlushCloseOrErase()) {
1628 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1629 return false;
1630 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001631 }
1632
1633 return true;
1634 }
1635
1636 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001637 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1638 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001639 std::function<std::string(const char*)> process = DotToDescriptor;
1640 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001641 }
1642
1643 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001644 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001645 const char* zip_filename,
1646 const char* image_classes_filename,
1647 std::string* error_msg) {
1648 std::function<std::string(const char*)> process = DotToDescriptor;
1649 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1650 }
1651
1652 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1653 // the given function.
1654 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1655 const char* input_filename, std::function<std::string(const char*)>* process) {
1656 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1657 if (input_file.get() == nullptr) {
1658 LOG(ERROR) << "Failed to open input file " << input_filename;
1659 return nullptr;
1660 }
1661 std::unique_ptr<std::unordered_set<std::string>> result(
1662 ReadCommentedInputStream(*input_file, process));
1663 input_file->close();
1664 return result.release();
1665 }
1666
1667 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1668 // Post-process each line with the given function.
1669 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001670 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001671 const char* input_filename,
1672 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001673 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001674 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1675 if (zip_archive.get() == nullptr) {
1676 return nullptr;
1677 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001678 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001679 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001680 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001681 zip_filename, error_msg->c_str());
1682 return nullptr;
1683 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001684 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1685 input_filename,
1686 error_msg));
1687 if (input_file.get() == nullptr) {
1688 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001689 zip_filename, error_msg->c_str());
1690 return nullptr;
1691 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001692 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1693 input_file->Size());
1694 std::istringstream input_stream(input_string);
1695 return ReadCommentedInputStream(input_stream, process);
1696 }
1697
1698 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1699 // with the given function.
1700 static std::unordered_set<std::string>* ReadCommentedInputStream(
1701 std::istream& in_stream,
1702 std::function<std::string(const char*)>* process) {
1703 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1704 new std::unordered_set<std::string>);
1705 while (in_stream.good()) {
1706 std::string dot;
1707 std::getline(in_stream, dot);
1708 if (StartsWith(dot, "#") || dot.empty()) {
1709 continue;
1710 }
1711 if (process != nullptr) {
1712 std::string descriptor((*process)(dot.c_str()));
1713 image_classes->insert(descriptor);
1714 } else {
1715 image_classes->insert(dot);
1716 }
1717 }
1718 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001719 }
1720
Mathieu Chartier49285c52014-12-02 15:43:48 -08001721 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001722 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1723 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001724 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001725 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001726 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07001727 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001728 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1729 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001730 }
1731
1732 std::unique_ptr<CompilerOptions> compiler_options_;
1733 Compiler::Kind compiler_kind_;
1734
1735 InstructionSet instruction_set_;
1736 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1737
1738 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1739
Vladimir Marko307dac92015-10-20 11:20:09 +01001740 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001741
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001742 DexFileToMethodInlinerMap method_inliner_map_;
1743 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1744
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001745 // Ownership for the class path files.
1746 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1747
Vladimir Marko307dac92015-10-20 11:20:09 +01001748 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001749
1750 size_t thread_count_;
1751 uint64_t start_ns_;
1752 std::unique_ptr<WatchDog> watchdog_;
1753 std::unique_ptr<File> oat_file_;
1754 std::string oat_stripped_;
1755 std::string oat_unstripped_;
1756 std::string oat_location_;
1757 std::string oat_filename_;
1758 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001759 std::vector<const char*> dex_filenames_;
1760 std::vector<const char*> dex_locations_;
1761 int zip_fd_;
1762 std::string zip_location_;
1763 std::string boot_image_option_;
1764 std::vector<const char*> runtime_args_;
1765 std::string image_filename_;
1766 uintptr_t image_base_;
1767 const char* image_classes_zip_filename_;
1768 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001769 const char* compiled_classes_zip_filename_;
1770 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001771 const char* compiled_methods_zip_filename_;
1772 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001773 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1774 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001775 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001776 bool app_image_;
1777 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001778 bool is_host_;
1779 std::string android_root_;
1780 std::vector<const DexFile*> dex_files_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001781 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001782 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001783
Vladimir Marko307dac92015-10-20 11:20:09 +01001784 std::unique_ptr<ImageWriter> image_writer_;
1785 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001786
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001787 std::vector<std::string> verbose_methods_;
1788 bool dump_stats_;
1789 bool dump_passes_;
1790 bool dump_timing_;
1791 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001792 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01001793 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001794 std::string swap_file_name_;
1795 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001796 std::string app_image_file_name_;
1797 int app_image_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001798 std::string profile_file_; // Profile file to use
1799 TimingLogger* timings_;
1800 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1801
1802 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1803};
1804
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001805static void b13564922() {
1806#if defined(__linux__) && defined(__arm__)
1807 int major, minor;
1808 struct utsname uts;
1809 if (uname(&uts) != -1 &&
1810 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1811 ((major < 3) || ((major == 3) && (minor < 4)))) {
1812 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1813 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1814 int old_personality = personality(0xffffffff);
1815 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1816 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1817 if (new_personality == -1) {
1818 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1819 }
1820 }
1821 }
1822#endif
1823}
1824
Andreas Gampe10e477d2014-11-19 12:57:42 -08001825static int CompileImage(Dex2Oat& dex2oat) {
1826 dex2oat.Compile();
1827
1828 // Create the boot.oat.
1829 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001830 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001831 return EXIT_FAILURE;
1832 }
1833
1834 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1835 // re-opened from the unstripped name.
1836 if (!dex2oat.FlushCloseOatFile()) {
1837 return EXIT_FAILURE;
1838 }
1839
1840 // Creates the boot.art and patches the boot.oat.
1841 if (!dex2oat.HandleImage()) {
1842 return EXIT_FAILURE;
1843 }
1844
1845 // When given --host, finish early without stripping.
1846 if (dex2oat.IsHost()) {
1847 dex2oat.DumpTiming();
1848 return EXIT_SUCCESS;
1849 }
1850
1851 // Copy unstripped to stripped location, if necessary.
1852 if (!dex2oat.CopyUnstrippedToStripped()) {
1853 return EXIT_FAILURE;
1854 }
1855
Andreas Gampe10e477d2014-11-19 12:57:42 -08001856 // FlushClose again, as stripping might have re-opened the oat file.
1857 if (!dex2oat.FlushCloseOatFile()) {
1858 return EXIT_FAILURE;
1859 }
1860
1861 dex2oat.DumpTiming();
1862 return EXIT_SUCCESS;
1863}
1864
1865static int CompileApp(Dex2Oat& dex2oat) {
1866 dex2oat.Compile();
1867
1868 // Create the app oat.
1869 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001870 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001871 return EXIT_FAILURE;
1872 }
1873
1874 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1875 // which we would lose.
1876 if (!dex2oat.FlushOatFile()) {
1877 return EXIT_FAILURE;
1878 }
1879
1880 // When given --host, finish early without stripping.
1881 if (dex2oat.IsHost()) {
1882 if (!dex2oat.FlushCloseOatFile()) {
1883 return EXIT_FAILURE;
1884 }
1885
1886 dex2oat.DumpTiming();
1887 return EXIT_SUCCESS;
1888 }
1889
1890 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1891 // unstripped version. If this is given, we expect to be able to open writable files by name.
1892 if (!dex2oat.CopyUnstrippedToStripped()) {
1893 return EXIT_FAILURE;
1894 }
1895
Andreas Gampe10e477d2014-11-19 12:57:42 -08001896 // Flush and close the file.
1897 if (!dex2oat.FlushCloseOatFile()) {
1898 return EXIT_FAILURE;
1899 }
1900
1901 dex2oat.DumpTiming();
1902 return EXIT_SUCCESS;
1903}
1904
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001905static int dex2oat(int argc, char** argv) {
1906 b13564922();
1907
1908 TimingLogger timings("compiler", false, false);
1909
1910 Dex2Oat dex2oat(&timings);
1911
1912 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1913 dex2oat.ParseArgs(argc, argv);
1914
1915 // Check early that the result of compilation can be written
1916 if (!dex2oat.OpenFile()) {
1917 return EXIT_FAILURE;
1918 }
1919
Andreas Gampe046c7062015-05-18 23:22:54 -07001920 // Print the complete line when any of the following is true:
1921 // 1) Debug build
1922 // 2) Compiling an image
1923 // 3) Compiling with --host
1924 // 4) Compiling on the host (not a target build)
1925 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001926 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07001927 LOG(INFO) << CommandLine();
1928 } else {
1929 LOG(INFO) << StrippedCommandLine();
1930 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001931
1932 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001933 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001934 return EXIT_FAILURE;
1935 }
1936
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001937 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001938 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001939 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08001940 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001941 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001942 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001943
1944 dex2oat.Shutdown();
1945 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001946}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001947} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948
1949int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001950 int result = art::dex2oat(argc, argv);
1951 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1952 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1953 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07001954 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001955 exit(result);
1956 }
1957 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001958}