blob: 87d5a78454641bcbfc021b0a6b92134527324d93 [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"
74#include "ScopedLocalRef.h"
75#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070076#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "well_known_classes.h"
78#include "zip_archive.h"
79
80namespace art {
81
Brian Carlstrom6449c622014-02-10 23:48:36 -080082static int original_argc;
83static char** original_argv;
84
85static std::string CommandLine() {
86 std::vector<std::string> command;
87 for (int i = 0; i < original_argc; ++i) {
88 command.push_back(original_argv[i]);
89 }
90 return Join(command, ' ');
91}
92
Andreas Gampe046c7062015-05-18 23:22:54 -070093// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
94// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
95// locations are all staged).
96static std::string StrippedCommandLine() {
97 std::vector<std::string> command;
98
99 // Do a pre-pass to look for zip-fd.
100 bool saw_zip_fd = false;
101 for (int i = 0; i < original_argc; ++i) {
102 if (StartsWith(original_argv[i], "--zip-fd=")) {
103 saw_zip_fd = true;
104 break;
105 }
106 }
107
108 // Now filter out things.
109 for (int i = 0; i < original_argc; ++i) {
110 // All runtime-arg parameters are dropped.
111 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
112 i++; // Drop the next part, too.
113 continue;
114 }
115
116 // Any instruction-setXXX is dropped.
117 if (StartsWith(original_argv[i], "--instruction-set")) {
118 continue;
119 }
120
121 // The boot image is dropped.
122 if (StartsWith(original_argv[i], "--boot-image=")) {
123 continue;
124 }
125
126 // This should leave any dex-file and oat-file options, describing what we compiled.
127
128 // However, we prefer to drop this when we saw --zip-fd.
129 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700130 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700131 if (StartsWith(original_argv[i], "--zip-") ||
132 StartsWith(original_argv[i], "--dex-") ||
133 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700134 StartsWith(original_argv[i], "--swap-") ||
135 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700136 continue;
137 }
138 }
139
140 command.push_back(original_argv[i]);
141 }
142
143 // Construct the final output.
144 if (command.size() <= 1U) {
145 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
146 return "Starting dex2oat.";
147 }
148 return Join(command, ' ');
149}
150
Brian Carlstrom7940e442013-07-12 13:46:57 -0700151static void UsageErrorV(const char* fmt, va_list ap) {
152 std::string error;
153 StringAppendV(&error, fmt, ap);
154 LOG(ERROR) << error;
155}
156
157static void UsageError(const char* fmt, ...) {
158 va_list ap;
159 va_start(ap, fmt);
160 UsageErrorV(fmt, ap);
161 va_end(ap);
162}
163
Andreas Gampe794ad762015-02-23 08:12:24 -0800164NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 va_list ap;
166 va_start(ap, fmt);
167 UsageErrorV(fmt, ap);
168 va_end(ap);
169
Brian Carlstrom6449c622014-02-10 23:48:36 -0800170 UsageError("Command: %s", CommandLine().c_str());
171
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 UsageError("Usage: dex2oat [options]...");
173 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100174 UsageError(" -j<number>: specifies the number of threads used for compilation.");
175 UsageError(" Default is the number of detected hardware threads available on the");
176 UsageError(" host system.");
177 UsageError(" Example: -j12");
178 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700179 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180 UsageError(" Example: --dex-file=/system/framework/core.jar");
181 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700182 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
183 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
184 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
185 UsageError(" --dex-location=/system/framework/core.jar");
186 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700187 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
188 UsageError(" containing a classes.dex file to compile.");
189 UsageError(" Example: --zip-fd=5");
190 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700191 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
192 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
194 UsageError("");
195 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
196 UsageError(" Example: --oat-file=/system/framework/boot.oat");
197 UsageError("");
198 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900199 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 UsageError("");
201 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
202 UsageError(" to the file descriptor specified by --oat-fd.");
203 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
204 UsageError("");
205 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
206 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
207 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 UsageError(" --image=<file.art>: specifies the output image filename.");
209 UsageError(" Example: --image=/system/framework/boot.art");
210 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800211 UsageError(" --image-format=(uncompressed|lz4):");
212 UsageError(" Which format to store the image.");
213 UsageError(" Example: --image-format=lz4");
214 UsageError(" Default: uncompressed");
215 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
217 UsageError(" Example: --image=frameworks/base/preloaded-classes");
218 UsageError("");
219 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
220 UsageError(" Example: --base=0x50000000");
221 UsageError("");
222 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000223 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000225 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000226 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 UsageError("");
228 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
229 UsageError(" Example: --android-root=out/host/linux-x86");
230 UsageError(" Default: $ANDROID_ROOT");
231 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800232 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700233 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError(" Example: --instruction-set=x86");
235 UsageError(" Default: arm");
236 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700237 UsageError(" --instruction-set-features=...,: Specify instruction set features");
238 UsageError(" Example: --instruction-set-features=div");
239 UsageError(" Default: default");
240 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700241 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
242 UsageError(" Default: disabled");
243 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800244 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800246 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100247 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100249 UsageError(" --compiler-filter="
250 "(verify-none"
251 "|interpret-only"
252 "|space"
253 "|balanced"
254 "|speed"
255 "|everything"
256 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700257 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800258 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800259 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800260 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
262 UsageError(" method for compiler filter tuning.");
263 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
264 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
265 UsageError("");
266 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
267 UsageError(" method for compiler filter tuning.");
268 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
269 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
270 UsageError("");
271 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
272 UsageError(" method for compiler filter tuning.");
273 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
274 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
275 UsageError("");
276 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
277 UsageError(" method for compiler filter tuning.");
278 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
279 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
280 UsageError("");
281 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
282 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700283 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
284 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800285 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
286 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
287 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100288 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
289 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100290 UsageError(" Has priority over the --compiler-filter option. Intended for ");
291 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100292 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
293 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
294 UsageError("");
295 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
296 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100297 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
298 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100299 UsageError(" Example: --inline-max-code-units=%d",
300 CompilerOptions::kDefaultInlineMaxCodeUnits);
301 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
302 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700303 UsageError(" --dump-timing: display a breakdown of where time was spent");
304 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700305 UsageError(" --include-patch-information: Include patching information so the generated code");
306 UsageError(" can have its base address moved without full recompilation.");
307 UsageError("");
308 UsageError(" --no-include-patch-information: Do not include patching information.");
309 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100310 UsageError(" -g");
311 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
312 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
313 UsageError(" This generates all the available information. Unneeded parts can be");
314 UsageError(" stripped using standard command line tools such as strip or objcopy.");
315 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700316 UsageError("");
Roland Levillainb2872da2015-09-02 09:35:25 +0100317 UsageError(" --debuggable: Produce debuggable code. Implies --generate-debug-info.");
318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100320 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700321 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
322 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
323 UsageError(" Use a separate --runtime-arg switch for each argument.");
324 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700325 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000326 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700328 UsageError(" --print-pass-names: print a list of pass names");
329 UsageError("");
330 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
331 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
332 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700333 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
334 "with the setting.");
335 UsageError(" Will print default if no overridden setting exists.");
336 UsageError("");
337 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
338 "Pass2Name:Pass2OptionName:Pass2Option#");
339 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
340 UsageError(" Separator used between options is a comma.");
341 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800342 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
343 UsageError(" Example: --swap-file=/data/tmp/swap.001");
344 UsageError("");
345 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
346 UsageError(" Example: --swap-fd=10");
347 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700348 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
349 UsageError(" Example: --app-image-fd=10");
350 UsageError("");
351 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
352 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
353 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700354 std::cerr << "See log for usage error information\n";
355 exit(EXIT_FAILURE);
356}
357
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358// The primary goal of the watchdog is to prevent stuck build servers
359// during development when fatal aborts lead to a cascade of failures
360// that result in a deadlock.
361class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800362// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363#undef CHECK_PTHREAD_CALL
364#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
365 do { \
366 int rc = call args; \
367 if (rc != 0) { \
368 errno = rc; \
369 std::string message(# call); \
370 message += " failed for "; \
371 message += reason; \
372 Fatal(message); \
373 } \
374 } while (false)
375
376 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700377 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 is_watch_dog_enabled_ = is_watch_dog_enabled;
379 if (!is_watch_dog_enabled_) {
380 return;
381 }
382 shutting_down_ = false;
383 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700384 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
385 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
387 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
388 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
389 }
390 ~WatchDog() {
391 if (!is_watch_dog_enabled_) {
392 return;
393 }
394 const char* reason = "dex2oat watch dog thread shutdown";
395 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
396 shutting_down_ = true;
397 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
398 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
399
Kenny Root51316382014-05-13 14:59:37 -0700400 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401
402 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
403 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
404 }
405
406 private:
407 static void* CallBack(void* arg) {
408 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
409 ::art::SetThreadName("dex2oat watch dog");
410 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700411 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 }
413
Andreas Gampe794ad762015-02-23 08:12:24 -0800414 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700415 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
416 // it's rather easy to hang in unwinding.
417 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
418 // logcat logging or stderr output.
419 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420 exit(1);
421 }
422
423 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
425 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700426 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 timespec timeout_ts;
428 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
429 const char* reason = "dex2oat watch dog thread waiting";
430 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
431 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800432 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700434 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
435 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 } else if (rc != 0) {
437 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
438 strerror(errno)));
439 Fatal(message.c_str());
440 }
441 }
442 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
443 }
444
445 // 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 -0700446 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700447 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800448
Andreas Gampe540138a2015-09-14 15:34:38 -0700449 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
450 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
451 // itself before that watchdog would take down the system server.
452 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453
454 bool is_watch_dog_enabled_;
455 bool shutting_down_;
456 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
457 pthread_mutex_t mutex_;
458 pthread_cond_t cond_;
459 pthread_attr_t attr_;
460 pthread_t pthread_;
461};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800463static constexpr size_t kMinDexFilesForSwap = 2;
464static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
465
466static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
467 if (is_image) {
468 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
469 return false;
470 }
471 if (dex_files.size() < kMinDexFilesForSwap) {
472 // If there are less dex files than the threshold, assume it's gonna be fine.
473 return false;
474 }
475 size_t dex_files_size = 0;
476 for (const auto* dex_file : dex_files) {
477 dex_files_size += dex_file->GetHeader().file_size_;
478 }
479 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
480}
481
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800482class Dex2Oat FINAL {
483 public:
484 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100485 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800486 instruction_set_(kRuntimeISA),
487 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700488 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800489 method_inliner_map_(),
490 runtime_(nullptr),
491 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
492 start_ns_(NanoTime()),
493 oat_fd_(-1),
494 zip_fd_(-1),
495 image_base_(0U),
496 image_classes_zip_filename_(nullptr),
497 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800498 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800499 compiled_classes_zip_filename_(nullptr),
500 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700501 compiled_methods_zip_filename_(nullptr),
502 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700503 app_image_(false),
504 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000506 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700507 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800508 dump_stats_(false),
509 dump_passes_(false),
510 dump_timing_(false),
511 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100512 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800513 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700514 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800515 timings_(timings) {}
516
517 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800518 // Free opened dex files before deleting the runtime_, because ~DexFile
519 // uses MemMap, which is shut down by ~Runtime.
520 class_path_files_.clear();
521 opened_dex_files_.clear();
522
523 // Log completion time before deleting the runtime_, because this accesses
524 // the runtime.
525 LogCompletionTime();
526
Vladimir Marko307dac92015-10-20 11:20:09 +0100527 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
528 // We want to just exit on non-debug builds, not bringing the runtime down
529 // in an orderly fashion. So release the following fields.
530 driver_.release();
531 image_writer_.release();
532 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
533 dex_file.release();
534 }
535 oat_file_.release();
536 runtime_.release();
537 verification_results_.release();
538 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100539 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700540 }
541
Roland Levillain9ec5e222015-08-17 20:18:41 +0100542 struct ParserOptions {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800543 std::string oat_symbols;
544 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800545 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000546 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800547 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100548 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800549
Roland Levillain9ec5e222015-08-17 20:18:41 +0100550 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000551 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100552 }
553
554 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000555 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100556 }
557
558 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000559 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100560 }
561
562 void ParseBase(const StringPiece& option) {
563 DCHECK(option.starts_with("--base="));
564 const char* image_base_str = option.substr(strlen("--base=")).data();
565 char* end;
566 image_base_ = strtoul(image_base_str, &end, 16);
567 if (end == image_base_str || *end != '\0') {
568 Usage("Failed to parse hexadecimal value for option %s", option.data());
569 }
570 }
571
572 void ParseInstructionSet(const StringPiece& option) {
573 DCHECK(option.starts_with("--instruction-set="));
574 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
575 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
576 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
577 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
578 buf.get()[instruction_set_str.length()] = 0;
579 instruction_set_ = GetInstructionSetFromString(buf.get());
580 // arm actually means thumb2.
581 if (instruction_set_ == InstructionSet::kArm) {
582 instruction_set_ = InstructionSet::kThumb2;
583 }
584 }
585
586 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
587 DCHECK(option.starts_with("--instruction-set-variant="));
588 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
589 instruction_set_features_.reset(
590 InstructionSetFeatures::FromVariant(
591 instruction_set_, str.as_string(), &parser_options->error_msg));
592 if (instruction_set_features_.get() == nullptr) {
593 Usage("%s", parser_options->error_msg.c_str());
594 }
595 }
596
597 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
598 DCHECK(option.starts_with("--instruction-set-features="));
599 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
600 if (instruction_set_features_.get() == nullptr) {
601 instruction_set_features_.reset(
602 InstructionSetFeatures::FromVariant(
603 instruction_set_, "default", &parser_options->error_msg));
604 if (instruction_set_features_.get() == nullptr) {
605 Usage("Problem initializing default instruction set features variant: %s",
606 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700607 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800608 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100609 instruction_set_features_.reset(
610 instruction_set_features_->AddFeaturesFromString(str.as_string(),
611 &parser_options->error_msg));
612 if (instruction_set_features_.get() == nullptr) {
613 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
614 }
615 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800616
Roland Levillain9ec5e222015-08-17 20:18:41 +0100617 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
618 DCHECK(option.starts_with("--compiler-backend="));
619 parser_options->requested_specific_compiler = true;
620 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
621 if (backend_str == "Quick") {
622 compiler_kind_ = Compiler::kQuick;
623 } else if (backend_str == "Optimizing") {
624 compiler_kind_ = Compiler::kOptimizing;
625 } else {
626 Usage("Unknown compiler backend: %s", backend_str.data());
627 }
628 }
629
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800630 void ParseImageFormat(const StringPiece& option) {
631 const StringPiece substr("--image-format=");
632 DCHECK(option.starts_with(substr));
633 const StringPiece format_str = option.substr(substr.length());
634 if (format_str == "lz4") {
635 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
636 } else if (format_str == "uncompressed") {
637 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
638 } else {
639 Usage("Unknown image format: %s", format_str.data());
640 }
641 }
642
Roland Levillain9ec5e222015-08-17 20:18:41 +0100643 void ProcessOptions(ParserOptions* parser_options) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700644 boot_image_ = !image_filename_.empty();
645 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
646
647 if (IsAppImage() && IsBootImage()) {
648 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
649 }
650
651 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100652 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000653 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000654 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000655
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800656 if (oat_filename_.empty() && oat_fd_ == -1) {
657 Usage("Output must be supplied with either --oat-file or --oat-fd");
658 }
659
660 if (!oat_filename_.empty() && oat_fd_ != -1) {
661 Usage("--oat-file should not be used with --oat-fd");
662 }
663
Roland Levillain9ec5e222015-08-17 20:18:41 +0100664 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800665 Usage("--oat-symbols should not be used with --oat-fd");
666 }
667
Roland Levillain9ec5e222015-08-17 20:18:41 +0100668 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800669 Usage("--oat-symbols should not be used with --host");
670 }
671
672 if (oat_fd_ != -1 && !image_filename_.empty()) {
673 Usage("--oat-fd should not be used with --image");
674 }
675
676 if (android_root_.empty()) {
677 const char* android_root_env_var = getenv("ANDROID_ROOT");
678 if (android_root_env_var == nullptr) {
679 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800681 android_root_ += android_root_env_var;
682 }
683
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700684 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100685 parser_options->boot_image_filename += android_root_;
686 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800687 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100688 if (!parser_options->boot_image_filename.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800689 boot_image_option_ += "-Ximage:";
Roland Levillain9ec5e222015-08-17 20:18:41 +0100690 boot_image_option_ += parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800691 }
692
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700693 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 Usage("--image-classes should only be used with --image");
695 }
696
697 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
698 Usage("--image-classes should not be used with --boot-image");
699 }
700
701 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
702 Usage("--image-classes-zip should be used with --image-classes");
703 }
704
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700705 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800706 Usage("--compiled-classes should only be used with --image");
707 }
708
709 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
710 Usage("--compiled-classes should not be used with --boot-image");
711 }
712
713 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
714 Usage("--compiled-classes-zip should be used with --compiled-classes");
715 }
716
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800717 if (dex_filenames_.empty() && zip_fd_ == -1) {
718 Usage("Input must be supplied with either --dex-file or --zip-fd");
719 }
720
721 if (!dex_filenames_.empty() && zip_fd_ != -1) {
722 Usage("--dex-file should not be used with --zip-fd");
723 }
724
725 if (!dex_filenames_.empty() && !zip_location_.empty()) {
726 Usage("--dex-file should not be used with --zip-location");
727 }
728
729 if (dex_locations_.empty()) {
730 for (const char* dex_file_name : dex_filenames_) {
731 dex_locations_.push_back(dex_file_name);
732 }
733 } else if (dex_locations_.size() != dex_filenames_.size()) {
734 Usage("--dex-location arguments do not match --dex-file arguments");
735 }
736
737 if (zip_fd_ != -1 && zip_location_.empty()) {
738 Usage("--zip-location should be supplied with --zip-fd");
739 }
740
741 if (boot_image_option_.empty()) {
742 if (image_base_ == 0) {
743 Usage("Non-zero --base not specified");
744 }
745 }
746
747 oat_stripped_ = oat_filename_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100748 if (!parser_options->oat_symbols.empty()) {
749 oat_unstripped_ = parser_options->oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 oat_unstripped_ = oat_filename_;
752 }
753
754 // If no instruction set feature was given, use the default one for the target
755 // instruction set.
756 if (instruction_set_features_.get() == nullptr) {
757 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100758 InstructionSetFeatures::FromVariant(
759 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800760 if (instruction_set_features_.get() == nullptr) {
761 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100762 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800763 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800764 }
765
766 if (instruction_set_ == kRuntimeISA) {
767 std::unique_ptr<const InstructionSetFeatures> runtime_features(
768 InstructionSetFeatures::FromCppDefines());
769 if (!instruction_set_features_->Equals(runtime_features.get())) {
770 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
771 << *instruction_set_features_ << ") and those of dex2oat executable ("
772 << *runtime_features <<") for the command line:\n"
773 << CommandLine();
774 }
775 }
776
Roland Levillaina215b952015-08-07 11:38:32 +0100777 // It they are not set, use default values for inlining settings.
778 // TODO: We should rethink the compiler filter. We mostly save
779 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000780 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
781 compiler_options_->inline_depth_limit_ =
782 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100783 // Implementation of the space filter: limit inlining depth.
784 ? CompilerOptions::kSpaceFilterInlineDepthLimit
785 : CompilerOptions::kDefaultInlineDepthLimit;
786 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000787 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
788 compiler_options_->inline_max_code_units_ =
789 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100790 // Implementation of the space filter: limit inlining max code units.
791 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
792 : CompilerOptions::kDefaultInlineMaxCodeUnits;
793 }
794
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800796 // Set the compilation target's implicit checks options.
797 switch (instruction_set_) {
798 case kArm:
799 case kThumb2:
800 case kArm64:
801 case kX86:
802 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700803 case kMips:
804 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000805 compiler_options_->implicit_null_checks_ = true;
806 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 break;
808
809 default:
810 // Defaults are correct.
811 break;
812 }
813
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000814 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800815
816 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100817 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800818 watchdog_.reset(new WatchDog(true));
819 }
820
821 // Fill some values into the key-value store for the oat header.
822 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100823 }
824
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000825 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100826 std::ostringstream oss;
827 for (int i = 0; i < argc; ++i) {
828 if (i > 0) {
829 oss << ' ';
830 }
831 oss << argv[i];
832 }
833 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
834 oss.str(""); // Reset.
835 oss << kRuntimeISA;
836 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
837 key_value_store_->Put(
838 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000839 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100840 key_value_store_->Put(
841 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000842 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100843 }
844
845 // Parse the arguments from the command line. In case of an unrecognized option or impossible
846 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
847 // returns, arguments have been successfully parsed.
848 void ParseArgs(int argc, char** argv) {
849 original_argc = argc;
850 original_argv = argv;
851
852 InitLogging(argv);
853
854 // Skip over argv[0].
855 argv++;
856 argc--;
857
858 if (argc == 0) {
859 Usage("No arguments specified");
860 }
861
862 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000863 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100864
865 for (int i = 0; i < argc; i++) {
866 const StringPiece option(argv[i]);
867 const bool log_options = false;
868 if (log_options) {
869 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
870 }
871 if (option.starts_with("--dex-file=")) {
872 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
873 } else if (option.starts_with("--dex-location=")) {
874 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
875 } else if (option.starts_with("--zip-fd=")) {
876 ParseZipFd(option);
877 } else if (option.starts_with("--zip-location=")) {
878 zip_location_ = option.substr(strlen("--zip-location=")).data();
879 } else if (option.starts_with("--oat-file=")) {
880 oat_filename_ = option.substr(strlen("--oat-file=")).data();
881 } else if (option.starts_with("--oat-symbols=")) {
882 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data();
883 } else if (option.starts_with("--oat-fd=")) {
884 ParseOatFd(option);
885 } else if (option == "--watch-dog") {
886 parser_options->watch_dog_enabled = true;
887 } else if (option == "--no-watch-dog") {
888 parser_options->watch_dog_enabled = false;
889 } else if (option.starts_with("-j")) {
890 ParseJ(option);
891 } else if (option.starts_with("--oat-location=")) {
892 oat_location_ = option.substr(strlen("--oat-location=")).data();
893 } else if (option.starts_with("--image=")) {
894 image_filename_ = option.substr(strlen("--image=")).data();
895 } else if (option.starts_with("--image-classes=")) {
896 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
897 } else if (option.starts_with("--image-classes-zip=")) {
898 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800899 } else if (option.starts_with("--image-format=")) {
900 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100901 } else if (option.starts_with("--compiled-classes=")) {
902 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
903 } else if (option.starts_with("--compiled-classes-zip=")) {
904 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
905 } else if (option.starts_with("--compiled-methods=")) {
906 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
907 } else if (option.starts_with("--compiled-methods-zip=")) {
908 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
909 } else if (option.starts_with("--base=")) {
910 ParseBase(option);
911 } else if (option.starts_with("--boot-image=")) {
912 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
913 } else if (option.starts_with("--android-root=")) {
914 android_root_ = option.substr(strlen("--android-root=")).data();
915 } else if (option.starts_with("--instruction-set=")) {
916 ParseInstructionSet(option);
917 } else if (option.starts_with("--instruction-set-variant=")) {
918 ParseInstructionSetVariant(option, parser_options.get());
919 } else if (option.starts_with("--instruction-set-features=")) {
920 ParseInstructionSetFeatures(option, parser_options.get());
921 } else if (option.starts_with("--compiler-backend=")) {
922 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000923 } else if (option.starts_with("--profile-file=")) {
924 profile_file_ = option.substr(strlen("--profile-file=")).data();
925 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
926 } else if (option == "--no-profile-file") {
927 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +0100928 } else if (option == "--host") {
929 is_host_ = true;
930 } else if (option == "--runtime-arg") {
931 if (++i >= argc) {
932 Usage("Missing required argument for --runtime-arg");
933 }
934 if (log_options) {
935 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
936 }
937 runtime_args_.push_back(argv[i]);
938 } else if (option == "--dump-timing") {
939 dump_timing_ = true;
940 } else if (option == "--dump-passes") {
941 dump_passes_ = true;
942 } else if (option.starts_with("--dump-cfg=")) {
943 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +0100944 } else if (option.starts_with("--dump-cfg-append")) {
945 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100946 } else if (option == "--dump-stats") {
947 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000948 } else if (option.starts_with("--swap-file=")) {
949 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
950 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700951 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
952 } else if (option.starts_with("--app-image-file=")) {
953 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
954 } else if (option.starts_with("--app-image-fd=")) {
955 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100956 } else if (option.starts_with("--verbose-methods=")) {
957 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
958 // conditional on having verbost methods.
959 gLogVerbosity.compiler = false;
960 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000961 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100962 Usage("Unknown argument %s", option.data());
963 }
964 }
965
966 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800967
968 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000969 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800970 }
971
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800972 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
973 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800974 bool OpenFile() {
975 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
976 if (create_file) {
977 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
978 if (oat_location_.empty()) {
979 oat_location_ = oat_filename_;
980 }
981 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800982 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800983 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800984 if (oat_file_->SetLength(0) != 0) {
985 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
986 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800987 }
988 if (oat_file_.get() == nullptr) {
989 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
990 return false;
991 }
992 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
993 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800994 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800995 return false;
996 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800997
998 // Swap file handling.
999 //
1000 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1001 // that we can use for swap.
1002 //
1003 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1004 // will immediately unlink to satisfy the swap fd assumption.
1005 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1006 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1007 if (swap_file.get() == nullptr) {
1008 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1009 return false;
1010 }
1011 swap_fd_ = swap_file->Fd();
1012 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1013 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1014 // released immediately.
1015 unlink(swap_file_name_.c_str());
1016 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001017 return true;
1018 }
1019
Andreas Gampea650e702014-12-03 14:28:02 -08001020 void EraseOatFile() {
1021 DCHECK(oat_file_.get() != nullptr);
1022 oat_file_->Erase();
1023 oat_file_.reset();
1024 }
1025
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001026 void Shutdown() {
1027 ScopedObjectAccess soa(Thread::Current());
1028 for (jobject dex_cache : dex_caches_) {
1029 soa.Env()->DeleteLocalRef(dex_cache);
1030 }
1031 dex_caches_.clear();
1032 }
1033
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001034 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1035 // boot class path.
1036 bool Setup() {
1037 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1038 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001039 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1040 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001041 std::string boot_class_path = "-Xbootclasspath:";
1042 boot_class_path += Join(dex_filenames_, ':');
1043 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1044 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1045 boot_class_path_locations += Join(dex_locations_, ':');
1046 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001047 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001048 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001049 }
1050 for (size_t i = 0; i < runtime_args_.size(); i++) {
1051 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001052 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001053
Vladimir Marko307dac92015-10-20 11:20:09 +01001054 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001055 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001056 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001057 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001058 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001059 CompilerCallbacks::CallbackMode::kCompileBootImage :
1060 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001061 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1062 runtime_options.push_back(
1063 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1064
Andreas Gampe1d00add2015-02-27 19:35:46 -08001065 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1066 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1067 // have been stripped in preopting, anyways).
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001068 if (!IsBootImage()) {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001069 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1070 }
Calin Juravle01aaf6e2015-06-19 22:05:39 +01001071 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1072 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1073 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Andreas Gampe1d00add2015-02-27 19:35:46 -08001074
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001075 {
1076 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
1077 if (!CreateRuntime(runtime_options)) {
1078 return false;
1079 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001080 }
1081
1082 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1083 // Runtime::Start, give it away now so that we don't starve GC.
1084 Thread* self = Thread::Current();
1085 self->TransitionFromRunnableToSuspended(kNative);
1086 // If we're doing the image, override the compiler filter to force full compilation. Must be
1087 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1088 // compilation of class initializers.
1089 // Whilst we're in native take the opportunity to initialize well known classes.
1090 WellKnownClasses::Init(self->GetJniEnv());
1091
1092 // If --image-classes was specified, calculate the full list of classes to include in the image
1093 if (image_classes_filename_ != nullptr) {
1094 std::string error_msg;
1095 if (image_classes_zip_filename_ != nullptr) {
1096 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001097 image_classes_filename_,
1098 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001099 } else {
1100 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1101 }
1102 if (image_classes_.get() == nullptr) {
1103 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1104 "': " << error_msg;
1105 return false;
1106 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001107 } else if (IsBootImage()) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001108 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001109 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001110 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1111 // image.
1112 if (compiled_classes_filename_ != nullptr) {
1113 std::string error_msg;
1114 if (compiled_classes_zip_filename_ != nullptr) {
1115 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1116 compiled_classes_filename_,
1117 &error_msg));
1118 } else {
1119 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1120 }
1121 if (compiled_classes_.get() == nullptr) {
1122 LOG(ERROR) << "Failed to create list of compiled classes from '"
1123 << compiled_classes_filename_ << "': " << error_msg;
1124 return false;
1125 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001126 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001127 compiled_classes_.reset(nullptr); // By default compile everything.
1128 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001129 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1130 if (compiled_methods_filename_ != nullptr) {
1131 std::string error_msg;
1132 if (compiled_methods_zip_filename_ != nullptr) {
1133 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1134 compiled_methods_filename_,
1135 nullptr, // No post-processing.
1136 &error_msg));
1137 } else {
1138 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1139 nullptr)); // No post-processing.
1140 }
1141 if (compiled_methods_.get() == nullptr) {
1142 LOG(ERROR) << "Failed to create list of compiled methods from '"
1143 << compiled_methods_filename_ << "': " << error_msg;
1144 return false;
1145 }
1146 } else {
1147 compiled_methods_.reset(nullptr); // By default compile everything.
1148 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001150 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001151 if (boot_image_option_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001152 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001153 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001154 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001155 if (dex_filenames_.empty()) {
1156 ATRACE_BEGIN("Opening zip archive from file descriptor");
1157 std::string error_msg;
1158 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1159 zip_location_.c_str(),
1160 &error_msg));
1161 if (zip_archive.get() == nullptr) {
1162 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1163 << error_msg;
1164 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001165 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001166 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001167 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1168 << "': " << error_msg;
1169 return false;
1170 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001171 for (auto& dex_file : opened_dex_files_) {
1172 dex_files_.push_back(dex_file.get());
1173 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001174 ATRACE_END();
1175 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001176 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001177 if (failure_count > 0) {
1178 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1179 return false;
1180 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001181 for (auto& dex_file : opened_dex_files_) {
1182 dex_files_.push_back(dex_file.get());
1183 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001184 }
1185
1186 constexpr bool kSaveDexInput = false;
1187 if (kSaveDexInput) {
1188 for (size_t i = 0; i < dex_files_.size(); ++i) {
1189 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001190 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1191 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001192 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1193 if (tmp_file.get() == nullptr) {
1194 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1195 << ". Try: adb shell chmod 777 /data/local/tmp";
1196 continue;
1197 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001198 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1199 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1200 UNUSED(tmp_file->Flush());
1201 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001202 LOG(INFO) << "Wrote input to " << tmp_file_name;
1203 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001204 }
1205 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001206 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1207 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 for (const auto& dex_file : dex_files_) {
1209 if (!dex_file->EnableWrite()) {
1210 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001211 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001212 ScopedObjectAccess soa(self);
1213 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001214 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001215 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001216 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001217
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001218 // If we use a swap file, ensure we are above the threshold to make it necessary.
1219 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001220 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001221 close(swap_fd_);
1222 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001223 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001224 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001225 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001226 }
1227 }
1228 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1229
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001230 /*
1231 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1232 * Don't bother to check if we're doing the image.
1233 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001234 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001235 compiler_options_->IsCompilationEnabled() &&
1236 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001237 size_t num_methods = 0;
1238 for (size_t i = 0; i != dex_files_.size(); ++i) {
1239 const DexFile* dex_file = dex_files_[i];
1240 CHECK(dex_file != nullptr);
1241 num_methods += dex_file->NumMethodIds();
1242 }
1243 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1244 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1245 VLOG(compiler) << "Below method threshold, compiling anyways";
1246 }
1247 }
1248
1249 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001250 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001251
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001252 // Create and invoke the compiler driver. This will compile all the dex files.
1253 void Compile() {
1254 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1255 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001256
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001257 // Handle and ClassLoader creation needs to come after Runtime::Create
1258 jobject class_loader = nullptr;
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001259 jobject class_path_class_loader = nullptr;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001260 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001261
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001262 if (!boot_image_option_.empty()) {
1263 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001264 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001265 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001266
1267 // Classpath: first the class-path given.
1268 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001269 for (auto& class_path_file : class_path_files_) {
1270 class_path_files.push_back(class_path_file.get());
1271 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001272
1273 // Store the classpath we have right now.
1274 key_value_store_->Put(OatHeader::kClassPathKey,
1275 OatFile::EncodeDexFileDependencies(class_path_files));
1276
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001277 class_path_class_loader = class_linker->CreatePathClassLoader(self,
1278 class_path_files,
1279 nullptr);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001280
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001281 // Class path loader as parent so that we'll resolve there first.
1282 class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001283 }
1284
Vladimir Marko307dac92015-10-20 11:20:09 +01001285 driver_.reset(new CompilerDriver(compiler_options_.get(),
1286 verification_results_.get(),
1287 &method_inliner_map_,
1288 compiler_kind_,
1289 instruction_set_,
1290 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001291 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001292 image_classes_.release(),
1293 compiled_classes_.release(),
1294 nullptr,
1295 thread_count_,
1296 dump_stats_,
1297 dump_passes_,
1298 dump_cfg_file_name_,
1299 dump_cfg_append_,
1300 compiler_phases_timings_.get(),
1301 swap_fd_,
1302 profile_file_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001303
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001304 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001305 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001306 }
1307
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308 // Notes on the interleaving of creating the image and oat file to
1309 // ensure the references between the two are correct.
1310 //
1311 // Currently we have a memory layout that looks something like this:
1312 //
1313 // +--------------+
1314 // | image |
1315 // +--------------+
1316 // | boot oat |
1317 // +--------------+
1318 // | alloc spaces |
1319 // +--------------+
1320 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001321 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322 //
1323 // 1. The image is expected to be loaded at an absolute address and
1324 // contains Objects with absolute pointers within the image.
1325 //
1326 // 2. There are absolute pointers from Methods in the image to their
1327 // code in the oat.
1328 //
1329 // 3. There are absolute pointers from the code in the oat to Methods
1330 // in the image.
1331 //
1332 // 4. There are absolute pointers from code in the oat to other code
1333 // in the oat.
1334 //
1335 // To get this all correct, we go through several steps.
1336 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001337 // 1. We prepare offsets for all data in the oat file and calculate
1338 // the oat data size and code size. During this stage, we also set
1339 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001340 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001341 // 2. We prepare offsets for the objects in the image and calculate
1342 // the image size.
1343 //
1344 // 3. We create the oat file. Originally this was just our own proprietary
1345 // file but now it is contained within an ELF dynamic object (aka an .so
1346 // file). Since we know the image size and oat data size and code size we
1347 // can prepare the ELF headers and we then know the ELF memory segment
1348 // layout and we can now resolve all references. The compiler provides
1349 // LinkerPatch information in each CompiledMethod and we resolve these,
1350 // using the layout information and image object locations provided by
1351 // image writer, as we're writing the method code.
1352 //
1353 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001354 // will be loaded after itself. Originally when oat file was simply
1355 // memory mapped so we could predict where its contents were based
1356 // on the file size. Now that it is an ELF file, we need to inspect
1357 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001358 // where the oat header is located within.
1359 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001360 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001361 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001362 // load the .so at the desired location at runtime by offsetting the
1363 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001364 // TODO: Do this in step 3. We already know the layout there.
1365 //
1366 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1367 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001368
1369
1370 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1371 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001372 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1373 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001374 bool CreateOatFile() {
1375 CHECK(key_value_store_.get() != nullptr);
1376
1377 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1378
1379 std::unique_ptr<OatWriter> oat_writer;
1380 {
1381 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1382 std::string image_file_location;
1383 uint32_t image_file_location_oat_checksum = 0;
1384 uintptr_t image_file_location_oat_data_begin = 0;
1385 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001386
1387 if (app_image_ && image_base_ == 0) {
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001388 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001389 image_base_ = RoundUp(
1390 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1391 kPageSize);
1392 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1393 }
1394
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001395 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001396 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001397 }
1398
1399 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001400 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001401 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001402 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1403 image_file_location_oat_data_begin =
1404 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1405 image_file_location = image_space->GetImageFilename();
1406 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1407 }
1408
1409 if (!image_file_location.empty()) {
1410 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1411 }
1412
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001413 oat_writer.reset(new OatWriter(dex_files_,
1414 image_file_location_oat_checksum,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001415 image_file_location_oat_data_begin,
1416 image_patch_delta,
Vladimir Marko307dac92015-10-20 11:20:09 +01001417 driver_.get(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001418 image_writer_.get(),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001419 IsBootImage(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001420 timings_,
1421 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001422 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001423
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001424 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001425 // The OatWriter constructor has already updated offsets in methods and we need to
1426 // prepare method offsets in the image address space for direct method patching.
1427 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1428 if (!image_writer_->PrepareImageAddressSpace()) {
1429 LOG(ERROR) << "Failed to prepare image address space.";
1430 return false;
1431 }
1432 }
1433
1434 {
1435 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001436 std::unique_ptr<ElfWriter> elf_writer =
1437 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file_.get());
1438
1439 elf_writer->Start();
1440
1441 OutputStream* rodata = elf_writer->StartRoData();
1442 if (!oat_writer->WriteRodata(rodata)) {
1443 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file_->GetPath();
1444 return false;
1445 }
1446 elf_writer->EndRoData(rodata);
1447
1448 OutputStream* text = elf_writer->StartText();
1449 if (!oat_writer->WriteCode(text)) {
1450 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file_->GetPath();
1451 return false;
1452 }
1453 elf_writer->EndText(text);
1454
1455 elf_writer->SetBssSize(oat_writer->GetBssSize());
1456
1457 elf_writer->WriteDynamicSection();
1458
1459 ArrayRef<const dwarf::MethodDebugInfo> method_infos(oat_writer->GetMethodDebugInfo());
1460 elf_writer->WriteDebugInfo(method_infos);
1461
1462 ArrayRef<const uintptr_t> patch_locations(oat_writer->GetAbsolutePatchLocations());
1463 elf_writer->WritePatchLocations(patch_locations);
1464
1465 if (!elf_writer->End()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001466 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1467 return false;
1468 }
1469 }
1470
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001471 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1472 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473 }
1474
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001475 // If we are compiling an image, invoke the image creation routine. Else just skip.
1476 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001477 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001478 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1479 if (!CreateImageFile()) {
1480 return false;
1481 }
1482 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001483 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001484 return true;
1485 }
1486
Andreas Gampe10e477d2014-11-19 12:57:42 -08001487 // Create a copy from unstripped to stripped.
1488 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001489 // If we don't want to strip in place, copy from unstripped location to stripped location.
1490 // We need to strip after image creation because FixupElf needs to use .strtab.
1491 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001492 // If the oat file is still open, flush it.
1493 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1494 if (!FlushCloseOatFile()) {
1495 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001496 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001497 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001498
1499 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001500 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1501 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1502 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001503 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001504 while (true) {
1505 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1506 if (bytes_read <= 0) {
1507 break;
1508 }
1509 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1510 CHECK(write_ok);
1511 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001512 if (out->FlushCloseOrErase() != 0) {
1513 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1514 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001515 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001516 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001517 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001518 return true;
1519 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001520
Andreas Gampe10e477d2014-11-19 12:57:42 -08001521 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001522 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001523 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1524 if (oat_file_->Flush() != 0) {
1525 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1526 << oat_filename_;
1527 oat_file_->Erase();
1528 return false;
1529 }
1530 }
1531 return true;
1532 }
1533
1534 bool FlushCloseOatFile() {
1535 if (oat_file_.get() != nullptr) {
1536 std::unique_ptr<File> tmp(oat_file_.release());
1537 if (tmp->FlushCloseOrErase() != 0) {
1538 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1539 << oat_filename_;
1540 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001541 }
1542 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001543 return true;
1544 }
1545
1546 void DumpTiming() {
1547 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1548 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1549 }
1550 if (dump_passes_) {
1551 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1552 }
1553 }
1554
1555 CompilerOptions* GetCompilerOptions() const {
1556 return compiler_options_.get();
1557 }
1558
Andreas Gampe10e477d2014-11-19 12:57:42 -08001559 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001560 return IsAppImage() || IsBootImage();
1561 }
1562
1563 bool IsAppImage() const {
1564 return app_image_;
1565 }
1566
1567 bool IsBootImage() const {
1568 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001569 }
1570
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001571 bool IsHost() const {
1572 return is_host_;
1573 }
1574
1575 private:
1576 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1577 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001578 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001579 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001580 size_t failure_count = 0;
1581 for (size_t i = 0; i < dex_filenames.size(); i++) {
1582 const char* dex_filename = dex_filenames[i];
1583 const char* dex_location = dex_locations[i];
1584 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1585 std::string error_msg;
1586 if (!OS::FileExists(dex_filename)) {
1587 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1588 continue;
1589 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001590 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001591 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1592 ++failure_count;
1593 }
1594 ATRACE_END();
1595 }
1596 return failure_count;
1597 }
1598
Andreas Gampee3712d02015-04-09 14:46:31 -07001599 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1600 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1601 // efficient, but under normal circumstances the list is neither large nor is this part too
1602 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1604 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001605 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001606 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001607 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1608 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001609 return true;
1610 }
1611 }
1612 return false;
1613 }
1614
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001615 // Appends to opened_dex_files any elements of class_path that dex_files
1616 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001617 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001618 std::vector<const DexFile*> dex_files,
1619 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001620 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001621 std::vector<std::string> parsed;
1622 Split(class_path, ':', &parsed);
1623 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1624 ScopedObjectAccess soa(Thread::Current());
1625 for (size_t i = 0; i < parsed.size(); ++i) {
1626 if (DexFilesContains(dex_files, parsed[i])) {
1627 continue;
1628 }
1629 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001630 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001631 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1632 }
1633 }
1634 }
1635
1636 // Create a runtime necessary for compilation.
1637 bool CreateRuntime(const RuntimeOptions& runtime_options)
1638 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1639 if (!Runtime::Create(runtime_options, false)) {
1640 LOG(ERROR) << "Failed to create runtime";
1641 return false;
1642 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001643 runtime_.reset(Runtime::Current());
1644 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001645 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1646 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001647 if (!runtime_->HasCalleeSaveMethod(type)) {
1648 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001649 }
1650 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001651 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001652
1653 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1654 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001655 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001656
Vladimir Marko307dac92015-10-20 11:20:09 +01001657 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001658
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001659 return true;
1660 }
1661
1662 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001663 DCHECK(IsImage());
1664 image_writer_.reset(new ImageWriter(*driver_,
1665 image_base,
1666 compiler_options_->GetCompilePic(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001667 IsAppImage(),
1668 image_storage_mode_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001669 }
1670
1671 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1672 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001673 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001674 CHECK(image_writer_ != nullptr);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001675 if (!image_writer_->Write(app_image_fd_,
1676 IsBootImage() ? image_filename_ : app_image_file_name_,
1677 oat_unstripped_,
1678 oat_location_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001679 LOG(ERROR) << "Failed to create image file " << image_filename_;
1680 return false;
1681 }
1682 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1683
1684 // Destroy ImageWriter before doing FixupElf.
1685 image_writer_.reset();
1686
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001687 // Do not fix up the ELF file if we are --compile-pic or compiing the app image
1688 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001689 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1690 if (oat_file.get() == nullptr) {
1691 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1692 return false;
1693 }
1694
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001696 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001697 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1698 return false;
1699 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001700
1701 if (oat_file->FlushCloseOrErase()) {
1702 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1703 return false;
1704 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001705 }
1706
1707 return true;
1708 }
1709
1710 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001711 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1712 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001713 std::function<std::string(const char*)> process = DotToDescriptor;
1714 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 }
1716
1717 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001718 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001719 const char* zip_filename,
1720 const char* image_classes_filename,
1721 std::string* error_msg) {
1722 std::function<std::string(const char*)> process = DotToDescriptor;
1723 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1724 }
1725
1726 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1727 // the given function.
1728 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1729 const char* input_filename, std::function<std::string(const char*)>* process) {
1730 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1731 if (input_file.get() == nullptr) {
1732 LOG(ERROR) << "Failed to open input file " << input_filename;
1733 return nullptr;
1734 }
1735 std::unique_ptr<std::unordered_set<std::string>> result(
1736 ReadCommentedInputStream(*input_file, process));
1737 input_file->close();
1738 return result.release();
1739 }
1740
1741 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1742 // Post-process each line with the given function.
1743 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001744 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001745 const char* input_filename,
1746 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001747 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001748 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1749 if (zip_archive.get() == nullptr) {
1750 return nullptr;
1751 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001752 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001753 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001754 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001755 zip_filename, error_msg->c_str());
1756 return nullptr;
1757 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001758 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1759 input_filename,
1760 error_msg));
1761 if (input_file.get() == nullptr) {
1762 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001763 zip_filename, error_msg->c_str());
1764 return nullptr;
1765 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001766 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1767 input_file->Size());
1768 std::istringstream input_stream(input_string);
1769 return ReadCommentedInputStream(input_stream, process);
1770 }
1771
1772 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1773 // with the given function.
1774 static std::unordered_set<std::string>* ReadCommentedInputStream(
1775 std::istream& in_stream,
1776 std::function<std::string(const char*)>* process) {
1777 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1778 new std::unordered_set<std::string>);
1779 while (in_stream.good()) {
1780 std::string dot;
1781 std::getline(in_stream, dot);
1782 if (StartsWith(dot, "#") || dot.empty()) {
1783 continue;
1784 }
1785 if (process != nullptr) {
1786 std::string descriptor((*process)(dot.c_str()));
1787 image_classes->insert(descriptor);
1788 } else {
1789 image_classes->insert(dot);
1790 }
1791 }
1792 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001793 }
1794
Mathieu Chartier49285c52014-12-02 15:43:48 -08001795 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001796 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1797 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001798 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001799 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001800 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07001801 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001802 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1803 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001804 }
1805
1806 std::unique_ptr<CompilerOptions> compiler_options_;
1807 Compiler::Kind compiler_kind_;
1808
1809 InstructionSet instruction_set_;
1810 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1811
1812 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1813
Vladimir Marko307dac92015-10-20 11:20:09 +01001814 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001815
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001816 DexFileToMethodInlinerMap method_inliner_map_;
1817 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1818
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001819 // Ownership for the class path files.
1820 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1821
Vladimir Marko307dac92015-10-20 11:20:09 +01001822 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001823
1824 size_t thread_count_;
1825 uint64_t start_ns_;
1826 std::unique_ptr<WatchDog> watchdog_;
1827 std::unique_ptr<File> oat_file_;
1828 std::string oat_stripped_;
1829 std::string oat_unstripped_;
1830 std::string oat_location_;
1831 std::string oat_filename_;
1832 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001833 std::vector<const char*> dex_filenames_;
1834 std::vector<const char*> dex_locations_;
1835 int zip_fd_;
1836 std::string zip_location_;
1837 std::string boot_image_option_;
1838 std::vector<const char*> runtime_args_;
1839 std::string image_filename_;
1840 uintptr_t image_base_;
1841 const char* image_classes_zip_filename_;
1842 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001843 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001844 const char* compiled_classes_zip_filename_;
1845 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001846 const char* compiled_methods_zip_filename_;
1847 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001848 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1849 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001850 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001851 bool app_image_;
1852 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001853 bool is_host_;
1854 std::string android_root_;
1855 std::vector<const DexFile*> dex_files_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001856 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001857 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001858
Vladimir Marko307dac92015-10-20 11:20:09 +01001859 std::unique_ptr<ImageWriter> image_writer_;
1860 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001861
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001862 std::vector<std::string> verbose_methods_;
1863 bool dump_stats_;
1864 bool dump_passes_;
1865 bool dump_timing_;
1866 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001867 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01001868 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001869 std::string swap_file_name_;
1870 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001871 std::string app_image_file_name_;
1872 int app_image_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001873 std::string profile_file_; // Profile file to use
1874 TimingLogger* timings_;
1875 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1876
1877 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1878};
1879
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001880static void b13564922() {
1881#if defined(__linux__) && defined(__arm__)
1882 int major, minor;
1883 struct utsname uts;
1884 if (uname(&uts) != -1 &&
1885 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1886 ((major < 3) || ((major == 3) && (minor < 4)))) {
1887 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1888 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1889 int old_personality = personality(0xffffffff);
1890 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1891 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1892 if (new_personality == -1) {
1893 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1894 }
1895 }
1896 }
1897#endif
1898}
1899
Andreas Gampe10e477d2014-11-19 12:57:42 -08001900static int CompileImage(Dex2Oat& dex2oat) {
1901 dex2oat.Compile();
1902
1903 // Create the boot.oat.
1904 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001905 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001906 return EXIT_FAILURE;
1907 }
1908
1909 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1910 // re-opened from the unstripped name.
1911 if (!dex2oat.FlushCloseOatFile()) {
1912 return EXIT_FAILURE;
1913 }
1914
1915 // Creates the boot.art and patches the boot.oat.
1916 if (!dex2oat.HandleImage()) {
1917 return EXIT_FAILURE;
1918 }
1919
1920 // When given --host, finish early without stripping.
1921 if (dex2oat.IsHost()) {
1922 dex2oat.DumpTiming();
1923 return EXIT_SUCCESS;
1924 }
1925
1926 // Copy unstripped to stripped location, if necessary.
1927 if (!dex2oat.CopyUnstrippedToStripped()) {
1928 return EXIT_FAILURE;
1929 }
1930
Andreas Gampe10e477d2014-11-19 12:57:42 -08001931 // FlushClose again, as stripping might have re-opened the oat file.
1932 if (!dex2oat.FlushCloseOatFile()) {
1933 return EXIT_FAILURE;
1934 }
1935
1936 dex2oat.DumpTiming();
1937 return EXIT_SUCCESS;
1938}
1939
1940static int CompileApp(Dex2Oat& dex2oat) {
1941 dex2oat.Compile();
1942
1943 // Create the app oat.
1944 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001945 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001946 return EXIT_FAILURE;
1947 }
1948
1949 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1950 // which we would lose.
1951 if (!dex2oat.FlushOatFile()) {
1952 return EXIT_FAILURE;
1953 }
1954
1955 // When given --host, finish early without stripping.
1956 if (dex2oat.IsHost()) {
1957 if (!dex2oat.FlushCloseOatFile()) {
1958 return EXIT_FAILURE;
1959 }
1960
1961 dex2oat.DumpTiming();
1962 return EXIT_SUCCESS;
1963 }
1964
1965 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1966 // unstripped version. If this is given, we expect to be able to open writable files by name.
1967 if (!dex2oat.CopyUnstrippedToStripped()) {
1968 return EXIT_FAILURE;
1969 }
1970
Andreas Gampe10e477d2014-11-19 12:57:42 -08001971 // Flush and close the file.
1972 if (!dex2oat.FlushCloseOatFile()) {
1973 return EXIT_FAILURE;
1974 }
1975
1976 dex2oat.DumpTiming();
1977 return EXIT_SUCCESS;
1978}
1979
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001980static int dex2oat(int argc, char** argv) {
1981 b13564922();
1982
1983 TimingLogger timings("compiler", false, false);
1984
1985 Dex2Oat dex2oat(&timings);
1986
1987 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1988 dex2oat.ParseArgs(argc, argv);
1989
1990 // Check early that the result of compilation can be written
1991 if (!dex2oat.OpenFile()) {
1992 return EXIT_FAILURE;
1993 }
1994
Andreas Gampe046c7062015-05-18 23:22:54 -07001995 // Print the complete line when any of the following is true:
1996 // 1) Debug build
1997 // 2) Compiling an image
1998 // 3) Compiling with --host
1999 // 4) Compiling on the host (not a target build)
2000 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002001 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002002 LOG(INFO) << CommandLine();
2003 } else {
2004 LOG(INFO) << StrippedCommandLine();
2005 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002006
2007 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002008 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002009 return EXIT_FAILURE;
2010 }
2011
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002012 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002013 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002014 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002015 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002016 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002017 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002018
2019 dex2oat.Shutdown();
2020 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002021}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002022} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002023
2024int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002025 int result = art::dex2oat(argc, argv);
2026 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2027 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2028 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002029 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002030 exit(result);
2031 }
2032 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002033}