blob: 21ce73c7d4a119b4f4bf716bd8e0e4801050ef18 [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"
Vladimir Marko10c13562015-11-25 14:33:36 +000058#include "dwarf/method_debug_info.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/class-inl.h"
68#include "mirror/class_loader.h"
69#include "mirror/object-inl.h"
70#include "mirror/object_array-inl.h"
71#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "os.h"
73#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000074#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "ScopedLocalRef.h"
76#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070077#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "well_known_classes.h"
79#include "zip_archive.h"
80
81namespace art {
82
Brian Carlstrom6449c622014-02-10 23:48:36 -080083static int original_argc;
84static char** original_argv;
85
86static std::string CommandLine() {
87 std::vector<std::string> command;
88 for (int i = 0; i < original_argc; ++i) {
89 command.push_back(original_argv[i]);
90 }
91 return Join(command, ' ');
92}
93
Andreas Gampe046c7062015-05-18 23:22:54 -070094// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
95// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
96// locations are all staged).
97static std::string StrippedCommandLine() {
98 std::vector<std::string> command;
99
100 // Do a pre-pass to look for zip-fd.
101 bool saw_zip_fd = false;
102 for (int i = 0; i < original_argc; ++i) {
103 if (StartsWith(original_argv[i], "--zip-fd=")) {
104 saw_zip_fd = true;
105 break;
106 }
107 }
108
109 // Now filter out things.
110 for (int i = 0; i < original_argc; ++i) {
111 // All runtime-arg parameters are dropped.
112 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
113 i++; // Drop the next part, too.
114 continue;
115 }
116
117 // Any instruction-setXXX is dropped.
118 if (StartsWith(original_argv[i], "--instruction-set")) {
119 continue;
120 }
121
122 // The boot image is dropped.
123 if (StartsWith(original_argv[i], "--boot-image=")) {
124 continue;
125 }
126
127 // This should leave any dex-file and oat-file options, describing what we compiled.
128
129 // However, we prefer to drop this when we saw --zip-fd.
130 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700131 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700132 if (StartsWith(original_argv[i], "--zip-") ||
133 StartsWith(original_argv[i], "--dex-") ||
134 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700135 StartsWith(original_argv[i], "--swap-") ||
136 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700137 continue;
138 }
139 }
140
141 command.push_back(original_argv[i]);
142 }
143
144 // Construct the final output.
145 if (command.size() <= 1U) {
146 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
147 return "Starting dex2oat.";
148 }
149 return Join(command, ' ');
150}
151
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152static void UsageErrorV(const char* fmt, va_list ap) {
153 std::string error;
154 StringAppendV(&error, fmt, ap);
155 LOG(ERROR) << error;
156}
157
158static void UsageError(const char* fmt, ...) {
159 va_list ap;
160 va_start(ap, fmt);
161 UsageErrorV(fmt, ap);
162 va_end(ap);
163}
164
Andreas Gampe794ad762015-02-23 08:12:24 -0800165NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 va_list ap;
167 va_start(ap, fmt);
168 UsageErrorV(fmt, ap);
169 va_end(ap);
170
Brian Carlstrom6449c622014-02-10 23:48:36 -0800171 UsageError("Command: %s", CommandLine().c_str());
172
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 UsageError("Usage: dex2oat [options]...");
174 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100175 UsageError(" -j<number>: specifies the number of threads used for compilation.");
176 UsageError(" Default is the number of detected hardware threads available on the");
177 UsageError(" host system.");
178 UsageError(" Example: -j12");
179 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700180 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 UsageError(" Example: --dex-file=/system/framework/core.jar");
182 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700183 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
184 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
185 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
186 UsageError(" --dex-location=/system/framework/core.jar");
187 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
189 UsageError(" containing a classes.dex file to compile.");
190 UsageError(" Example: --zip-fd=5");
191 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700192 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
193 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
195 UsageError("");
196 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
197 UsageError(" Example: --oat-file=/system/framework/boot.oat");
198 UsageError("");
199 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900200 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 UsageError("");
202 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
203 UsageError(" to the file descriptor specified by --oat-fd.");
204 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
205 UsageError("");
206 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
207 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
208 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError(" --image=<file.art>: specifies the output image filename.");
210 UsageError(" Example: --image=/system/framework/boot.art");
211 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800212 UsageError(" --image-format=(uncompressed|lz4):");
213 UsageError(" Which format to store the image.");
214 UsageError(" Example: --image-format=lz4");
215 UsageError(" Default: uncompressed");
216 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
218 UsageError(" Example: --image=frameworks/base/preloaded-classes");
219 UsageError("");
220 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
221 UsageError(" Example: --base=0x50000000");
222 UsageError("");
223 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000224 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000226 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000227 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError("");
229 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
230 UsageError(" Example: --android-root=out/host/linux-x86");
231 UsageError(" Default: $ANDROID_ROOT");
232 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800233 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700234 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 UsageError(" Example: --instruction-set=x86");
236 UsageError(" Default: arm");
237 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700238 UsageError(" --instruction-set-features=...,: Specify instruction set features");
239 UsageError(" Example: --instruction-set-features=div");
240 UsageError(" Default: default");
241 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700242 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
243 UsageError(" Default: disabled");
244 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800245 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800247 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100248 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100250 UsageError(" --compiler-filter="
251 "(verify-none"
252 "|interpret-only"
253 "|space"
254 "|balanced"
255 "|speed"
256 "|everything"
257 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700258 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800259 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800260 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800262 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
263 UsageError(" method for compiler filter tuning.");
264 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
265 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
266 UsageError("");
267 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
268 UsageError(" method for compiler filter tuning.");
269 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
270 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
271 UsageError("");
272 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
273 UsageError(" method for compiler filter tuning.");
274 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
275 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
276 UsageError("");
277 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
278 UsageError(" method for compiler filter tuning.");
279 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
280 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
281 UsageError("");
282 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
283 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700284 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
285 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800286 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
287 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
288 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100289 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
290 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100291 UsageError(" Has priority over the --compiler-filter option. Intended for ");
292 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100293 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
294 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
295 UsageError("");
296 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
297 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100298 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
299 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100300 UsageError(" Example: --inline-max-code-units=%d",
301 CompilerOptions::kDefaultInlineMaxCodeUnits);
302 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
303 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700304 UsageError(" --dump-timing: display a breakdown of where time was spent");
305 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700306 UsageError(" --include-patch-information: Include patching information so the generated code");
307 UsageError(" can have its base address moved without full recompilation.");
308 UsageError("");
309 UsageError(" --no-include-patch-information: Do not include patching information.");
310 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100311 UsageError(" -g");
312 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
313 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
314 UsageError(" This generates all the available information. Unneeded parts can be");
315 UsageError(" stripped using standard command line tools such as strip or objcopy.");
316 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700317 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100318 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100319 UsageError("");
David Srbecky0cf44932015-12-09 14:09:59 +0000320 UsageError(" --debuggable: Produce code debuggable with Java debugger. Implies -g.");
321 UsageError("");
322 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
323 UsageError(" Implies --debuggable.");
324 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
326 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
327 UsageError(" Use a separate --runtime-arg switch for each argument.");
328 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700329 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000330 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700332 UsageError(" --print-pass-names: print a list of pass names");
333 UsageError("");
334 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
335 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
336 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700337 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
338 "with the setting.");
339 UsageError(" Will print default if no overridden setting exists.");
340 UsageError("");
341 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
342 "Pass2Name:Pass2OptionName:Pass2Option#");
343 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
344 UsageError(" Separator used between options is a comma.");
345 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800346 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
347 UsageError(" Example: --swap-file=/data/tmp/swap.001");
348 UsageError("");
349 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
350 UsageError(" Example: --swap-fd=10");
351 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700352 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
353 UsageError(" Example: --app-image-fd=10");
354 UsageError("");
355 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
356 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
357 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358 std::cerr << "See log for usage error information\n";
359 exit(EXIT_FAILURE);
360}
361
Brian Carlstrom7940e442013-07-12 13:46:57 -0700362// The primary goal of the watchdog is to prevent stuck build servers
363// during development when fatal aborts lead to a cascade of failures
364// that result in a deadlock.
365class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800366// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367#undef CHECK_PTHREAD_CALL
368#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
369 do { \
370 int rc = call args; \
371 if (rc != 0) { \
372 errno = rc; \
373 std::string message(# call); \
374 message += " failed for "; \
375 message += reason; \
376 Fatal(message); \
377 } \
378 } while (false)
379
380 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700381 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382 is_watch_dog_enabled_ = is_watch_dog_enabled;
383 if (!is_watch_dog_enabled_) {
384 return;
385 }
386 shutting_down_ = false;
387 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700388 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
389 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700390 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
391 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
392 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
393 }
394 ~WatchDog() {
395 if (!is_watch_dog_enabled_) {
396 return;
397 }
398 const char* reason = "dex2oat watch dog thread shutdown";
399 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
400 shutting_down_ = true;
401 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
402 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
403
Kenny Root51316382014-05-13 14:59:37 -0700404 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405
406 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
407 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
408 }
409
410 private:
411 static void* CallBack(void* arg) {
412 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
413 ::art::SetThreadName("dex2oat watch dog");
414 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700415 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416 }
417
Andreas Gampe794ad762015-02-23 08:12:24 -0800418 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700419 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
420 // it's rather easy to hang in unwinding.
421 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
422 // logcat logging or stderr output.
423 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 exit(1);
425 }
426
427 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
429 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700430 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 timespec timeout_ts;
432 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
433 const char* reason = "dex2oat watch dog thread waiting";
434 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
435 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800436 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700438 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
439 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 } else if (rc != 0) {
441 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
442 strerror(errno)));
443 Fatal(message.c_str());
444 }
445 }
446 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
447 }
448
449 // 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 -0700450 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700451 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800452
Andreas Gampe540138a2015-09-14 15:34:38 -0700453 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
454 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
455 // itself before that watchdog would take down the system server.
456 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457
458 bool is_watch_dog_enabled_;
459 bool shutting_down_;
460 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
461 pthread_mutex_t mutex_;
462 pthread_cond_t cond_;
463 pthread_attr_t attr_;
464 pthread_t pthread_;
465};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800467static constexpr size_t kMinDexFilesForSwap = 2;
468static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
469
470static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
471 if (is_image) {
472 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
473 return false;
474 }
475 if (dex_files.size() < kMinDexFilesForSwap) {
476 // If there are less dex files than the threshold, assume it's gonna be fine.
477 return false;
478 }
479 size_t dex_files_size = 0;
480 for (const auto* dex_file : dex_files) {
481 dex_files_size += dex_file->GetHeader().file_size_;
482 }
483 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
484}
485
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800486class Dex2Oat FINAL {
487 public:
488 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100489 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800490 instruction_set_(kRuntimeISA),
491 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700492 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800493 method_inliner_map_(),
494 runtime_(nullptr),
495 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
496 start_ns_(NanoTime()),
497 oat_fd_(-1),
498 zip_fd_(-1),
499 image_base_(0U),
500 image_classes_zip_filename_(nullptr),
501 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800502 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800503 compiled_classes_zip_filename_(nullptr),
504 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700505 compiled_methods_zip_filename_(nullptr),
506 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700507 app_image_(false),
508 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000510 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700511 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800512 dump_stats_(false),
513 dump_passes_(false),
514 dump_timing_(false),
515 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100516 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800517 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700518 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800519 timings_(timings) {}
520
521 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800522 // Free opened dex files before deleting the runtime_, because ~DexFile
523 // uses MemMap, which is shut down by ~Runtime.
524 class_path_files_.clear();
525 opened_dex_files_.clear();
526
527 // Log completion time before deleting the runtime_, because this accesses
528 // the runtime.
529 LogCompletionTime();
530
Vladimir Marko307dac92015-10-20 11:20:09 +0100531 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
532 // We want to just exit on non-debug builds, not bringing the runtime down
533 // in an orderly fashion. So release the following fields.
534 driver_.release();
535 image_writer_.release();
536 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
537 dex_file.release();
538 }
539 oat_file_.release();
540 runtime_.release();
541 verification_results_.release();
542 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100543 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700544 }
545
Roland Levillain9ec5e222015-08-17 20:18:41 +0100546 struct ParserOptions {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800547 std::string oat_symbols;
548 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800549 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000550 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800551 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100552 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800553
Roland Levillain9ec5e222015-08-17 20:18:41 +0100554 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000555 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100556 }
557
558 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000559 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100560 }
561
562 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000563 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100564 }
565
566 void ParseBase(const StringPiece& option) {
567 DCHECK(option.starts_with("--base="));
568 const char* image_base_str = option.substr(strlen("--base=")).data();
569 char* end;
570 image_base_ = strtoul(image_base_str, &end, 16);
571 if (end == image_base_str || *end != '\0') {
572 Usage("Failed to parse hexadecimal value for option %s", option.data());
573 }
574 }
575
576 void ParseInstructionSet(const StringPiece& option) {
577 DCHECK(option.starts_with("--instruction-set="));
578 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
579 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
580 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
581 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
582 buf.get()[instruction_set_str.length()] = 0;
583 instruction_set_ = GetInstructionSetFromString(buf.get());
584 // arm actually means thumb2.
585 if (instruction_set_ == InstructionSet::kArm) {
586 instruction_set_ = InstructionSet::kThumb2;
587 }
588 }
589
590 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
591 DCHECK(option.starts_with("--instruction-set-variant="));
592 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
593 instruction_set_features_.reset(
594 InstructionSetFeatures::FromVariant(
595 instruction_set_, str.as_string(), &parser_options->error_msg));
596 if (instruction_set_features_.get() == nullptr) {
597 Usage("%s", parser_options->error_msg.c_str());
598 }
599 }
600
601 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
602 DCHECK(option.starts_with("--instruction-set-features="));
603 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
604 if (instruction_set_features_.get() == nullptr) {
605 instruction_set_features_.reset(
606 InstructionSetFeatures::FromVariant(
607 instruction_set_, "default", &parser_options->error_msg));
608 if (instruction_set_features_.get() == nullptr) {
609 Usage("Problem initializing default instruction set features variant: %s",
610 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700611 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800612 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100613 instruction_set_features_.reset(
614 instruction_set_features_->AddFeaturesFromString(str.as_string(),
615 &parser_options->error_msg));
616 if (instruction_set_features_.get() == nullptr) {
617 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
618 }
619 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800620
Roland Levillain9ec5e222015-08-17 20:18:41 +0100621 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
622 DCHECK(option.starts_with("--compiler-backend="));
623 parser_options->requested_specific_compiler = true;
624 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
625 if (backend_str == "Quick") {
626 compiler_kind_ = Compiler::kQuick;
627 } else if (backend_str == "Optimizing") {
628 compiler_kind_ = Compiler::kOptimizing;
629 } else {
630 Usage("Unknown compiler backend: %s", backend_str.data());
631 }
632 }
633
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800634 void ParseImageFormat(const StringPiece& option) {
635 const StringPiece substr("--image-format=");
636 DCHECK(option.starts_with(substr));
637 const StringPiece format_str = option.substr(substr.length());
638 if (format_str == "lz4") {
639 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
640 } else if (format_str == "uncompressed") {
641 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
642 } else {
643 Usage("Unknown image format: %s", format_str.data());
644 }
645 }
646
Roland Levillain9ec5e222015-08-17 20:18:41 +0100647 void ProcessOptions(ParserOptions* parser_options) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700648 boot_image_ = !image_filename_.empty();
649 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
650
651 if (IsAppImage() && IsBootImage()) {
652 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
653 }
654
655 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100656 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000657 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000658 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000659
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800660 if (oat_filename_.empty() && oat_fd_ == -1) {
661 Usage("Output must be supplied with either --oat-file or --oat-fd");
662 }
663
664 if (!oat_filename_.empty() && oat_fd_ != -1) {
665 Usage("--oat-file should not be used with --oat-fd");
666 }
667
Roland Levillain9ec5e222015-08-17 20:18:41 +0100668 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800669 Usage("--oat-symbols should not be used with --oat-fd");
670 }
671
Roland Levillain9ec5e222015-08-17 20:18:41 +0100672 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800673 Usage("--oat-symbols should not be used with --host");
674 }
675
676 if (oat_fd_ != -1 && !image_filename_.empty()) {
677 Usage("--oat-fd should not be used with --image");
678 }
679
680 if (android_root_.empty()) {
681 const char* android_root_env_var = getenv("ANDROID_ROOT");
682 if (android_root_env_var == nullptr) {
683 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800685 android_root_ += android_root_env_var;
686 }
687
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700688 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100689 parser_options->boot_image_filename += android_root_;
690 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800691 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100692 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000693 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 }
695
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700696 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 Usage("--image-classes should only be used with --image");
698 }
699
Vladimir Marko49b0f452015-12-10 13:49:19 +0000700 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800701 Usage("--image-classes should not be used with --boot-image");
702 }
703
704 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
705 Usage("--image-classes-zip should be used with --image-classes");
706 }
707
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700708 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800709 Usage("--compiled-classes should only be used with --image");
710 }
711
Vladimir Marko49b0f452015-12-10 13:49:19 +0000712 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800713 Usage("--compiled-classes should not be used with --boot-image");
714 }
715
716 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
717 Usage("--compiled-classes-zip should be used with --compiled-classes");
718 }
719
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 if (dex_filenames_.empty() && zip_fd_ == -1) {
721 Usage("Input must be supplied with either --dex-file or --zip-fd");
722 }
723
724 if (!dex_filenames_.empty() && zip_fd_ != -1) {
725 Usage("--dex-file should not be used with --zip-fd");
726 }
727
728 if (!dex_filenames_.empty() && !zip_location_.empty()) {
729 Usage("--dex-file should not be used with --zip-location");
730 }
731
732 if (dex_locations_.empty()) {
733 for (const char* dex_file_name : dex_filenames_) {
734 dex_locations_.push_back(dex_file_name);
735 }
736 } else if (dex_locations_.size() != dex_filenames_.size()) {
737 Usage("--dex-location arguments do not match --dex-file arguments");
738 }
739
740 if (zip_fd_ != -1 && zip_location_.empty()) {
741 Usage("--zip-location should be supplied with --zip-fd");
742 }
743
Vladimir Marko49b0f452015-12-10 13:49:19 +0000744 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 if (image_base_ == 0) {
746 Usage("Non-zero --base not specified");
747 }
748 }
749
750 oat_stripped_ = oat_filename_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100751 if (!parser_options->oat_symbols.empty()) {
752 oat_unstripped_ = parser_options->oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 oat_unstripped_ = oat_filename_;
755 }
756
757 // If no instruction set feature was given, use the default one for the target
758 // instruction set.
759 if (instruction_set_features_.get() == nullptr) {
760 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100761 InstructionSetFeatures::FromVariant(
762 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800763 if (instruction_set_features_.get() == nullptr) {
764 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100765 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800766 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800767 }
768
769 if (instruction_set_ == kRuntimeISA) {
770 std::unique_ptr<const InstructionSetFeatures> runtime_features(
771 InstructionSetFeatures::FromCppDefines());
772 if (!instruction_set_features_->Equals(runtime_features.get())) {
773 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
774 << *instruction_set_features_ << ") and those of dex2oat executable ("
775 << *runtime_features <<") for the command line:\n"
776 << CommandLine();
777 }
778 }
779
Roland Levillaina215b952015-08-07 11:38:32 +0100780 // It they are not set, use default values for inlining settings.
781 // TODO: We should rethink the compiler filter. We mostly save
782 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000783 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
784 compiler_options_->inline_depth_limit_ =
785 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100786 // Implementation of the space filter: limit inlining depth.
787 ? CompilerOptions::kSpaceFilterInlineDepthLimit
788 : CompilerOptions::kDefaultInlineDepthLimit;
789 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000790 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
791 compiler_options_->inline_max_code_units_ =
792 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100793 // Implementation of the space filter: limit inlining max code units.
794 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
795 : CompilerOptions::kDefaultInlineMaxCodeUnits;
796 }
797
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800799 // Set the compilation target's implicit checks options.
800 switch (instruction_set_) {
801 case kArm:
802 case kThumb2:
803 case kArm64:
804 case kX86:
805 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700806 case kMips:
807 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000808 compiler_options_->implicit_null_checks_ = true;
809 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800810 break;
811
812 default:
813 // Defaults are correct.
814 break;
815 }
816
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000817 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800818
819 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100820 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800821 watchdog_.reset(new WatchDog(true));
822 }
823
824 // Fill some values into the key-value store for the oat header.
825 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100826 }
827
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000828 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100829 std::ostringstream oss;
830 for (int i = 0; i < argc; ++i) {
831 if (i > 0) {
832 oss << ' ';
833 }
834 oss << argv[i];
835 }
836 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
837 oss.str(""); // Reset.
838 oss << kRuntimeISA;
839 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
840 key_value_store_->Put(
841 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000842 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100843 key_value_store_->Put(
844 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000845 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100846 }
847
848 // Parse the arguments from the command line. In case of an unrecognized option or impossible
849 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
850 // returns, arguments have been successfully parsed.
851 void ParseArgs(int argc, char** argv) {
852 original_argc = argc;
853 original_argv = argv;
854
855 InitLogging(argv);
856
857 // Skip over argv[0].
858 argv++;
859 argc--;
860
861 if (argc == 0) {
862 Usage("No arguments specified");
863 }
864
865 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000866 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100867
868 for (int i = 0; i < argc; i++) {
869 const StringPiece option(argv[i]);
870 const bool log_options = false;
871 if (log_options) {
872 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
873 }
874 if (option.starts_with("--dex-file=")) {
875 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
876 } else if (option.starts_with("--dex-location=")) {
877 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
878 } else if (option.starts_with("--zip-fd=")) {
879 ParseZipFd(option);
880 } else if (option.starts_with("--zip-location=")) {
881 zip_location_ = option.substr(strlen("--zip-location=")).data();
882 } else if (option.starts_with("--oat-file=")) {
883 oat_filename_ = option.substr(strlen("--oat-file=")).data();
884 } else if (option.starts_with("--oat-symbols=")) {
885 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data();
886 } else if (option.starts_with("--oat-fd=")) {
887 ParseOatFd(option);
888 } else if (option == "--watch-dog") {
889 parser_options->watch_dog_enabled = true;
890 } else if (option == "--no-watch-dog") {
891 parser_options->watch_dog_enabled = false;
892 } else if (option.starts_with("-j")) {
893 ParseJ(option);
894 } else if (option.starts_with("--oat-location=")) {
895 oat_location_ = option.substr(strlen("--oat-location=")).data();
896 } else if (option.starts_with("--image=")) {
897 image_filename_ = option.substr(strlen("--image=")).data();
898 } else if (option.starts_with("--image-classes=")) {
899 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
900 } else if (option.starts_with("--image-classes-zip=")) {
901 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800902 } else if (option.starts_with("--image-format=")) {
903 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100904 } else if (option.starts_with("--compiled-classes=")) {
905 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
906 } else if (option.starts_with("--compiled-classes-zip=")) {
907 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
908 } else if (option.starts_with("--compiled-methods=")) {
909 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
910 } else if (option.starts_with("--compiled-methods-zip=")) {
911 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
912 } else if (option.starts_with("--base=")) {
913 ParseBase(option);
914 } else if (option.starts_with("--boot-image=")) {
915 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
916 } else if (option.starts_with("--android-root=")) {
917 android_root_ = option.substr(strlen("--android-root=")).data();
918 } else if (option.starts_with("--instruction-set=")) {
919 ParseInstructionSet(option);
920 } else if (option.starts_with("--instruction-set-variant=")) {
921 ParseInstructionSetVariant(option, parser_options.get());
922 } else if (option.starts_with("--instruction-set-features=")) {
923 ParseInstructionSetFeatures(option, parser_options.get());
924 } else if (option.starts_with("--compiler-backend=")) {
925 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000926 } else if (option.starts_with("--profile-file=")) {
927 profile_file_ = option.substr(strlen("--profile-file=")).data();
928 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
929 } else if (option == "--no-profile-file") {
930 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +0100931 } else if (option == "--host") {
932 is_host_ = true;
933 } else if (option == "--runtime-arg") {
934 if (++i >= argc) {
935 Usage("Missing required argument for --runtime-arg");
936 }
937 if (log_options) {
938 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
939 }
940 runtime_args_.push_back(argv[i]);
941 } else if (option == "--dump-timing") {
942 dump_timing_ = true;
943 } else if (option == "--dump-passes") {
944 dump_passes_ = true;
945 } else if (option.starts_with("--dump-cfg=")) {
946 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +0100947 } else if (option.starts_with("--dump-cfg-append")) {
948 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100949 } else if (option == "--dump-stats") {
950 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000951 } else if (option.starts_with("--swap-file=")) {
952 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
953 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700954 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
955 } else if (option.starts_with("--app-image-file=")) {
956 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
957 } else if (option.starts_with("--app-image-fd=")) {
958 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100959 } else if (option.starts_with("--verbose-methods=")) {
960 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
961 // conditional on having verbost methods.
962 gLogVerbosity.compiler = false;
963 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000964 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100965 Usage("Unknown argument %s", option.data());
966 }
967 }
968
969 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800970
971 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000972 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 }
974
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800975 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
976 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800977 bool OpenFile() {
978 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
979 if (create_file) {
980 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
981 if (oat_location_.empty()) {
982 oat_location_ = oat_filename_;
983 }
984 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800985 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800987 if (oat_file_->SetLength(0) != 0) {
988 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
989 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800990 }
991 if (oat_file_.get() == nullptr) {
992 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
993 return false;
994 }
995 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
996 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800997 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800998 return false;
999 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001000
1001 // Swap file handling.
1002 //
1003 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1004 // that we can use for swap.
1005 //
1006 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1007 // will immediately unlink to satisfy the swap fd assumption.
1008 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1009 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1010 if (swap_file.get() == nullptr) {
1011 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1012 return false;
1013 }
1014 swap_fd_ = swap_file->Fd();
1015 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1016 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1017 // released immediately.
1018 unlink(swap_file_name_.c_str());
1019 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001020 return true;
1021 }
1022
Andreas Gampea650e702014-12-03 14:28:02 -08001023 void EraseOatFile() {
1024 DCHECK(oat_file_.get() != nullptr);
1025 oat_file_->Erase();
1026 oat_file_.reset();
1027 }
1028
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001029 void Shutdown() {
1030 ScopedObjectAccess soa(Thread::Current());
1031 for (jobject dex_cache : dex_caches_) {
1032 soa.Env()->DeleteLocalRef(dex_cache);
1033 }
1034 dex_caches_.clear();
1035 }
1036
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001037 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1038 // boot class path.
1039 bool Setup() {
1040 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001041 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001042
1043 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1044 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001046
Vladimir Marko307dac92015-10-20 11:20:09 +01001047 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001048 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001049 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001050 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001051 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001052 CompilerCallbacks::CallbackMode::kCompileBootImage :
1053 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001054
Vladimir Marko49b0f452015-12-10 13:49:19 +00001055 RuntimeArgumentMap runtime_options;
1056 if (!PrepareRuntimeOptions(&runtime_options)) {
1057 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001058 }
1059
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001060 {
1061 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001062 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001063 return false;
1064 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001065 }
1066
1067 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1068 // Runtime::Start, give it away now so that we don't starve GC.
1069 Thread* self = Thread::Current();
1070 self->TransitionFromRunnableToSuspended(kNative);
1071 // If we're doing the image, override the compiler filter to force full compilation. Must be
1072 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1073 // compilation of class initializers.
1074 // Whilst we're in native take the opportunity to initialize well known classes.
1075 WellKnownClasses::Init(self->GetJniEnv());
1076
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001077 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001078 if (boot_image_filename_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001079 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001080 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001081 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001082 if (dex_filenames_.empty()) {
1083 ATRACE_BEGIN("Opening zip archive from file descriptor");
1084 std::string error_msg;
1085 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1086 zip_location_.c_str(),
1087 &error_msg));
1088 if (zip_archive.get() == nullptr) {
1089 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1090 << error_msg;
1091 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001092 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001093 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001094 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1095 << "': " << error_msg;
1096 return false;
1097 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001098 for (auto& dex_file : opened_dex_files_) {
1099 dex_files_.push_back(dex_file.get());
1100 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001101 ATRACE_END();
1102 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001103 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001104 if (failure_count > 0) {
1105 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1106 return false;
1107 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001108 for (auto& dex_file : opened_dex_files_) {
1109 dex_files_.push_back(dex_file.get());
1110 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001111 }
1112
1113 constexpr bool kSaveDexInput = false;
1114 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001115 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001116 }
1117 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001118 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1119 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001120 for (const auto& dex_file : dex_files_) {
1121 if (!dex_file->EnableWrite()) {
1122 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001123 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001124 ScopedObjectAccess soa(self);
1125 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001126 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001127 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001128 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001129
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001130 // If we use a swap file, ensure we are above the threshold to make it necessary.
1131 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001132 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001133 close(swap_fd_);
1134 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001135 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001136 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001137 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001138 }
1139 }
1140 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1141
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001142 /*
1143 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1144 * Don't bother to check if we're doing the image.
1145 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001146 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001147 compiler_options_->IsCompilationEnabled() &&
1148 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149 size_t num_methods = 0;
1150 for (size_t i = 0; i != dex_files_.size(); ++i) {
1151 const DexFile* dex_file = dex_files_[i];
1152 CHECK(dex_file != nullptr);
1153 num_methods += dex_file->NumMethodIds();
1154 }
1155 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1156 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1157 VLOG(compiler) << "Below method threshold, compiling anyways";
1158 }
1159 }
1160
1161 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001162 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001163
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001164 // Create and invoke the compiler driver. This will compile all the dex files.
1165 void Compile() {
1166 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1167 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001168
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001169 // Handle and ClassLoader creation needs to come after Runtime::Create
1170 jobject class_loader = nullptr;
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001171 jobject class_path_class_loader = nullptr;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001173
Vladimir Marko49b0f452015-12-10 13:49:19 +00001174 if (!boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001175 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001176 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001177 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001178
1179 // Classpath: first the class-path given.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001180 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
Andreas Gampe7848da42015-04-09 11:15:04 -07001181
1182 // Store the classpath we have right now.
1183 key_value_store_->Put(OatHeader::kClassPathKey,
1184 OatFile::EncodeDexFileDependencies(class_path_files));
1185
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001186 class_path_class_loader = class_linker->CreatePathClassLoader(self,
1187 class_path_files,
1188 nullptr);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001189
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001190 // Class path loader as parent so that we'll resolve there first.
1191 class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001192 }
1193
Vladimir Marko307dac92015-10-20 11:20:09 +01001194 driver_.reset(new CompilerDriver(compiler_options_.get(),
1195 verification_results_.get(),
1196 &method_inliner_map_,
1197 compiler_kind_,
1198 instruction_set_,
1199 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001200 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001201 image_classes_.release(),
1202 compiled_classes_.release(),
1203 nullptr,
1204 thread_count_,
1205 dump_stats_,
1206 dump_passes_,
1207 dump_cfg_file_name_,
1208 dump_cfg_append_,
1209 compiler_phases_timings_.get(),
1210 swap_fd_,
1211 profile_file_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001213 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001214 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001215 }
1216
Brian Carlstrom7940e442013-07-12 13:46:57 -07001217 // Notes on the interleaving of creating the image and oat file to
1218 // ensure the references between the two are correct.
1219 //
1220 // Currently we have a memory layout that looks something like this:
1221 //
1222 // +--------------+
1223 // | image |
1224 // +--------------+
1225 // | boot oat |
1226 // +--------------+
1227 // | alloc spaces |
1228 // +--------------+
1229 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001230 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001231 //
1232 // 1. The image is expected to be loaded at an absolute address and
1233 // contains Objects with absolute pointers within the image.
1234 //
1235 // 2. There are absolute pointers from Methods in the image to their
1236 // code in the oat.
1237 //
1238 // 3. There are absolute pointers from the code in the oat to Methods
1239 // in the image.
1240 //
1241 // 4. There are absolute pointers from code in the oat to other code
1242 // in the oat.
1243 //
1244 // To get this all correct, we go through several steps.
1245 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001246 // 1. We prepare offsets for all data in the oat file and calculate
1247 // the oat data size and code size. During this stage, we also set
1248 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001249 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001250 // 2. We prepare offsets for the objects in the image and calculate
1251 // the image size.
1252 //
1253 // 3. We create the oat file. Originally this was just our own proprietary
1254 // file but now it is contained within an ELF dynamic object (aka an .so
1255 // file). Since we know the image size and oat data size and code size we
1256 // can prepare the ELF headers and we then know the ELF memory segment
1257 // layout and we can now resolve all references. The compiler provides
1258 // LinkerPatch information in each CompiledMethod and we resolve these,
1259 // using the layout information and image object locations provided by
1260 // image writer, as we're writing the method code.
1261 //
1262 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001263 // will be loaded after itself. Originally when oat file was simply
1264 // memory mapped so we could predict where its contents were based
1265 // on the file size. Now that it is an ELF file, we need to inspect
1266 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001267 // where the oat header is located within.
1268 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001269 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001270 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001271 // load the .so at the desired location at runtime by offsetting the
1272 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001273 // TODO: Do this in step 3. We already know the layout there.
1274 //
1275 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1276 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001277
1278
1279 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1280 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001281 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1282 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001283 bool CreateOatFile() {
1284 CHECK(key_value_store_.get() != nullptr);
1285
1286 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1287
1288 std::unique_ptr<OatWriter> oat_writer;
1289 {
1290 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1291 std::string image_file_location;
1292 uint32_t image_file_location_oat_checksum = 0;
1293 uintptr_t image_file_location_oat_data_begin = 0;
1294 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001295
1296 if (app_image_ && image_base_ == 0) {
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001297 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001298 image_base_ = RoundUp(
1299 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1300 kPageSize);
1301 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1302 }
1303
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001304 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001305 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001306 }
1307
1308 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001309 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001310 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001311 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1312 image_file_location_oat_data_begin =
1313 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1314 image_file_location = image_space->GetImageFilename();
1315 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1316 }
1317
1318 if (!image_file_location.empty()) {
1319 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1320 }
1321
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001322 oat_writer.reset(new OatWriter(dex_files_,
1323 image_file_location_oat_checksum,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001324 image_file_location_oat_data_begin,
1325 image_patch_delta,
Vladimir Marko307dac92015-10-20 11:20:09 +01001326 driver_.get(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001327 image_writer_.get(),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001328 IsBootImage(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001329 timings_,
1330 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001331 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001332
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001333 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001334 // The OatWriter constructor has already updated offsets in methods and we need to
1335 // prepare method offsets in the image address space for direct method patching.
1336 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1337 if (!image_writer_->PrepareImageAddressSpace()) {
1338 LOG(ERROR) << "Failed to prepare image address space.";
1339 return false;
1340 }
1341 }
1342
1343 {
1344 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001345 std::unique_ptr<ElfWriter> elf_writer =
1346 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file_.get());
1347
1348 elf_writer->Start();
1349
1350 OutputStream* rodata = elf_writer->StartRoData();
1351 if (!oat_writer->WriteRodata(rodata)) {
1352 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file_->GetPath();
1353 return false;
1354 }
1355 elf_writer->EndRoData(rodata);
1356
1357 OutputStream* text = elf_writer->StartText();
1358 if (!oat_writer->WriteCode(text)) {
1359 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file_->GetPath();
1360 return false;
1361 }
1362 elf_writer->EndText(text);
1363
1364 elf_writer->SetBssSize(oat_writer->GetBssSize());
Vladimir Marko10c13562015-11-25 14:33:36 +00001365 elf_writer->WriteDynamicSection();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001366 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1367 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001368
1369 if (!elf_writer->End()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001370 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1371 return false;
1372 }
1373 }
1374
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001375 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1376 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001377 }
1378
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 // If we are compiling an image, invoke the image creation routine. Else just skip.
1380 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001381 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001382 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1383 if (!CreateImageFile()) {
1384 return false;
1385 }
1386 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001387 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001388 return true;
1389 }
1390
Andreas Gampe10e477d2014-11-19 12:57:42 -08001391 // Create a copy from unstripped to stripped.
1392 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393 // If we don't want to strip in place, copy from unstripped location to stripped location.
1394 // We need to strip after image creation because FixupElf needs to use .strtab.
1395 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001396 // If the oat file is still open, flush it.
1397 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1398 if (!FlushCloseOatFile()) {
1399 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001400 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001401 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001402
1403 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001404 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1405 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1406 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001407 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001408 while (true) {
1409 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1410 if (bytes_read <= 0) {
1411 break;
1412 }
1413 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1414 CHECK(write_ok);
1415 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001416 if (out->FlushCloseOrErase() != 0) {
1417 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1418 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001419 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001420 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001421 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001422 return true;
1423 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001424
Andreas Gampe10e477d2014-11-19 12:57:42 -08001425 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001426 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001427 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1428 if (oat_file_->Flush() != 0) {
1429 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1430 << oat_filename_;
1431 oat_file_->Erase();
1432 return false;
1433 }
1434 }
1435 return true;
1436 }
1437
1438 bool FlushCloseOatFile() {
1439 if (oat_file_.get() != nullptr) {
1440 std::unique_ptr<File> tmp(oat_file_.release());
1441 if (tmp->FlushCloseOrErase() != 0) {
1442 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1443 << oat_filename_;
1444 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001445 }
1446 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001447 return true;
1448 }
1449
1450 void DumpTiming() {
1451 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1452 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1453 }
1454 if (dump_passes_) {
1455 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1456 }
1457 }
1458
1459 CompilerOptions* GetCompilerOptions() const {
1460 return compiler_options_.get();
1461 }
1462
Andreas Gampe10e477d2014-11-19 12:57:42 -08001463 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001464 return IsAppImage() || IsBootImage();
1465 }
1466
1467 bool IsAppImage() const {
1468 return app_image_;
1469 }
1470
1471 bool IsBootImage() const {
1472 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001473 }
1474
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001475 bool IsHost() const {
1476 return is_host_;
1477 }
1478
1479 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001480 template <typename T>
1481 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1482 std::vector<T*> result;
1483 result.reserve(src.size());
1484 for (const std::unique_ptr<T>& t : src) {
1485 result.push_back(t.get());
1486 }
1487 return result;
1488 }
1489
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001490 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1491 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001492 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001493 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 size_t failure_count = 0;
1495 for (size_t i = 0; i < dex_filenames.size(); i++) {
1496 const char* dex_filename = dex_filenames[i];
1497 const char* dex_location = dex_locations[i];
1498 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1499 std::string error_msg;
1500 if (!OS::FileExists(dex_filename)) {
1501 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1502 continue;
1503 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001504 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001505 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1506 ++failure_count;
1507 }
1508 ATRACE_END();
1509 }
1510 return failure_count;
1511 }
1512
Andreas Gampee3712d02015-04-09 14:46:31 -07001513 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1514 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1515 // efficient, but under normal circumstances the list is neither large nor is this part too
1516 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001517 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1518 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001519 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001520 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001521 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1522 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001523 return true;
1524 }
1525 }
1526 return false;
1527 }
1528
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001529 // Appends to opened_dex_files any elements of class_path that dex_files
1530 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001531 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001532 std::vector<const DexFile*> dex_files,
1533 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001534 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001535 std::vector<std::string> parsed;
1536 Split(class_path, ':', &parsed);
1537 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1538 ScopedObjectAccess soa(Thread::Current());
1539 for (size_t i = 0; i < parsed.size(); ++i) {
1540 if (DexFilesContains(dex_files, parsed[i])) {
1541 continue;
1542 }
1543 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001544 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001545 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1546 }
1547 }
1548 }
1549
Vladimir Marko49b0f452015-12-10 13:49:19 +00001550 bool PrepareImageClasses() {
1551 // If --image-classes was specified, calculate the full list of classes to include in the image.
1552 if (image_classes_filename_ != nullptr) {
1553 image_classes_ =
1554 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1555 if (image_classes_ == nullptr) {
1556 return false;
1557 }
1558 } else if (IsBootImage()) {
1559 image_classes_.reset(new std::unordered_set<std::string>);
1560 }
1561 return true;
1562 }
1563
1564 bool PrepareCompiledClasses() {
1565 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1566 // image.
1567 if (compiled_classes_filename_ != nullptr) {
1568 compiled_classes_ =
1569 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1570 if (compiled_classes_ == nullptr) {
1571 return false;
1572 }
1573 } else {
1574 compiled_classes_.reset(nullptr); // By default compile everything.
1575 }
1576 return true;
1577 }
1578
1579 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1580 const char* classes_filename,
1581 const char* tag) {
1582 std::unique_ptr<std::unordered_set<std::string>> classes;
1583 std::string error_msg;
1584 if (zip_filename != nullptr) {
1585 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1586 } else {
1587 classes.reset(ReadImageClassesFromFile(classes_filename));
1588 }
1589 if (classes == nullptr) {
1590 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1591 << classes_filename << "': " << error_msg;
1592 }
1593 return classes;
1594 }
1595
1596 bool PrepareCompiledMethods() {
1597 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1598 if (compiled_methods_filename_ != nullptr) {
1599 std::string error_msg;
1600 if (compiled_methods_zip_filename_ != nullptr) {
1601 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1602 compiled_methods_filename_,
1603 nullptr, // No post-processing.
1604 &error_msg));
1605 } else {
1606 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1607 nullptr)); // No post-processing.
1608 }
1609 if (compiled_methods_.get() == nullptr) {
1610 LOG(ERROR) << "Failed to create list of compiled methods from '"
1611 << compiled_methods_filename_ << "': " << error_msg;
1612 return false;
1613 }
1614 } else {
1615 compiled_methods_.reset(nullptr); // By default compile everything.
1616 }
1617 return true;
1618 }
1619
1620 void SaveDexInput() {
1621 for (size_t i = 0; i < dex_files_.size(); ++i) {
1622 const DexFile* dex_file = dex_files_[i];
1623 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1624 getpid(), i));
1625 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1626 if (tmp_file.get() == nullptr) {
1627 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1628 << ". Try: adb shell chmod 777 /data/local/tmp";
1629 continue;
1630 }
1631 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1632 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1633 UNUSED(tmp_file->Flush());
1634 UNUSED(tmp_file->Close());
1635 LOG(INFO) << "Wrote input to " << tmp_file_name;
1636 }
1637 }
1638
1639 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
1640 RuntimeOptions raw_options;
1641 if (boot_image_filename_.empty()) {
1642 std::string boot_class_path = "-Xbootclasspath:";
1643 boot_class_path += Join(dex_filenames_, ':');
1644 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
1645 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1646 boot_class_path_locations += Join(dex_locations_, ':');
1647 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
1648 } else {
1649 std::string boot_image_option = "-Ximage:";
1650 boot_image_option += boot_image_filename_;
1651 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
1652 }
1653 for (size_t i = 0; i < runtime_args_.size(); i++) {
1654 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
1655 }
1656
1657 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1658 raw_options.push_back(
1659 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1660
1661 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1662 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1663 // have been stripped in preopting, anyways).
1664 if (!IsBootImage()) {
1665 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1666 }
1667 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1668 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1669 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
1670
1671 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
1672 LOG(ERROR) << "Failed to parse runtime options";
1673 return false;
1674 }
1675 return true;
1676 }
1677
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001678 // Create a runtime necessary for compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001679 bool CreateRuntime(RuntimeArgumentMap&& runtime_options)
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001680 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001681 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001682 LOG(ERROR) << "Failed to create runtime";
1683 return false;
1684 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001685 runtime_.reset(Runtime::Current());
1686 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001687 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1688 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001689 if (!runtime_->HasCalleeSaveMethod(type)) {
1690 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001691 }
1692 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001693 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001694
1695 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1696 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001697 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001698
Vladimir Marko307dac92015-10-20 11:20:09 +01001699 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001700
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001701 return true;
1702 }
1703
1704 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001705 DCHECK(IsImage());
1706 image_writer_.reset(new ImageWriter(*driver_,
1707 image_base,
1708 compiler_options_->GetCompilePic(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001709 IsAppImage(),
1710 image_storage_mode_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001711 }
1712
1713 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1714 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001715 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001716 CHECK(image_writer_ != nullptr);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001717 if (!image_writer_->Write(app_image_fd_,
1718 IsBootImage() ? image_filename_ : app_image_file_name_,
1719 oat_unstripped_,
1720 oat_location_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001721 LOG(ERROR) << "Failed to create image file " << image_filename_;
1722 return false;
1723 }
1724 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1725
1726 // Destroy ImageWriter before doing FixupElf.
1727 image_writer_.reset();
1728
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001729 // Do not fix up the ELF file if we are --compile-pic or compiing the app image
1730 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001731 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1732 if (oat_file.get() == nullptr) {
1733 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1734 return false;
1735 }
1736
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001737 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001738 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001739 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1740 return false;
1741 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001742
1743 if (oat_file->FlushCloseOrErase()) {
1744 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1745 return false;
1746 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001747 }
1748
1749 return true;
1750 }
1751
1752 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001753 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1754 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001755 std::function<std::string(const char*)> process = DotToDescriptor;
1756 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001757 }
1758
1759 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001760 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001761 const char* zip_filename,
1762 const char* image_classes_filename,
1763 std::string* error_msg) {
1764 std::function<std::string(const char*)> process = DotToDescriptor;
1765 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1766 }
1767
1768 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1769 // the given function.
1770 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1771 const char* input_filename, std::function<std::string(const char*)>* process) {
1772 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1773 if (input_file.get() == nullptr) {
1774 LOG(ERROR) << "Failed to open input file " << input_filename;
1775 return nullptr;
1776 }
1777 std::unique_ptr<std::unordered_set<std::string>> result(
1778 ReadCommentedInputStream(*input_file, process));
1779 input_file->close();
1780 return result.release();
1781 }
1782
1783 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1784 // Post-process each line with the given function.
1785 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001786 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001787 const char* input_filename,
1788 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001789 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001790 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1791 if (zip_archive.get() == nullptr) {
1792 return nullptr;
1793 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001794 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001795 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001796 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001797 zip_filename, error_msg->c_str());
1798 return nullptr;
1799 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001800 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1801 input_filename,
1802 error_msg));
1803 if (input_file.get() == nullptr) {
1804 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001805 zip_filename, error_msg->c_str());
1806 return nullptr;
1807 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001808 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1809 input_file->Size());
1810 std::istringstream input_stream(input_string);
1811 return ReadCommentedInputStream(input_stream, process);
1812 }
1813
1814 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1815 // with the given function.
1816 static std::unordered_set<std::string>* ReadCommentedInputStream(
1817 std::istream& in_stream,
1818 std::function<std::string(const char*)>* process) {
1819 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1820 new std::unordered_set<std::string>);
1821 while (in_stream.good()) {
1822 std::string dot;
1823 std::getline(in_stream, dot);
1824 if (StartsWith(dot, "#") || dot.empty()) {
1825 continue;
1826 }
1827 if (process != nullptr) {
1828 std::string descriptor((*process)(dot.c_str()));
1829 image_classes->insert(descriptor);
1830 } else {
1831 image_classes->insert(dot);
1832 }
1833 }
1834 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001835 }
1836
Mathieu Chartier49285c52014-12-02 15:43:48 -08001837 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001838 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1839 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001840 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001841 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001842 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07001843 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001844 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1845 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001846 }
1847
1848 std::unique_ptr<CompilerOptions> compiler_options_;
1849 Compiler::Kind compiler_kind_;
1850
1851 InstructionSet instruction_set_;
1852 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1853
1854 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1855
Vladimir Marko307dac92015-10-20 11:20:09 +01001856 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001857
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001858 DexFileToMethodInlinerMap method_inliner_map_;
1859 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1860
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001861 // Ownership for the class path files.
1862 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1863
Vladimir Marko307dac92015-10-20 11:20:09 +01001864 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001865
1866 size_t thread_count_;
1867 uint64_t start_ns_;
1868 std::unique_ptr<WatchDog> watchdog_;
1869 std::unique_ptr<File> oat_file_;
1870 std::string oat_stripped_;
1871 std::string oat_unstripped_;
1872 std::string oat_location_;
1873 std::string oat_filename_;
1874 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001875 std::vector<const char*> dex_filenames_;
1876 std::vector<const char*> dex_locations_;
1877 int zip_fd_;
1878 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00001879 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001880 std::vector<const char*> runtime_args_;
1881 std::string image_filename_;
1882 uintptr_t image_base_;
1883 const char* image_classes_zip_filename_;
1884 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001885 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001886 const char* compiled_classes_zip_filename_;
1887 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001888 const char* compiled_methods_zip_filename_;
1889 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001890 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1891 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001892 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001893 bool app_image_;
1894 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001895 bool is_host_;
1896 std::string android_root_;
1897 std::vector<const DexFile*> dex_files_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001898 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001899 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001900
Vladimir Marko307dac92015-10-20 11:20:09 +01001901 std::unique_ptr<ImageWriter> image_writer_;
1902 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001903
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001904 std::vector<std::string> verbose_methods_;
1905 bool dump_stats_;
1906 bool dump_passes_;
1907 bool dump_timing_;
1908 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001909 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01001910 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001911 std::string swap_file_name_;
1912 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001913 std::string app_image_file_name_;
1914 int app_image_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001915 std::string profile_file_; // Profile file to use
1916 TimingLogger* timings_;
1917 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1918
1919 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1920};
1921
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001922static void b13564922() {
1923#if defined(__linux__) && defined(__arm__)
1924 int major, minor;
1925 struct utsname uts;
1926 if (uname(&uts) != -1 &&
1927 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1928 ((major < 3) || ((major == 3) && (minor < 4)))) {
1929 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1930 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1931 int old_personality = personality(0xffffffff);
1932 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1933 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1934 if (new_personality == -1) {
1935 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1936 }
1937 }
1938 }
1939#endif
1940}
1941
Andreas Gampe10e477d2014-11-19 12:57:42 -08001942static int CompileImage(Dex2Oat& dex2oat) {
1943 dex2oat.Compile();
1944
1945 // Create the boot.oat.
1946 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001947 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001948 return EXIT_FAILURE;
1949 }
1950
1951 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1952 // re-opened from the unstripped name.
1953 if (!dex2oat.FlushCloseOatFile()) {
1954 return EXIT_FAILURE;
1955 }
1956
1957 // Creates the boot.art and patches the boot.oat.
1958 if (!dex2oat.HandleImage()) {
1959 return EXIT_FAILURE;
1960 }
1961
1962 // When given --host, finish early without stripping.
1963 if (dex2oat.IsHost()) {
1964 dex2oat.DumpTiming();
1965 return EXIT_SUCCESS;
1966 }
1967
1968 // Copy unstripped to stripped location, if necessary.
1969 if (!dex2oat.CopyUnstrippedToStripped()) {
1970 return EXIT_FAILURE;
1971 }
1972
Andreas Gampe10e477d2014-11-19 12:57:42 -08001973 // FlushClose again, as stripping might have re-opened the oat file.
1974 if (!dex2oat.FlushCloseOatFile()) {
1975 return EXIT_FAILURE;
1976 }
1977
1978 dex2oat.DumpTiming();
1979 return EXIT_SUCCESS;
1980}
1981
1982static int CompileApp(Dex2Oat& dex2oat) {
1983 dex2oat.Compile();
1984
1985 // Create the app oat.
1986 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001987 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001988 return EXIT_FAILURE;
1989 }
1990
1991 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1992 // which we would lose.
1993 if (!dex2oat.FlushOatFile()) {
1994 return EXIT_FAILURE;
1995 }
1996
1997 // When given --host, finish early without stripping.
1998 if (dex2oat.IsHost()) {
1999 if (!dex2oat.FlushCloseOatFile()) {
2000 return EXIT_FAILURE;
2001 }
2002
2003 dex2oat.DumpTiming();
2004 return EXIT_SUCCESS;
2005 }
2006
2007 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
2008 // unstripped version. If this is given, we expect to be able to open writable files by name.
2009 if (!dex2oat.CopyUnstrippedToStripped()) {
2010 return EXIT_FAILURE;
2011 }
2012
Andreas Gampe10e477d2014-11-19 12:57:42 -08002013 // Flush and close the file.
2014 if (!dex2oat.FlushCloseOatFile()) {
2015 return EXIT_FAILURE;
2016 }
2017
2018 dex2oat.DumpTiming();
2019 return EXIT_SUCCESS;
2020}
2021
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002022static int dex2oat(int argc, char** argv) {
2023 b13564922();
2024
2025 TimingLogger timings("compiler", false, false);
2026
2027 Dex2Oat dex2oat(&timings);
2028
2029 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2030 dex2oat.ParseArgs(argc, argv);
2031
2032 // Check early that the result of compilation can be written
2033 if (!dex2oat.OpenFile()) {
2034 return EXIT_FAILURE;
2035 }
2036
Andreas Gampe046c7062015-05-18 23:22:54 -07002037 // Print the complete line when any of the following is true:
2038 // 1) Debug build
2039 // 2) Compiling an image
2040 // 3) Compiling with --host
2041 // 4) Compiling on the host (not a target build)
2042 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002043 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002044 LOG(INFO) << CommandLine();
2045 } else {
2046 LOG(INFO) << StrippedCommandLine();
2047 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002048
2049 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002050 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002051 return EXIT_FAILURE;
2052 }
2053
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002054 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002055 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002056 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002057 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002058 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002059 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002060
2061 dex2oat.Shutdown();
2062 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002063}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002064} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002065
2066int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002067 int result = art::dex2oat(argc, argv);
2068 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2069 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2070 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002071 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002072 exit(result);
2073 }
2074 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002075}