blob: bb4224b7c1f15f70e296c573a452d38f9df9caa5 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000053#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick_compiler_callbacks.h"
55#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000058#include "dwarf/method_debug_info.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/class-inl.h"
68#include "mirror/class_loader.h"
69#include "mirror/object-inl.h"
70#include "mirror/object_array-inl.h"
71#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "os.h"
73#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000074#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "ScopedLocalRef.h"
76#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070077#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "well_known_classes.h"
79#include "zip_archive.h"
80
81namespace art {
82
Brian Carlstrom6449c622014-02-10 23:48:36 -080083static int original_argc;
84static char** original_argv;
85
86static std::string CommandLine() {
87 std::vector<std::string> command;
88 for (int i = 0; i < original_argc; ++i) {
89 command.push_back(original_argv[i]);
90 }
91 return Join(command, ' ');
92}
93
Andreas Gampe046c7062015-05-18 23:22:54 -070094// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
95// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
96// locations are all staged).
97static std::string StrippedCommandLine() {
98 std::vector<std::string> command;
99
100 // Do a pre-pass to look for zip-fd.
101 bool saw_zip_fd = false;
102 for (int i = 0; i < original_argc; ++i) {
103 if (StartsWith(original_argv[i], "--zip-fd=")) {
104 saw_zip_fd = true;
105 break;
106 }
107 }
108
109 // Now filter out things.
110 for (int i = 0; i < original_argc; ++i) {
111 // All runtime-arg parameters are dropped.
112 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
113 i++; // Drop the next part, too.
114 continue;
115 }
116
117 // Any instruction-setXXX is dropped.
118 if (StartsWith(original_argv[i], "--instruction-set")) {
119 continue;
120 }
121
122 // The boot image is dropped.
123 if (StartsWith(original_argv[i], "--boot-image=")) {
124 continue;
125 }
126
127 // This should leave any dex-file and oat-file options, describing what we compiled.
128
129 // However, we prefer to drop this when we saw --zip-fd.
130 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700131 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700132 if (StartsWith(original_argv[i], "--zip-") ||
133 StartsWith(original_argv[i], "--dex-") ||
134 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700135 StartsWith(original_argv[i], "--swap-") ||
136 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700137 continue;
138 }
139 }
140
141 command.push_back(original_argv[i]);
142 }
143
144 // Construct the final output.
145 if (command.size() <= 1U) {
146 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
147 return "Starting dex2oat.";
148 }
149 return Join(command, ' ');
150}
151
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152static void UsageErrorV(const char* fmt, va_list ap) {
153 std::string error;
154 StringAppendV(&error, fmt, ap);
155 LOG(ERROR) << error;
156}
157
158static void UsageError(const char* fmt, ...) {
159 va_list ap;
160 va_start(ap, fmt);
161 UsageErrorV(fmt, ap);
162 va_end(ap);
163}
164
Andreas Gampe794ad762015-02-23 08:12:24 -0800165NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 va_list ap;
167 va_start(ap, fmt);
168 UsageErrorV(fmt, ap);
169 va_end(ap);
170
Brian Carlstrom6449c622014-02-10 23:48:36 -0800171 UsageError("Command: %s", CommandLine().c_str());
172
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 UsageError("Usage: dex2oat [options]...");
174 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100175 UsageError(" -j<number>: specifies the number of threads used for compilation.");
176 UsageError(" Default is the number of detected hardware threads available on the");
177 UsageError(" host system.");
178 UsageError(" Example: -j12");
179 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700180 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 UsageError(" Example: --dex-file=/system/framework/core.jar");
182 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700183 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
184 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
185 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
186 UsageError(" --dex-location=/system/framework/core.jar");
187 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
189 UsageError(" containing a classes.dex file to compile.");
190 UsageError(" Example: --zip-fd=5");
191 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700192 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
193 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
195 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800196 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 UsageError(" Example: --oat-file=/system/framework/boot.oat");
198 UsageError("");
199 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900200 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 UsageError("");
202 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
203 UsageError(" to the file descriptor specified by --oat-fd.");
204 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
205 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800206 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700207 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
208 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800209 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 UsageError(" Example: --image=/system/framework/boot.art");
211 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800212 UsageError(" --image-format=(uncompressed|lz4):");
213 UsageError(" Which format to store the image.");
214 UsageError(" Example: --image-format=lz4");
215 UsageError(" Default: uncompressed");
216 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
218 UsageError(" Example: --image=frameworks/base/preloaded-classes");
219 UsageError("");
220 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
221 UsageError(" Example: --base=0x50000000");
222 UsageError("");
223 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000224 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000226 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000227 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError("");
229 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
230 UsageError(" Example: --android-root=out/host/linux-x86");
231 UsageError(" Default: $ANDROID_ROOT");
232 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800233 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700234 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 UsageError(" Example: --instruction-set=x86");
236 UsageError(" Default: arm");
237 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700238 UsageError(" --instruction-set-features=...,: Specify instruction set features");
239 UsageError(" Example: --instruction-set-features=div");
240 UsageError(" Default: default");
241 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700242 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
243 UsageError(" Default: disabled");
244 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800245 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800247 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100248 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700249 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100250 UsageError(" --compiler-filter="
251 "(verify-none"
252 "|interpret-only"
253 "|space"
254 "|balanced"
255 "|speed"
256 "|everything"
257 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700258 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800259 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800260 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800262 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
263 UsageError(" method for compiler filter tuning.");
264 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
265 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
266 UsageError("");
267 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
268 UsageError(" method for compiler filter tuning.");
269 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
270 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
271 UsageError("");
272 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
273 UsageError(" method for compiler filter tuning.");
274 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
275 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
276 UsageError("");
277 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
278 UsageError(" method for compiler filter tuning.");
279 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
280 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
281 UsageError("");
282 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
283 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700284 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
285 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800286 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
287 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
288 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100289 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
290 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100291 UsageError(" Has priority over the --compiler-filter option. Intended for ");
292 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100293 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
294 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
295 UsageError("");
296 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
297 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100298 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
299 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100300 UsageError(" Example: --inline-max-code-units=%d",
301 CompilerOptions::kDefaultInlineMaxCodeUnits);
302 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
303 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700304 UsageError(" --dump-timing: display a breakdown of where time was spent");
305 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700306 UsageError(" --include-patch-information: Include patching information so the generated code");
307 UsageError(" can have its base address moved without full recompilation.");
308 UsageError("");
309 UsageError(" --no-include-patch-information: Do not include patching information.");
310 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100311 UsageError(" -g");
312 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
313 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
314 UsageError(" This generates all the available information. Unneeded parts can be");
315 UsageError(" stripped using standard command line tools such as strip or objcopy.");
316 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700317 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100318 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100319 UsageError("");
David Srbecky0cf44932015-12-09 14:09:59 +0000320 UsageError(" --debuggable: Produce code debuggable with Java debugger. Implies -g.");
321 UsageError("");
322 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
323 UsageError(" Implies --debuggable.");
324 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
326 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
327 UsageError(" Use a separate --runtime-arg switch for each argument.");
328 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700329 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000330 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700332 UsageError(" --print-pass-names: print a list of pass names");
333 UsageError("");
334 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
335 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
336 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700337 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
338 "with the setting.");
339 UsageError(" Will print default if no overridden setting exists.");
340 UsageError("");
341 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
342 "Pass2Name:Pass2OptionName:Pass2Option#");
343 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
344 UsageError(" Separator used between options is a comma.");
345 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800346 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
347 UsageError(" Example: --swap-file=/data/tmp/swap.001");
348 UsageError("");
349 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
350 UsageError(" Example: --swap-fd=10");
351 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700352 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
353 UsageError(" Example: --app-image-fd=10");
354 UsageError("");
355 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
356 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
357 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800358 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
359 "input dex file.");
360 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700361 std::cerr << "See log for usage error information\n";
362 exit(EXIT_FAILURE);
363}
364
Brian Carlstrom7940e442013-07-12 13:46:57 -0700365// The primary goal of the watchdog is to prevent stuck build servers
366// during development when fatal aborts lead to a cascade of failures
367// that result in a deadlock.
368class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800369// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370#undef CHECK_PTHREAD_CALL
371#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
372 do { \
373 int rc = call args; \
374 if (rc != 0) { \
375 errno = rc; \
376 std::string message(# call); \
377 message += " failed for "; \
378 message += reason; \
379 Fatal(message); \
380 } \
381 } while (false)
382
383 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700384 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 is_watch_dog_enabled_ = is_watch_dog_enabled;
386 if (!is_watch_dog_enabled_) {
387 return;
388 }
389 shutting_down_ = false;
390 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700391 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
392 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
394 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
395 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
396 }
397 ~WatchDog() {
398 if (!is_watch_dog_enabled_) {
399 return;
400 }
401 const char* reason = "dex2oat watch dog thread shutdown";
402 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
403 shutting_down_ = true;
404 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
405 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
406
Kenny Root51316382014-05-13 14:59:37 -0700407 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700408
409 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
411 }
412
413 private:
414 static void* CallBack(void* arg) {
415 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
416 ::art::SetThreadName("dex2oat watch dog");
417 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700418 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419 }
420
Andreas Gampe794ad762015-02-23 08:12:24 -0800421 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700422 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
423 // it's rather easy to hang in unwinding.
424 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
425 // logcat logging or stderr output.
426 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 exit(1);
428 }
429
430 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
432 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700433 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700434 timespec timeout_ts;
435 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
436 const char* reason = "dex2oat watch dog thread waiting";
437 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
438 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800439 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700441 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
442 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 } else if (rc != 0) {
444 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
445 strerror(errno)));
446 Fatal(message.c_str());
447 }
448 }
449 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
450 }
451
452 // 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 -0700453 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700454 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455
Andreas Gampe540138a2015-09-14 15:34:38 -0700456 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
457 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
458 // itself before that watchdog would take down the system server.
459 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460
461 bool is_watch_dog_enabled_;
462 bool shutting_down_;
463 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
464 pthread_mutex_t mutex_;
465 pthread_cond_t cond_;
466 pthread_attr_t attr_;
467 pthread_t pthread_;
468};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800470static constexpr size_t kMinDexFilesForSwap = 2;
471static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
472
473static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
474 if (is_image) {
475 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
476 return false;
477 }
478 if (dex_files.size() < kMinDexFilesForSwap) {
479 // If there are less dex files than the threshold, assume it's gonna be fine.
480 return false;
481 }
482 size_t dex_files_size = 0;
483 for (const auto* dex_file : dex_files) {
484 dex_files_size += dex_file->GetHeader().file_size_;
485 }
486 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
487}
488
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800489class Dex2Oat FINAL {
490 public:
491 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100492 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800493 instruction_set_(kRuntimeISA),
494 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700495 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800496 method_inliner_map_(),
497 runtime_(nullptr),
498 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
499 start_ns_(NanoTime()),
500 oat_fd_(-1),
501 zip_fd_(-1),
502 image_base_(0U),
503 image_classes_zip_filename_(nullptr),
504 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800505 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800506 compiled_classes_zip_filename_(nullptr),
507 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700508 compiled_methods_zip_filename_(nullptr),
509 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700510 app_image_(false),
511 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800512 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000513 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700514 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800515 dump_stats_(false),
516 dump_passes_(false),
517 dump_timing_(false),
518 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100519 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800520 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700521 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800522 timings_(timings) {}
523
524 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800525 // Free opened dex files before deleting the runtime_, because ~DexFile
526 // uses MemMap, which is shut down by ~Runtime.
527 class_path_files_.clear();
528 opened_dex_files_.clear();
529
530 // Log completion time before deleting the runtime_, because this accesses
531 // the runtime.
532 LogCompletionTime();
533
Vladimir Marko307dac92015-10-20 11:20:09 +0100534 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
535 // We want to just exit on non-debug builds, not bringing the runtime down
536 // in an orderly fashion. So release the following fields.
537 driver_.release();
538 image_writer_.release();
539 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
540 dex_file.release();
541 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800542 for (std::unique_ptr<File>& oat_file : oat_files_) {
543 oat_file.release();
544 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100545 runtime_.release();
546 verification_results_.release();
547 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100548 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700549 }
550
Roland Levillain9ec5e222015-08-17 20:18:41 +0100551 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800552 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800553 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800554 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000555 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100557 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800558
Roland Levillain9ec5e222015-08-17 20:18:41 +0100559 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000560 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100561 }
562
563 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000564 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100565 }
566
567 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000568 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100569 }
570
571 void ParseBase(const StringPiece& option) {
572 DCHECK(option.starts_with("--base="));
573 const char* image_base_str = option.substr(strlen("--base=")).data();
574 char* end;
575 image_base_ = strtoul(image_base_str, &end, 16);
576 if (end == image_base_str || *end != '\0') {
577 Usage("Failed to parse hexadecimal value for option %s", option.data());
578 }
579 }
580
581 void ParseInstructionSet(const StringPiece& option) {
582 DCHECK(option.starts_with("--instruction-set="));
583 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
584 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
585 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
586 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
587 buf.get()[instruction_set_str.length()] = 0;
588 instruction_set_ = GetInstructionSetFromString(buf.get());
589 // arm actually means thumb2.
590 if (instruction_set_ == InstructionSet::kArm) {
591 instruction_set_ = InstructionSet::kThumb2;
592 }
593 }
594
595 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
596 DCHECK(option.starts_with("--instruction-set-variant="));
597 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
598 instruction_set_features_.reset(
599 InstructionSetFeatures::FromVariant(
600 instruction_set_, str.as_string(), &parser_options->error_msg));
601 if (instruction_set_features_.get() == nullptr) {
602 Usage("%s", parser_options->error_msg.c_str());
603 }
604 }
605
606 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
607 DCHECK(option.starts_with("--instruction-set-features="));
608 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
609 if (instruction_set_features_.get() == nullptr) {
610 instruction_set_features_.reset(
611 InstructionSetFeatures::FromVariant(
612 instruction_set_, "default", &parser_options->error_msg));
613 if (instruction_set_features_.get() == nullptr) {
614 Usage("Problem initializing default instruction set features variant: %s",
615 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700616 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800617 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100618 instruction_set_features_.reset(
619 instruction_set_features_->AddFeaturesFromString(str.as_string(),
620 &parser_options->error_msg));
621 if (instruction_set_features_.get() == nullptr) {
622 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
623 }
624 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800625
Roland Levillain9ec5e222015-08-17 20:18:41 +0100626 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
627 DCHECK(option.starts_with("--compiler-backend="));
628 parser_options->requested_specific_compiler = true;
629 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
630 if (backend_str == "Quick") {
631 compiler_kind_ = Compiler::kQuick;
632 } else if (backend_str == "Optimizing") {
633 compiler_kind_ = Compiler::kOptimizing;
634 } else {
635 Usage("Unknown compiler backend: %s", backend_str.data());
636 }
637 }
638
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800639 void ParseImageFormat(const StringPiece& option) {
640 const StringPiece substr("--image-format=");
641 DCHECK(option.starts_with(substr));
642 const StringPiece format_str = option.substr(substr.length());
643 if (format_str == "lz4") {
644 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
645 } else if (format_str == "uncompressed") {
646 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
647 } else {
648 Usage("Unknown image format: %s", format_str.data());
649 }
650 }
651
Jeff Haodcdc85b2015-12-04 14:06:18 -0800652 void ProcessOptions(ParserOptions* parser_options, bool multi_image) {
653 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700654 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
655
656 if (IsAppImage() && IsBootImage()) {
657 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
658 }
659
660 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100661 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000662 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000663 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000664
Jeff Haodcdc85b2015-12-04 14:06:18 -0800665 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800666 Usage("Output must be supplied with either --oat-file or --oat-fd");
667 }
668
Jeff Haodcdc85b2015-12-04 14:06:18 -0800669 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800670 Usage("--oat-file should not be used with --oat-fd");
671 }
672
Roland Levillain9ec5e222015-08-17 20:18:41 +0100673 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800674 Usage("--oat-symbols should not be used with --oat-fd");
675 }
676
Roland Levillain9ec5e222015-08-17 20:18:41 +0100677 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800678 Usage("--oat-symbols should not be used with --host");
679 }
680
Jeff Haodcdc85b2015-12-04 14:06:18 -0800681 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682 Usage("--oat-fd should not be used with --image");
683 }
684
Jeff Haodcdc85b2015-12-04 14:06:18 -0800685 if (!parser_options->oat_symbols.empty() &&
686 parser_options->oat_symbols.size() != oat_filenames_.size()) {
687 Usage("--oat-file arguments do not match --oat-symbols arguments");
688 }
689
690 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
691 Usage("--oat-file arguments do not match --image arguments");
692 }
693
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 if (android_root_.empty()) {
695 const char* android_root_env_var = getenv("ANDROID_ROOT");
696 if (android_root_env_var == nullptr) {
697 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800699 android_root_ += android_root_env_var;
700 }
701
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700702 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100703 parser_options->boot_image_filename += android_root_;
704 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100706 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000707 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 }
709
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700710 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 Usage("--image-classes should only be used with --image");
712 }
713
Vladimir Marko49b0f452015-12-10 13:49:19 +0000714 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800715 Usage("--image-classes should not be used with --boot-image");
716 }
717
718 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
719 Usage("--image-classes-zip should be used with --image-classes");
720 }
721
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700722 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800723 Usage("--compiled-classes should only be used with --image");
724 }
725
Vladimir Marko49b0f452015-12-10 13:49:19 +0000726 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800727 Usage("--compiled-classes should not be used with --boot-image");
728 }
729
730 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
731 Usage("--compiled-classes-zip should be used with --compiled-classes");
732 }
733
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 if (dex_filenames_.empty() && zip_fd_ == -1) {
735 Usage("Input must be supplied with either --dex-file or --zip-fd");
736 }
737
738 if (!dex_filenames_.empty() && zip_fd_ != -1) {
739 Usage("--dex-file should not be used with --zip-fd");
740 }
741
742 if (!dex_filenames_.empty() && !zip_location_.empty()) {
743 Usage("--dex-file should not be used with --zip-location");
744 }
745
746 if (dex_locations_.empty()) {
747 for (const char* dex_file_name : dex_filenames_) {
748 dex_locations_.push_back(dex_file_name);
749 }
750 } else if (dex_locations_.size() != dex_filenames_.size()) {
751 Usage("--dex-location arguments do not match --dex-file arguments");
752 }
753
Jeff Haodcdc85b2015-12-04 14:06:18 -0800754 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
755 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
756 Usage("--oat-file arguments must be singular or match --dex-file arguments");
757 }
758 }
759
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800760 if (zip_fd_ != -1 && zip_location_.empty()) {
761 Usage("--zip-location should be supplied with --zip-fd");
762 }
763
Vladimir Marko49b0f452015-12-10 13:49:19 +0000764 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800765 if (image_base_ == 0) {
766 Usage("Non-zero --base not specified");
767 }
768 }
769
Roland Levillain9ec5e222015-08-17 20:18:41 +0100770 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800771 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800772 }
773
774 // If no instruction set feature was given, use the default one for the target
775 // instruction set.
776 if (instruction_set_features_.get() == nullptr) {
777 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100778 InstructionSetFeatures::FromVariant(
779 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800780 if (instruction_set_features_.get() == nullptr) {
781 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100782 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800783 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800784 }
785
786 if (instruction_set_ == kRuntimeISA) {
787 std::unique_ptr<const InstructionSetFeatures> runtime_features(
788 InstructionSetFeatures::FromCppDefines());
789 if (!instruction_set_features_->Equals(runtime_features.get())) {
790 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
791 << *instruction_set_features_ << ") and those of dex2oat executable ("
792 << *runtime_features <<") for the command line:\n"
793 << CommandLine();
794 }
795 }
796
Roland Levillaina215b952015-08-07 11:38:32 +0100797 // It they are not set, use default values for inlining settings.
798 // TODO: We should rethink the compiler filter. We mostly save
799 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000800 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
801 compiler_options_->inline_depth_limit_ =
802 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100803 // Implementation of the space filter: limit inlining depth.
804 ? CompilerOptions::kSpaceFilterInlineDepthLimit
805 : CompilerOptions::kDefaultInlineDepthLimit;
806 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000807 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
808 compiler_options_->inline_max_code_units_ =
809 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100810 // Implementation of the space filter: limit inlining max code units.
811 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
812 : CompilerOptions::kDefaultInlineMaxCodeUnits;
813 }
814
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800815 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800816 // Set the compilation target's implicit checks options.
817 switch (instruction_set_) {
818 case kArm:
819 case kThumb2:
820 case kArm64:
821 case kX86:
822 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700823 case kMips:
824 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000825 compiler_options_->implicit_null_checks_ = true;
826 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800827 break;
828
829 default:
830 // Defaults are correct.
831 break;
832 }
833
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000834 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800835
Jeff Haodcdc85b2015-12-04 14:06:18 -0800836 if (!IsBootImage() && multi_image) {
837 Usage("--multi-image can only be used when creating boot images");
838 }
839 if (IsBootImage() && multi_image && image_filenames_.size() > 1) {
840 Usage("--multi-image cannot be used with multiple image names");
841 }
842
843 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
844 if (!kIsTargetBuild && IsBootImage()) {
845 if (image_filenames_.size() == 1) {
846 multi_image = true;
847 }
848 }
849
850 if (IsBootImage() && multi_image) {
851 // Expand the oat and image filenames.
852 std::string base_oat = oat_filenames_[0];
853 size_t last_oat_slash = base_oat.rfind('/');
854 if (last_oat_slash == std::string::npos) {
855 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
856 }
857 base_oat = base_oat.substr(0, last_oat_slash + 1);
858
859 std::string base_img = image_filenames_[0];
860 size_t last_img_slash = base_img.rfind('/');
861 if (last_img_slash == std::string::npos) {
862 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
863 }
864 base_img = base_img.substr(0, last_img_slash + 1);
865
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000866 // Now create the other names.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800867 // Note: we have some special case here for our testing. We have to inject the differentiating
868 // parts for the different core images.
869 std::string infix; // Empty infix by default.
870 {
871 // Check the first name.
872 std::string dex_file = oat_filenames_[0];
873 size_t last_dex_slash = dex_file.rfind('/');
874 if (last_dex_slash != std::string::npos) {
875 dex_file = dex_file.substr(last_dex_slash + 1);
876 }
877 size_t last_dex_dot = dex_file.rfind('.');
878 if (last_dex_dot != std::string::npos) {
879 dex_file = dex_file.substr(0, last_dex_dot);
880 }
881 if (StartsWith(dex_file, "core-")) {
882 infix = dex_file.substr(strlen("core"));
883 }
884 }
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000885 // Use a counted loop to skip the first one.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800886 for (size_t i = 1; i < dex_locations_.size(); ++i) {
887 // TODO: Make everything properly std::string.
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000888 std::string image_name = CreateMultiImageName(dex_locations_[i], infix, ".art");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800889 char_backing_storage_.push_back(base_img + image_name);
890 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
891
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000892 std::string oat_name = CreateMultiImageName(dex_locations_[i], infix, ".oat");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800893 char_backing_storage_.push_back(base_oat + oat_name);
894 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
895 }
896 }
897
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800898 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100899 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800900 watchdog_.reset(new WatchDog(true));
901 }
902
903 // Fill some values into the key-value store for the oat header.
904 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100905 }
906
Jeff Haodcdc85b2015-12-04 14:06:18 -0800907 static std::string CreateMultiImageName(std::string in,
908 const std::string& infix,
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000909 const char* suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800910 size_t last_dex_slash = in.rfind('/');
911 if (last_dex_slash != std::string::npos) {
912 in = in.substr(last_dex_slash + 1);
913 }
914 if (!infix.empty()) {
915 // Inject infix.
916 size_t last_dot = in.rfind('.');
917 if (last_dot != std::string::npos) {
918 in.insert(last_dot, infix);
919 }
920 }
921 if (EndsWith(in, ".jar")) {
Nicolas Geoffrayde38b792015-12-30 14:50:12 +0000922 in = in.substr(0, in.length() - strlen(".jar")) + (suffix != nullptr ? suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800923 }
924 return in;
925 }
926
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000927 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100928 std::ostringstream oss;
929 for (int i = 0; i < argc; ++i) {
930 if (i > 0) {
931 oss << ' ';
932 }
933 oss << argv[i];
934 }
935 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
936 oss.str(""); // Reset.
937 oss << kRuntimeISA;
938 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
939 key_value_store_->Put(
940 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000941 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100942 key_value_store_->Put(
943 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000944 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100945 }
946
947 // Parse the arguments from the command line. In case of an unrecognized option or impossible
948 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
949 // returns, arguments have been successfully parsed.
950 void ParseArgs(int argc, char** argv) {
951 original_argc = argc;
952 original_argv = argv;
953
954 InitLogging(argv);
955
956 // Skip over argv[0].
957 argv++;
958 argc--;
959
960 if (argc == 0) {
961 Usage("No arguments specified");
962 }
963
964 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000965 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100966
Jeff Haodcdc85b2015-12-04 14:06:18 -0800967 bool multi_image = false;
968
Roland Levillain9ec5e222015-08-17 20:18:41 +0100969 for (int i = 0; i < argc; i++) {
970 const StringPiece option(argv[i]);
971 const bool log_options = false;
972 if (log_options) {
973 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
974 }
975 if (option.starts_with("--dex-file=")) {
976 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
977 } else if (option.starts_with("--dex-location=")) {
978 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
979 } else if (option.starts_with("--zip-fd=")) {
980 ParseZipFd(option);
981 } else if (option.starts_with("--zip-location=")) {
982 zip_location_ = option.substr(strlen("--zip-location=")).data();
983 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800984 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100985 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800986 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100987 } else if (option.starts_with("--oat-fd=")) {
988 ParseOatFd(option);
989 } else if (option == "--watch-dog") {
990 parser_options->watch_dog_enabled = true;
991 } else if (option == "--no-watch-dog") {
992 parser_options->watch_dog_enabled = false;
993 } else if (option.starts_with("-j")) {
994 ParseJ(option);
995 } else if (option.starts_with("--oat-location=")) {
996 oat_location_ = option.substr(strlen("--oat-location=")).data();
997 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800998 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100999 } else if (option.starts_with("--image-classes=")) {
1000 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1001 } else if (option.starts_with("--image-classes-zip=")) {
1002 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001003 } else if (option.starts_with("--image-format=")) {
1004 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001005 } else if (option.starts_with("--compiled-classes=")) {
1006 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1007 } else if (option.starts_with("--compiled-classes-zip=")) {
1008 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1009 } else if (option.starts_with("--compiled-methods=")) {
1010 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1011 } else if (option.starts_with("--compiled-methods-zip=")) {
1012 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1013 } else if (option.starts_with("--base=")) {
1014 ParseBase(option);
1015 } else if (option.starts_with("--boot-image=")) {
1016 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1017 } else if (option.starts_with("--android-root=")) {
1018 android_root_ = option.substr(strlen("--android-root=")).data();
1019 } else if (option.starts_with("--instruction-set=")) {
1020 ParseInstructionSet(option);
1021 } else if (option.starts_with("--instruction-set-variant=")) {
1022 ParseInstructionSetVariant(option, parser_options.get());
1023 } else if (option.starts_with("--instruction-set-features=")) {
1024 ParseInstructionSetFeatures(option, parser_options.get());
1025 } else if (option.starts_with("--compiler-backend=")) {
1026 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001027 } else if (option.starts_with("--profile-file=")) {
1028 profile_file_ = option.substr(strlen("--profile-file=")).data();
1029 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
1030 } else if (option == "--no-profile-file") {
1031 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001032 } else if (option == "--host") {
1033 is_host_ = true;
1034 } else if (option == "--runtime-arg") {
1035 if (++i >= argc) {
1036 Usage("Missing required argument for --runtime-arg");
1037 }
1038 if (log_options) {
1039 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1040 }
1041 runtime_args_.push_back(argv[i]);
1042 } else if (option == "--dump-timing") {
1043 dump_timing_ = true;
1044 } else if (option == "--dump-passes") {
1045 dump_passes_ = true;
1046 } else if (option.starts_with("--dump-cfg=")) {
1047 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +01001048 } else if (option.starts_with("--dump-cfg-append")) {
1049 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001050 } else if (option == "--dump-stats") {
1051 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001052 } else if (option.starts_with("--swap-file=")) {
1053 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1054 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001055 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1056 } else if (option.starts_with("--app-image-file=")) {
1057 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1058 } else if (option.starts_with("--app-image-fd=")) {
1059 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001060 } else if (option.starts_with("--verbose-methods=")) {
1061 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1062 // conditional on having verbost methods.
1063 gLogVerbosity.compiler = false;
1064 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001065 } else if (option == "--multi-image") {
1066 multi_image = true;
1067 } else if (option.starts_with("--no-inline-from=")) {
1068 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001069 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001070 Usage("Unknown argument %s", option.data());
1071 }
1072 }
1073
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 ProcessOptions(parser_options.get(), multi_image);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001075
1076 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001077 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001078 }
1079
Jeff Haodcdc85b2015-12-04 14:06:18 -08001080 // Check whether the oat output files are writable, and open them for later. Also open a swap
1081 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001082 bool OpenFile() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001083 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001084 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001085 for (const char* oat_filename : oat_filenames_) {
1086 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1087 if (oat_file.get() == nullptr) {
1088 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1089 return false;
1090 }
1091 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1092 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1093 oat_file->Erase();
1094 return false;
1095 }
1096 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001097 }
1098 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001099 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1100 oat_file->DisableAutoClose();
1101 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001102 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1103 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001104 if (oat_file.get() == nullptr) {
1105 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1106 return false;
1107 }
1108 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1109 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1110 oat_file->Erase();
1111 return false;
1112 }
1113 oat_filenames_.push_back(oat_location_.c_str());
1114 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001115 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001116
1117 // Swap file handling.
1118 //
1119 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1120 // that we can use for swap.
1121 //
1122 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1123 // will immediately unlink to satisfy the swap fd assumption.
1124 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1125 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1126 if (swap_file.get() == nullptr) {
1127 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1128 return false;
1129 }
1130 swap_fd_ = swap_file->Fd();
1131 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1132 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1133 // released immediately.
1134 unlink(swap_file_name_.c_str());
1135 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001136 return true;
1137 }
1138
Jeff Haodcdc85b2015-12-04 14:06:18 -08001139 void EraseOatFiles() {
1140 for (size_t i = 0; i < oat_files_.size(); ++i) {
1141 DCHECK(oat_files_[i].get() != nullptr);
1142 oat_files_[i]->Erase();
1143 oat_files_[i].reset();
1144 }
Andreas Gampea650e702014-12-03 14:28:02 -08001145 }
1146
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001147 void Shutdown() {
1148 ScopedObjectAccess soa(Thread::Current());
1149 for (jobject dex_cache : dex_caches_) {
1150 soa.Env()->DeleteLocalRef(dex_cache);
1151 }
1152 dex_caches_.clear();
1153 }
1154
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001155 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1156 // boot class path.
1157 bool Setup() {
1158 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001159 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001160
1161 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1162 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001164
Vladimir Marko307dac92015-10-20 11:20:09 +01001165 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001166 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001167 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001168 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001169 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001170 CompilerCallbacks::CallbackMode::kCompileBootImage :
1171 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172
Vladimir Marko49b0f452015-12-10 13:49:19 +00001173 RuntimeArgumentMap runtime_options;
1174 if (!PrepareRuntimeOptions(&runtime_options)) {
1175 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001176 }
1177
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001178 {
1179 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001180 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001181 return false;
1182 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001183 }
1184
1185 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1186 // Runtime::Start, give it away now so that we don't starve GC.
1187 Thread* self = Thread::Current();
1188 self->TransitionFromRunnableToSuspended(kNative);
1189 // If we're doing the image, override the compiler filter to force full compilation. Must be
1190 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1191 // compilation of class initializers.
1192 // Whilst we're in native take the opportunity to initialize well known classes.
1193 WellKnownClasses::Init(self->GetJniEnv());
1194
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001195 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001196 if (boot_image_filename_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001197 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001198 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001199 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001200 if (dex_filenames_.empty()) {
1201 ATRACE_BEGIN("Opening zip archive from file descriptor");
1202 std::string error_msg;
1203 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1204 zip_location_.c_str(),
1205 &error_msg));
1206 if (zip_archive.get() == nullptr) {
1207 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1208 << error_msg;
1209 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001210 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001211 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1213 << "': " << error_msg;
1214 return false;
1215 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001216 for (auto& dex_file : opened_dex_files_) {
1217 dex_files_.push_back(dex_file.get());
1218 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001219 ATRACE_END();
1220 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001221 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001222 if (failure_count > 0) {
1223 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1224 return false;
1225 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001226 for (auto& dex_file : opened_dex_files_) {
1227 dex_files_.push_back(dex_file.get());
1228 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001229 }
1230
1231 constexpr bool kSaveDexInput = false;
1232 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001233 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001234 }
1235 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001236 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1237 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001238 for (const auto& dex_file : dex_files_) {
1239 if (!dex_file->EnableWrite()) {
1240 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001241 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001242 ScopedObjectAccess soa(self);
1243 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001244 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001245 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001246 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001247
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001248 // If we use a swap file, ensure we are above the threshold to make it necessary.
1249 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001250 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001251 close(swap_fd_);
1252 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001253 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001254 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001255 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001256 }
1257 }
1258 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1259
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001260 /*
1261 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1262 * Don't bother to check if we're doing the image.
1263 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001264 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001265 compiler_options_->IsCompilationEnabled() &&
1266 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001267 size_t num_methods = 0;
1268 for (size_t i = 0; i != dex_files_.size(); ++i) {
1269 const DexFile* dex_file = dex_files_[i];
1270 CHECK(dex_file != nullptr);
1271 num_methods += dex_file->NumMethodIds();
1272 }
1273 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1274 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1275 VLOG(compiler) << "Below method threshold, compiling anyways";
1276 }
1277 }
1278
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 // Organize inputs, handling multi-dex and multiple oat file outputs.
1280 CreateDexOatMappings();
1281
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001282 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001283 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001284
Jeff Haodcdc85b2015-12-04 14:06:18 -08001285 void CreateDexOatMappings() {
1286 if (oat_files_.size() > 1) {
1287 size_t index = 0;
1288 for (size_t i = 0; i < oat_files_.size(); ++i) {
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001289 std::vector<const DexFile*> dex_files = { 1, dex_files_[index] };
1290 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
1291 index++;
1292 while (index < dex_files_.size() &&
1293 (dex_files_[index]->GetBaseLocation() == dex_files_[index - 1]->GetBaseLocation())) {
Andreas Gampe288b1e92015-12-28 10:41:49 -08001294 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001295 dex_files.push_back(dex_files_[index]);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001296 index++;
1297 }
1298 dex_files_per_oat_file_.push_back(std::move(dex_files));
1299 }
1300 } else {
1301 dex_files_per_oat_file_.push_back(dex_files_);
1302 for (const DexFile* dex_file : dex_files_) {
1303 dex_file_oat_filename_map_.emplace(dex_file, oat_filenames_[0]);
1304 }
1305 }
1306 }
1307
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001308 // Create and invoke the compiler driver. This will compile all the dex files.
1309 void Compile() {
1310 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1311 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001312
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001313 // Handle and ClassLoader creation needs to come after Runtime::Create
1314 jobject class_loader = nullptr;
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001315 jobject class_path_class_loader = nullptr;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001316 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001317
Vladimir Marko49b0f452015-12-10 13:49:19 +00001318 if (!boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001319 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001320 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001321 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001322
1323 // Classpath: first the class-path given.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001324 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
Andreas Gampe7848da42015-04-09 11:15:04 -07001325
1326 // Store the classpath we have right now.
1327 key_value_store_->Put(OatHeader::kClassPathKey,
1328 OatFile::EncodeDexFileDependencies(class_path_files));
1329
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001330 class_path_class_loader = class_linker->CreatePathClassLoader(self,
1331 class_path_files,
1332 nullptr);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001333
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001334 // Class path loader as parent so that we'll resolve there first.
1335 class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001336 }
1337
Jeff Haodcdc85b2015-12-04 14:06:18 -08001338 // Find the dex file we should not inline from.
1339
1340 // For now, on the host always have core-oj removed.
1341 if (!kIsTargetBuild && no_inline_from_string_.empty()) {
1342 no_inline_from_string_ = "core-oj";
1343 }
1344
1345 if (!no_inline_from_string_.empty()) {
1346 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1347 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1348 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1349 &class_linker->GetBootClassPath(),
1350 &class_path_files,
1351 &dex_files_
1352 };
1353 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1354 if (dex_file_vector == nullptr) {
1355 continue;
1356 }
1357
1358 bool found = false;
1359
1360 for (const DexFile* dex_file : *dex_file_vector) {
1361 // Try the complete location first.
1362 found = no_inline_from_string_ == dex_file->GetLocation();
1363 // The try just the name.
1364 if (!found) {
1365 size_t last_slash = dex_file->GetLocation().rfind('/');
1366 if (last_slash != std::string::npos) {
1367 found = StartsWith(dex_file->GetLocation().substr(last_slash + 1),
1368 no_inline_from_string_.c_str());
1369 }
1370 }
1371
1372 if (found) {
1373 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1374 compiler_options_->no_inline_from_ = dex_file;
1375 break;
1376 }
1377 }
1378
1379 if (found) {
1380 break;
1381 }
1382 }
1383 }
1384
1385 if (IsBootImage() && image_filenames_.size() > 1) {
1386 // If we're compiling the boot image, store the boot classpath into the Key-Value store. If
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001387 // the image filename was adapted (e.g., for our tests), we need to change this here, too. We
1388 // need this for the multi-image case.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001389 std::ostringstream bootcp_oss;
1390 bool first_bootcp = true;
1391 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1392 if (!first_bootcp) {
1393 bootcp_oss << ":";
1394 }
1395
1396 std::string dex_loc = dex_locations_[i];
1397 std::string image_filename = image_filenames_[i];
1398
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001399 // Use the dex_loc path, but the image_filename name.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 size_t dex_last_slash = dex_loc.rfind('/');
1401 size_t image_last_slash = image_filename.rfind('/');
1402 if (dex_last_slash == std::string::npos) {
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001403 dex_loc = image_filename.substr(image_last_slash + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001404 } else {
1405 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001406 image_filename.substr(image_last_slash + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001407 }
1408
1409 // Image filenames already end with .art, no need to replace.
1410
1411 bootcp_oss << dex_loc;
1412 first_bootcp = false;
1413 }
1414 key_value_store_->Put(OatHeader::kBootClassPath, bootcp_oss.str());
1415 }
1416
Vladimir Marko307dac92015-10-20 11:20:09 +01001417 driver_.reset(new CompilerDriver(compiler_options_.get(),
1418 verification_results_.get(),
1419 &method_inliner_map_,
1420 compiler_kind_,
1421 instruction_set_,
1422 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001423 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001424 image_classes_.release(),
1425 compiled_classes_.release(),
1426 nullptr,
1427 thread_count_,
1428 dump_stats_,
1429 dump_passes_,
1430 dump_cfg_file_name_,
1431 dump_cfg_append_,
1432 compiler_phases_timings_.get(),
1433 swap_fd_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001434 profile_file_,
1435 &dex_file_oat_filename_map_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001436
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001437 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001438 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001439 }
1440
Jeff Haodcdc85b2015-12-04 14:06:18 -08001441 // TODO: Update comments about how this works for multi image. b/26317072
Brian Carlstrom7940e442013-07-12 13:46:57 -07001442 // Notes on the interleaving of creating the image and oat file to
1443 // ensure the references between the two are correct.
1444 //
1445 // Currently we have a memory layout that looks something like this:
1446 //
1447 // +--------------+
1448 // | image |
1449 // +--------------+
1450 // | boot oat |
1451 // +--------------+
1452 // | alloc spaces |
1453 // +--------------+
1454 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001455 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001456 //
1457 // 1. The image is expected to be loaded at an absolute address and
1458 // contains Objects with absolute pointers within the image.
1459 //
1460 // 2. There are absolute pointers from Methods in the image to their
1461 // code in the oat.
1462 //
1463 // 3. There are absolute pointers from the code in the oat to Methods
1464 // in the image.
1465 //
1466 // 4. There are absolute pointers from code in the oat to other code
1467 // in the oat.
1468 //
1469 // To get this all correct, we go through several steps.
1470 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001471 // 1. We prepare offsets for all data in the oat file and calculate
1472 // the oat data size and code size. During this stage, we also set
1473 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001474 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001475 // 2. We prepare offsets for the objects in the image and calculate
1476 // the image size.
1477 //
1478 // 3. We create the oat file. Originally this was just our own proprietary
1479 // file but now it is contained within an ELF dynamic object (aka an .so
1480 // file). Since we know the image size and oat data size and code size we
1481 // can prepare the ELF headers and we then know the ELF memory segment
1482 // layout and we can now resolve all references. The compiler provides
1483 // LinkerPatch information in each CompiledMethod and we resolve these,
1484 // using the layout information and image object locations provided by
1485 // image writer, as we're writing the method code.
1486 //
1487 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001488 // will be loaded after itself. Originally when oat file was simply
1489 // memory mapped so we could predict where its contents were based
1490 // on the file size. Now that it is an ELF file, we need to inspect
1491 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001492 // where the oat header is located within.
1493 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001494 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001495 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001496 // load the .so at the desired location at runtime by offsetting the
1497 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001498 // TODO: Do this in step 3. We already know the layout there.
1499 //
1500 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1501 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001502
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001503 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1504 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001505 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1506 // case (when the file will be explicitly erased).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001507 bool CreateOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001508 CHECK(key_value_store_.get() != nullptr);
1509
1510 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1511
Jeff Haodcdc85b2015-12-04 14:06:18 -08001512 std::vector<std::unique_ptr<OatWriter>> oat_writers;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001513 {
1514 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1515 std::string image_file_location;
1516 uint32_t image_file_location_oat_checksum = 0;
1517 uintptr_t image_file_location_oat_data_begin = 0;
1518 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001519
1520 if (app_image_ && image_base_ == 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 std::vector<gc::space::ImageSpace*> image_spaces =
1522 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1523 for (gc::space::ImageSpace* image_space : image_spaces) {
1524 // TODO: IS THIS IN ORDER? JUST TAKE THE LAST ONE?
1525 image_base_ = std::max(image_base_, RoundUp(
1526 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1527 kPageSize));
1528 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001529 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1530 }
1531
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001532 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001533 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001534 }
1535
1536 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001537 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001538 std::vector<gc::space::ImageSpace*> image_spaces =
1539 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1540 image_file_location_oat_checksum = image_spaces[0]->GetImageHeader().GetOatChecksum();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001541 image_file_location_oat_data_begin =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001542 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1543 image_patch_delta = image_spaces[0]->GetImageHeader().GetPatchDelta();
1544 std::vector<std::string> image_filenames;
1545 for (const gc::space::ImageSpace* image_space : image_spaces) {
1546 image_filenames.push_back(image_space->GetImageFilename());
1547 }
1548 image_file_location = Join(image_filenames, ':');
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001549 }
1550
1551 if (!image_file_location.empty()) {
1552 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1553 }
1554
Jeff Haodcdc85b2015-12-04 14:06:18 -08001555 for (size_t i = 0; i < oat_files_.size(); ++i) {
1556 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1557 std::unique_ptr<OatWriter> oat_writer(new OatWriter(dex_files,
1558 image_file_location_oat_checksum,
1559 image_file_location_oat_data_begin,
1560 image_patch_delta,
1561 driver_.get(),
1562 image_writer_.get(),
1563 IsBootImage(),
1564 timings_,
1565 key_value_store_.get()));
1566 oat_writers.push_back(std::move(oat_writer));
1567 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001569
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001570 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001571 // The OatWriter constructor has already updated offsets in methods and we need to
1572 // prepare method offsets in the image address space for direct method patching.
1573 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1574 if (!image_writer_->PrepareImageAddressSpace()) {
1575 LOG(ERROR) << "Failed to prepare image address space.";
1576 return false;
1577 }
1578 }
1579
1580 {
1581 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001582 for (size_t i = 0; i < oat_files_.size(); ++i) {
1583 std::unique_ptr<File>& oat_file = oat_files_[i];
1584 std::unique_ptr<OatWriter>& oat_writer = oat_writers[i];
1585 std::unique_ptr<ElfWriter> elf_writer =
1586 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get());
Vladimir Marko10c13562015-11-25 14:33:36 +00001587
Jeff Haodcdc85b2015-12-04 14:06:18 -08001588 elf_writer->Start();
Vladimir Marko10c13562015-11-25 14:33:36 +00001589
Jeff Haodcdc85b2015-12-04 14:06:18 -08001590 OutputStream* rodata = elf_writer->StartRoData();
1591 if (!oat_writer->WriteRodata(rodata)) {
1592 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1593 return false;
1594 }
1595 elf_writer->EndRoData(rodata);
Vladimir Marko10c13562015-11-25 14:33:36 +00001596
Jeff Haodcdc85b2015-12-04 14:06:18 -08001597 OutputStream* text = elf_writer->StartText();
1598 if (!oat_writer->WriteCode(text)) {
1599 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1600 return false;
1601 }
1602 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001603
Jeff Haodcdc85b2015-12-04 14:06:18 -08001604 elf_writer->SetBssSize(oat_writer->GetBssSize());
1605 elf_writer->WriteDynamicSection();
1606 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1607 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001608
Jeff Haodcdc85b2015-12-04 14:06:18 -08001609 if (!elf_writer->End()) {
1610 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1611 return false;
1612 }
1613
1614 // Flush the oat file.
1615 if (oat_files_[i] != nullptr) {
1616 if (oat_files_[i]->Flush() != 0) {
1617 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1618 oat_files_[i]->Erase();
1619 return false;
1620 }
1621 }
1622
1623 if (IsImage()) {
1624 // Update oat estimates.
1625 UpdateImageWriter(i);
1626 }
1627
1628 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001629 }
1630 }
1631
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633 }
1634
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001635 // If we are compiling an image, invoke the image creation routine. Else just skip.
1636 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001637 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001638 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1639 if (!CreateImageFile()) {
1640 return false;
1641 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001642 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001643 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001644 return true;
1645 }
1646
Jeff Haodcdc85b2015-12-04 14:06:18 -08001647 // Create a copy from stripped to unstripped.
1648 bool CopyStrippedToUnstripped() {
1649 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1650 // If we don't want to strip in place, copy from stripped location to unstripped location.
1651 // We need to strip after image creation because FixupElf needs to use .strtab.
1652 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1653 // If the oat file is still open, flush it.
1654 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1655 if (!FlushCloseOatFile(i)) {
1656 return false;
1657 }
1658 }
1659
1660 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1661 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1662 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1663 size_t buffer_size = 8192;
1664 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1665 while (true) {
1666 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1667 if (bytes_read <= 0) {
1668 break;
1669 }
1670 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1671 CHECK(write_ok);
1672 }
1673 if (out->FlushCloseOrErase() != 0) {
1674 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1675 return false;
1676 }
1677 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1678 }
1679 }
1680 return true;
1681 }
1682
1683 bool FlushOatFiles() {
1684 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1685 for (size_t i = 0; i < oat_files_.size(); ++i) {
1686 if (oat_files_[i].get() != nullptr) {
1687 if (oat_files_[i]->Flush() != 0) {
1688 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1689 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001690 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001691 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001692 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001693 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001694 return true;
1695 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001696
Jeff Haodcdc85b2015-12-04 14:06:18 -08001697 bool FlushCloseOatFile(size_t i) {
1698 if (oat_files_[i].get() != nullptr) {
1699 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001700 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001701 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001702 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001703 }
1704 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001705 return true;
1706 }
1707
Jeff Haodcdc85b2015-12-04 14:06:18 -08001708 bool FlushCloseOatFiles() {
1709 bool result = true;
1710 for (size_t i = 0; i < oat_files_.size(); ++i) {
1711 result &= FlushCloseOatFile(i);
1712 }
1713 return result;
1714 }
1715
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001716 void DumpTiming() {
1717 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1718 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1719 }
1720 if (dump_passes_) {
1721 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1722 }
1723 }
1724
1725 CompilerOptions* GetCompilerOptions() const {
1726 return compiler_options_.get();
1727 }
1728
Andreas Gampe10e477d2014-11-19 12:57:42 -08001729 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001730 return IsAppImage() || IsBootImage();
1731 }
1732
1733 bool IsAppImage() const {
1734 return app_image_;
1735 }
1736
1737 bool IsBootImage() const {
1738 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001739 }
1740
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001741 bool IsHost() const {
1742 return is_host_;
1743 }
1744
1745 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001746 template <typename T>
1747 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1748 std::vector<T*> result;
1749 result.reserve(src.size());
1750 for (const std::unique_ptr<T>& t : src) {
1751 result.push_back(t.get());
1752 }
1753 return result;
1754 }
1755
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001756 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1757 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001758 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001759 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001760 size_t failure_count = 0;
1761 for (size_t i = 0; i < dex_filenames.size(); i++) {
1762 const char* dex_filename = dex_filenames[i];
1763 const char* dex_location = dex_locations[i];
1764 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1765 std::string error_msg;
1766 if (!OS::FileExists(dex_filename)) {
1767 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1768 continue;
1769 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001770 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001771 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1772 ++failure_count;
1773 }
1774 ATRACE_END();
1775 }
1776 return failure_count;
1777 }
1778
Andreas Gampee3712d02015-04-09 14:46:31 -07001779 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1780 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1781 // efficient, but under normal circumstances the list is neither large nor is this part too
1782 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001783 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1784 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001785 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001786 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001787 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1788 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001789 return true;
1790 }
1791 }
1792 return false;
1793 }
1794
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001795 // Appends to opened_dex_files any elements of class_path that dex_files
1796 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001797 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001798 std::vector<const DexFile*> dex_files,
1799 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001800 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001801 std::vector<std::string> parsed;
1802 Split(class_path, ':', &parsed);
1803 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1804 ScopedObjectAccess soa(Thread::Current());
1805 for (size_t i = 0; i < parsed.size(); ++i) {
1806 if (DexFilesContains(dex_files, parsed[i])) {
1807 continue;
1808 }
1809 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001810 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001811 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1812 }
1813 }
1814 }
1815
Vladimir Marko49b0f452015-12-10 13:49:19 +00001816 bool PrepareImageClasses() {
1817 // If --image-classes was specified, calculate the full list of classes to include in the image.
1818 if (image_classes_filename_ != nullptr) {
1819 image_classes_ =
1820 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1821 if (image_classes_ == nullptr) {
1822 return false;
1823 }
1824 } else if (IsBootImage()) {
1825 image_classes_.reset(new std::unordered_set<std::string>);
1826 }
1827 return true;
1828 }
1829
1830 bool PrepareCompiledClasses() {
1831 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1832 // image.
1833 if (compiled_classes_filename_ != nullptr) {
1834 compiled_classes_ =
1835 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1836 if (compiled_classes_ == nullptr) {
1837 return false;
1838 }
1839 } else {
1840 compiled_classes_.reset(nullptr); // By default compile everything.
1841 }
1842 return true;
1843 }
1844
1845 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1846 const char* classes_filename,
1847 const char* tag) {
1848 std::unique_ptr<std::unordered_set<std::string>> classes;
1849 std::string error_msg;
1850 if (zip_filename != nullptr) {
1851 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1852 } else {
1853 classes.reset(ReadImageClassesFromFile(classes_filename));
1854 }
1855 if (classes == nullptr) {
1856 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1857 << classes_filename << "': " << error_msg;
1858 }
1859 return classes;
1860 }
1861
1862 bool PrepareCompiledMethods() {
1863 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1864 if (compiled_methods_filename_ != nullptr) {
1865 std::string error_msg;
1866 if (compiled_methods_zip_filename_ != nullptr) {
1867 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1868 compiled_methods_filename_,
1869 nullptr, // No post-processing.
1870 &error_msg));
1871 } else {
1872 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1873 nullptr)); // No post-processing.
1874 }
1875 if (compiled_methods_.get() == nullptr) {
1876 LOG(ERROR) << "Failed to create list of compiled methods from '"
1877 << compiled_methods_filename_ << "': " << error_msg;
1878 return false;
1879 }
1880 } else {
1881 compiled_methods_.reset(nullptr); // By default compile everything.
1882 }
1883 return true;
1884 }
1885
1886 void SaveDexInput() {
1887 for (size_t i = 0; i < dex_files_.size(); ++i) {
1888 const DexFile* dex_file = dex_files_[i];
1889 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1890 getpid(), i));
1891 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1892 if (tmp_file.get() == nullptr) {
1893 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1894 << ". Try: adb shell chmod 777 /data/local/tmp";
1895 continue;
1896 }
1897 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1898 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1899 UNUSED(tmp_file->Flush());
1900 UNUSED(tmp_file->Close());
1901 LOG(INFO) << "Wrote input to " << tmp_file_name;
1902 }
1903 }
1904
1905 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
1906 RuntimeOptions raw_options;
1907 if (boot_image_filename_.empty()) {
1908 std::string boot_class_path = "-Xbootclasspath:";
1909 boot_class_path += Join(dex_filenames_, ':');
1910 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
1911 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1912 boot_class_path_locations += Join(dex_locations_, ':');
1913 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
1914 } else {
1915 std::string boot_image_option = "-Ximage:";
1916 boot_image_option += boot_image_filename_;
1917 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
1918 }
1919 for (size_t i = 0; i < runtime_args_.size(); i++) {
1920 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
1921 }
1922
1923 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1924 raw_options.push_back(
1925 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1926
1927 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1928 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1929 // have been stripped in preopting, anyways).
1930 if (!IsBootImage()) {
1931 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1932 }
1933 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1934 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1935 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
1936
1937 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
1938 LOG(ERROR) << "Failed to parse runtime options";
1939 return false;
1940 }
1941 return true;
1942 }
1943
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001944 // Create a runtime necessary for compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001945 bool CreateRuntime(RuntimeArgumentMap&& runtime_options)
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001946 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001947 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001948 LOG(ERROR) << "Failed to create runtime";
1949 return false;
1950 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001951 runtime_.reset(Runtime::Current());
1952 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001953 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1954 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001955 if (!runtime_->HasCalleeSaveMethod(type)) {
1956 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001957 }
1958 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001959 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001960
1961 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1962 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001963 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001964
Vladimir Marko307dac92015-10-20 11:20:09 +01001965 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001966
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001967 return true;
1968 }
1969
1970 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001971 DCHECK(IsImage());
1972 image_writer_.reset(new ImageWriter(*driver_,
1973 image_base,
1974 compiler_options_->GetCompilePic(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001975 IsAppImage(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001976 image_storage_mode_,
1977 oat_filenames_,
1978 dex_file_oat_filename_map_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001979 }
1980
Jeff Haodcdc85b2015-12-04 14:06:18 -08001981 // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001982 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001983 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001984 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001985 if (!IsBootImage()) {
1986 image_filenames_.push_back(app_image_file_name_.c_str());
1987 }
1988 if (!image_writer_->Write(app_image_fd_, image_filenames_, oat_filenames_)) {
1989 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001990 return false;
1991 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001992
Jeff Haodcdc85b2015-12-04 14:06:18 -08001993 // We need the OatDataBegin entries.
1994 std::map<const char*, uintptr_t> oat_data_begins;
1995 for (const char* oat_filename : oat_filenames_) {
1996 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
1997 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001998 // Destroy ImageWriter before doing FixupElf.
1999 image_writer_.reset();
2000
Jeff Haodcdc85b2015-12-04 14:06:18 -08002001 for (const char* oat_filename : oat_filenames_) {
2002 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2003 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2004 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2005 if (oat_file.get() == nullptr) {
2006 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2007 return false;
2008 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002009
Jeff Haodcdc85b2015-12-04 14:06:18 -08002010 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002011
Jeff Haodcdc85b2015-12-04 14:06:18 -08002012 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2013 oat_file->Erase();
2014 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2015 return false;
2016 }
2017
2018 if (oat_file->FlushCloseOrErase()) {
2019 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2020 return false;
2021 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002022 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002023 }
2024
2025 return true;
2026 }
2027
2028 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002029 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2030 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002031 std::function<std::string(const char*)> process = DotToDescriptor;
2032 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002033 }
2034
2035 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002036 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002037 const char* zip_filename,
2038 const char* image_classes_filename,
2039 std::string* error_msg) {
2040 std::function<std::string(const char*)> process = DotToDescriptor;
2041 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2042 }
2043
2044 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2045 // the given function.
2046 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2047 const char* input_filename, std::function<std::string(const char*)>* process) {
2048 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2049 if (input_file.get() == nullptr) {
2050 LOG(ERROR) << "Failed to open input file " << input_filename;
2051 return nullptr;
2052 }
2053 std::unique_ptr<std::unordered_set<std::string>> result(
2054 ReadCommentedInputStream(*input_file, process));
2055 input_file->close();
2056 return result.release();
2057 }
2058
2059 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2060 // Post-process each line with the given function.
2061 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002062 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002063 const char* input_filename,
2064 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002065 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002066 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2067 if (zip_archive.get() == nullptr) {
2068 return nullptr;
2069 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002070 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002071 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002072 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002073 zip_filename, error_msg->c_str());
2074 return nullptr;
2075 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002076 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2077 input_filename,
2078 error_msg));
2079 if (input_file.get() == nullptr) {
2080 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002081 zip_filename, error_msg->c_str());
2082 return nullptr;
2083 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002084 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2085 input_file->Size());
2086 std::istringstream input_stream(input_string);
2087 return ReadCommentedInputStream(input_stream, process);
2088 }
2089
2090 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2091 // with the given function.
2092 static std::unordered_set<std::string>* ReadCommentedInputStream(
2093 std::istream& in_stream,
2094 std::function<std::string(const char*)>* process) {
2095 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2096 new std::unordered_set<std::string>);
2097 while (in_stream.good()) {
2098 std::string dot;
2099 std::getline(in_stream, dot);
2100 if (StartsWith(dot, "#") || dot.empty()) {
2101 continue;
2102 }
2103 if (process != nullptr) {
2104 std::string descriptor((*process)(dot.c_str()));
2105 image_classes->insert(descriptor);
2106 } else {
2107 image_classes->insert(dot);
2108 }
2109 }
2110 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002111 }
2112
Mathieu Chartier49285c52014-12-02 15:43:48 -08002113 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002114 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2115 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002116 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002117 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002118 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002119 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002120 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2121 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002122 }
2123
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2125 std::string res(image_filename);
2126 size_t last_slash = res.rfind('/');
2127 if (last_slash == std::string::npos || last_slash == 0) {
2128 return res;
2129 }
2130 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2131 if (penultimate_slash == std::string::npos) {
2132 return res;
2133 }
2134 // Check that the string in-between is the expected one.
2135 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2136 GetInstructionSetString(isa)) {
2137 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2138 return res;
2139 }
2140 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2141 }
2142
2143 // Update the estimate for the oat file with the given index.
2144 void UpdateImageWriter(size_t index) {
2145 DCHECK(image_writer_ != nullptr);
2146 DCHECK_LT(index, oat_filenames_.size());
2147
2148 image_writer_->UpdateOatFile(oat_filenames_[index]);
2149 }
2150
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002151 std::unique_ptr<CompilerOptions> compiler_options_;
2152 Compiler::Kind compiler_kind_;
2153
2154 InstructionSet instruction_set_;
2155 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2156
2157 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2158
Vladimir Marko307dac92015-10-20 11:20:09 +01002159 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002160
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002161 DexFileToMethodInlinerMap method_inliner_map_;
2162 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2163
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002164 // Ownership for the class path files.
2165 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2166
Vladimir Marko307dac92015-10-20 11:20:09 +01002167 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002168
2169 size_t thread_count_;
2170 uint64_t start_ns_;
2171 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002172 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002173 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002174 std::vector<const char*> oat_filenames_;
2175 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002176 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002177 std::vector<const char*> dex_filenames_;
2178 std::vector<const char*> dex_locations_;
2179 int zip_fd_;
2180 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002181 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002182 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002183 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002184 uintptr_t image_base_;
2185 const char* image_classes_zip_filename_;
2186 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002187 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002188 const char* compiled_classes_zip_filename_;
2189 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002190 const char* compiled_methods_zip_filename_;
2191 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002192 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2193 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002194 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002195 bool app_image_;
2196 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002197 bool is_host_;
2198 std::string android_root_;
2199 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002200 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002201 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002202 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002203
Vladimir Marko307dac92015-10-20 11:20:09 +01002204 std::unique_ptr<ImageWriter> image_writer_;
2205 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002206
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002207 std::vector<std::string> verbose_methods_;
2208 bool dump_stats_;
2209 bool dump_passes_;
2210 bool dump_timing_;
2211 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00002212 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01002213 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002214 std::string swap_file_name_;
2215 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002216 std::string app_image_file_name_;
2217 int app_image_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002218 std::string profile_file_; // Profile file to use
2219 TimingLogger* timings_;
2220 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002221 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2222 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2223
2224 // Backing storage.
2225 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002226
2227 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2228};
2229
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002230static void b13564922() {
2231#if defined(__linux__) && defined(__arm__)
2232 int major, minor;
2233 struct utsname uts;
2234 if (uname(&uts) != -1 &&
2235 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2236 ((major < 3) || ((major == 3) && (minor < 4)))) {
2237 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2238 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2239 int old_personality = personality(0xffffffff);
2240 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2241 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2242 if (new_personality == -1) {
2243 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2244 }
2245 }
2246 }
2247#endif
2248}
2249
Andreas Gampe10e477d2014-11-19 12:57:42 -08002250static int CompileImage(Dex2Oat& dex2oat) {
2251 dex2oat.Compile();
2252
Jeff Haodcdc85b2015-12-04 14:06:18 -08002253 if (!dex2oat.CreateOatFiles()) {
2254 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002255 return EXIT_FAILURE;
2256 }
2257
Jeff Haodcdc85b2015-12-04 14:06:18 -08002258 // Close the image oat files. We always expect the output file by name, and it will be
2259 // re-opened from the unstripped name. Note: it's easier to *flush* and close...
2260 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002261 return EXIT_FAILURE;
2262 }
2263
Jeff Haodcdc85b2015-12-04 14:06:18 -08002264 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002265 if (!dex2oat.HandleImage()) {
2266 return EXIT_FAILURE;
2267 }
2268
2269 // When given --host, finish early without stripping.
2270 if (dex2oat.IsHost()) {
2271 dex2oat.DumpTiming();
2272 return EXIT_SUCCESS;
2273 }
2274
Jeff Haodcdc85b2015-12-04 14:06:18 -08002275 // Copy stripped to unstripped location, if necessary.
2276 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002277 return EXIT_FAILURE;
2278 }
2279
Jeff Haodcdc85b2015-12-04 14:06:18 -08002280 // FlushClose again, as stripping might have re-opened the oat files.
2281 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002282 return EXIT_FAILURE;
2283 }
2284
2285 dex2oat.DumpTiming();
2286 return EXIT_SUCCESS;
2287}
2288
2289static int CompileApp(Dex2Oat& dex2oat) {
2290 dex2oat.Compile();
2291
Jeff Haodcdc85b2015-12-04 14:06:18 -08002292 if (!dex2oat.CreateOatFiles()) {
2293 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002294 return EXIT_FAILURE;
2295 }
2296
Jeff Haodcdc85b2015-12-04 14:06:18 -08002297 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002298 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002299
2300 // When given --host, finish early without stripping.
2301 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002302 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002303 return EXIT_FAILURE;
2304 }
2305
2306 dex2oat.DumpTiming();
2307 return EXIT_SUCCESS;
2308 }
2309
Jeff Haodcdc85b2015-12-04 14:06:18 -08002310 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2311 // stripped versions. If this is given, we expect to be able to open writable files by name.
2312 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002313 return EXIT_FAILURE;
2314 }
2315
Jeff Haodcdc85b2015-12-04 14:06:18 -08002316 // Flush and close the files.
2317 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002318 return EXIT_FAILURE;
2319 }
2320
2321 dex2oat.DumpTiming();
2322 return EXIT_SUCCESS;
2323}
2324
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002325static int dex2oat(int argc, char** argv) {
2326 b13564922();
2327
2328 TimingLogger timings("compiler", false, false);
2329
2330 Dex2Oat dex2oat(&timings);
2331
2332 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2333 dex2oat.ParseArgs(argc, argv);
2334
2335 // Check early that the result of compilation can be written
2336 if (!dex2oat.OpenFile()) {
2337 return EXIT_FAILURE;
2338 }
2339
Andreas Gampe046c7062015-05-18 23:22:54 -07002340 // Print the complete line when any of the following is true:
2341 // 1) Debug build
2342 // 2) Compiling an image
2343 // 3) Compiling with --host
2344 // 4) Compiling on the host (not a target build)
2345 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002346 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002347 LOG(INFO) << CommandLine();
2348 } else {
2349 LOG(INFO) << StrippedCommandLine();
2350 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002351
2352 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002353 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002354 return EXIT_FAILURE;
2355 }
2356
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002357 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002358 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002359 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002360 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002361 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002362 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002363
2364 dex2oat.Shutdown();
2365 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002366}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002367} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002368
2369int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002370 int result = art::dex2oat(argc, argv);
2371 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2372 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2373 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002374 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002375 exit(result);
2376 }
2377 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002378}