blob: 437aba7ad14e5166279b4f91a3d7b972986a29a9 [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 Rogersd582fa42014-11-05 23:46:43 -080035#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080036#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000037#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080039#include "base/macros.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000040#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "base/stl_util.h"
42#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "base/timing_logger.h"
45#include "base/unix_file/fd_file.h"
46#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000047#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000048#include "compiler_callbacks.h"
David Srbecky09c2a6b2016-03-11 17:11:44 +000049#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000050#include "debug/method_debug_info.h"
Ian Rogerse63db272014-07-15 15:36:11 -070051#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000052#include "dex/quick_compiler_callbacks.h"
53#include "dex/verification_results.h"
54#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080056#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080057#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070058#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000059#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "gc/space/image_space.h"
61#include "gc/space/space-inl.h"
62#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070063#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020064#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "leb128.h"
Vladimir Marko944da602016-02-19 12:27:55 +000066#include "linker/multi_oat_relative_patcher.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"
Jeff Haob11ffb72016-04-07 15:40:54 -070071#include "oat_file_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "os.h"
74#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000075#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076#include "ScopedLocalRef.h"
77#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070078#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070079#include "well_known_classes.h"
80#include "zip_archive.h"
81
82namespace art {
83
Andreas Gampee1459ae2016-06-29 09:36:30 -070084static constexpr size_t kDefaultMinDexFilesForSwap = 2;
85static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB;
86
Brian Carlstrom6449c622014-02-10 23:48:36 -080087static int original_argc;
88static char** original_argv;
89
90static std::string CommandLine() {
91 std::vector<std::string> command;
92 for (int i = 0; i < original_argc; ++i) {
93 command.push_back(original_argv[i]);
94 }
95 return Join(command, ' ');
96}
97
Andreas Gampe046c7062015-05-18 23:22:54 -070098// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
99// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
100// locations are all staged).
101static std::string StrippedCommandLine() {
102 std::vector<std::string> command;
103
104 // Do a pre-pass to look for zip-fd.
105 bool saw_zip_fd = false;
106 for (int i = 0; i < original_argc; ++i) {
107 if (StartsWith(original_argv[i], "--zip-fd=")) {
108 saw_zip_fd = true;
109 break;
110 }
111 }
112
113 // Now filter out things.
114 for (int i = 0; i < original_argc; ++i) {
115 // All runtime-arg parameters are dropped.
116 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
117 i++; // Drop the next part, too.
118 continue;
119 }
120
121 // Any instruction-setXXX is dropped.
122 if (StartsWith(original_argv[i], "--instruction-set")) {
123 continue;
124 }
125
126 // The boot image is dropped.
127 if (StartsWith(original_argv[i], "--boot-image=")) {
128 continue;
129 }
130
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800131 // The image format is dropped.
132 if (StartsWith(original_argv[i], "--image-format=")) {
133 continue;
134 }
135
Andreas Gampe046c7062015-05-18 23:22:54 -0700136 // This should leave any dex-file and oat-file options, describing what we compiled.
137
138 // However, we prefer to drop this when we saw --zip-fd.
139 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700140 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700141 if (StartsWith(original_argv[i], "--zip-") ||
142 StartsWith(original_argv[i], "--dex-") ||
143 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700144 StartsWith(original_argv[i], "--swap-") ||
145 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700146 continue;
147 }
148 }
149
150 command.push_back(original_argv[i]);
151 }
152
153 // Construct the final output.
154 if (command.size() <= 1U) {
155 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
156 return "Starting dex2oat.";
157 }
158 return Join(command, ' ');
159}
160
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161static void UsageErrorV(const char* fmt, va_list ap) {
162 std::string error;
163 StringAppendV(&error, fmt, ap);
164 LOG(ERROR) << error;
165}
166
167static void UsageError(const char* fmt, ...) {
168 va_list ap;
169 va_start(ap, fmt);
170 UsageErrorV(fmt, ap);
171 va_end(ap);
172}
173
Andreas Gampe794ad762015-02-23 08:12:24 -0800174NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 va_list ap;
176 va_start(ap, fmt);
177 UsageErrorV(fmt, ap);
178 va_end(ap);
179
Brian Carlstrom6449c622014-02-10 23:48:36 -0800180 UsageError("Command: %s", CommandLine().c_str());
181
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182 UsageError("Usage: dex2oat [options]...");
183 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100184 UsageError(" -j<number>: specifies the number of threads used for compilation.");
185 UsageError(" Default is the number of detected hardware threads available on the");
186 UsageError(" host system.");
187 UsageError(" Example: -j12");
188 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700189 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 UsageError(" Example: --dex-file=/system/framework/core.jar");
191 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700192 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
193 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
194 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
195 UsageError(" --dex-location=/system/framework/core.jar");
196 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
198 UsageError(" containing a classes.dex file to compile.");
199 UsageError(" Example: --zip-fd=5");
200 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700201 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
202 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
204 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800205 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 UsageError(" Example: --oat-file=/system/framework/boot.oat");
207 UsageError("");
208 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900209 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 UsageError("");
211 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
212 UsageError(" to the file descriptor specified by --oat-fd.");
213 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
214 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
217 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800218 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 UsageError(" Example: --image=/system/framework/boot.art");
220 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800221 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800222 UsageError(" Which format to store the image.");
223 UsageError(" Example: --image-format=lz4");
224 UsageError(" Default: uncompressed");
225 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
227 UsageError(" Example: --image=frameworks/base/preloaded-classes");
228 UsageError("");
229 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
230 UsageError(" Example: --base=0x50000000");
231 UsageError("");
232 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000233 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000235 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000236 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError("");
238 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
239 UsageError(" Example: --android-root=out/host/linux-x86");
240 UsageError(" Default: $ANDROID_ROOT");
241 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800242 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700243 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700244 UsageError(" Example: --instruction-set=x86");
245 UsageError(" Default: arm");
246 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700247 UsageError(" --instruction-set-features=...,: Specify instruction set features");
248 UsageError(" Example: --instruction-set-features=div");
249 UsageError(" Default: default");
250 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700251 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
252 UsageError(" Default: disabled");
253 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800254 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800256 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100257 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700258 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100259 UsageError(" --compiler-filter="
260 "(verify-none"
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700261 "|verify-at-runtime"
Mathieu Chartiera8077802016-03-16 19:08:31 -0700262 "|verify-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100263 "|interpret-only"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000264 "|time"
265 "|space-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100266 "|space"
267 "|balanced"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000268 "|speed-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100269 "|speed"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000270 "|everything-profile"
271 "|everything):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700272 UsageError(" select compiler filter.");
Mathieu Chartiera8077802016-03-16 19:08:31 -0700273 UsageError(" verify-profile requires a --profile(-fd) to also be passed in.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800274 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800275 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800276 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800277 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
278 UsageError(" method for compiler filter tuning.");
279 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
280 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
281 UsageError("");
282 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
283 UsageError(" method for compiler filter tuning.");
284 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
285 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
286 UsageError("");
287 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
288 UsageError(" method for compiler filter tuning.");
289 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
290 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
291 UsageError("");
292 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
293 UsageError(" method for compiler filter tuning.");
294 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
295 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
296 UsageError("");
297 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
298 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700299 UsageError(" and the filter is not interpret-only or verify-none or verify-at-runtime, ");
300 UsageError(" overrides the filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800301 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
302 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
303 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100304 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
305 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100306 UsageError(" Has priority over the --compiler-filter option. Intended for ");
307 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100308 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
309 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
310 UsageError("");
311 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
312 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100313 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
314 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100315 UsageError(" Example: --inline-max-code-units=%d",
316 CompilerOptions::kDefaultInlineMaxCodeUnits);
317 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
318 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700319 UsageError(" --dump-timing: display a breakdown of where time was spent");
320 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700321 UsageError(" --include-patch-information: Include patching information so the generated code");
322 UsageError(" can have its base address moved without full recompilation.");
323 UsageError("");
324 UsageError(" --no-include-patch-information: Do not include patching information.");
325 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100326 UsageError(" -g");
327 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
328 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky346dc992016-03-13 22:00:07 +0000329 UsageError(" If used without --debuggable, it will be best-effort only.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000330 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700331 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100332 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100333 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000334 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
335 UsageError(" debug information necessary to print backtraces. (disabled by default)");
336 UsageError("");
David Srbecky346dc992016-03-13 22:00:07 +0000337 UsageError(" --no-generate-mini-debug-info: Do not generate backtrace info.");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000338 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000339 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000340 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
342 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
343 UsageError(" Use a separate --runtime-arg switch for each argument.");
344 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700345 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000346 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000348 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
349 UsageError(" Cannot be used together with --profile-file.");
350 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800351 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
352 UsageError(" Example: --swap-file=/data/tmp/swap.001");
353 UsageError("");
354 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
355 UsageError(" Example: --swap-fd=10");
356 UsageError("");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700357 UsageError(" --swap-dex-size-threshold=<size>: specifies the minimum total dex file size in");
358 UsageError(" bytes to allow the use of swap.");
359 UsageError(" Example: --swap-dex-size-threshold=1000000");
360 UsageError(" Default: %zu", kDefaultMinDexFileCumulativeSizeForSwap);
361 UsageError("");
362 UsageError(" --swap-dex-count-threshold=<count>: specifies the minimum number of dex files to");
363 UsageError(" allow the use of swap.");
364 UsageError(" Example: --swap-dex-count-threshold=10");
365 UsageError(" Default: %zu", kDefaultMinDexFilesForSwap);
366 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700367 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
368 UsageError(" Example: --app-image-fd=10");
369 UsageError("");
370 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
371 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
372 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800373 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
374 "input dex file.");
375 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000376 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
377 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
378 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
379 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 std::cerr << "See log for usage error information\n";
381 exit(EXIT_FAILURE);
382}
383
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384// The primary goal of the watchdog is to prevent stuck build servers
385// during development when fatal aborts lead to a cascade of failures
386// that result in a deadlock.
387class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800388// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389#undef CHECK_PTHREAD_CALL
390#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
391 do { \
392 int rc = call args; \
393 if (rc != 0) { \
394 errno = rc; \
395 std::string message(# call); \
396 message += " failed for "; \
397 message += reason; \
398 Fatal(message); \
399 } \
400 } while (false)
401
402 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700403 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 is_watch_dog_enabled_ = is_watch_dog_enabled;
405 if (!is_watch_dog_enabled_) {
406 return;
407 }
408 shutting_down_ = false;
409 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
414 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
415 }
416 ~WatchDog() {
417 if (!is_watch_dog_enabled_) {
418 return;
419 }
420 const char* reason = "dex2oat watch dog thread shutdown";
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
422 shutting_down_ = true;
423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
425
Kenny Root51316382014-05-13 14:59:37 -0700426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427
428 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
429 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
430 }
431
432 private:
433 static void* CallBack(void* arg) {
434 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
435 ::art::SetThreadName("dex2oat watch dog");
436 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700437 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 }
439
Andreas Gampe794ad762015-02-23 08:12:24 -0800440 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700441 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
442 // it's rather easy to hang in unwinding.
443 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
444 // logcat logging or stderr output.
445 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 exit(1);
447 }
448
449 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
451 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700452 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453 timespec timeout_ts;
454 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
455 const char* reason = "dex2oat watch dog thread waiting";
456 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
457 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800458 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700460 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
461 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462 } else if (rc != 0) {
463 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
464 strerror(errno)));
465 Fatal(message.c_str());
466 }
467 }
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
469 }
470
471 // 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 -0700472 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700473 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800474
Andreas Gampe540138a2015-09-14 15:34:38 -0700475 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
476 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
477 // itself before that watchdog would take down the system server.
478 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479
480 bool is_watch_dog_enabled_;
481 bool shutting_down_;
482 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
483 pthread_mutex_t mutex_;
484 pthread_cond_t cond_;
485 pthread_attr_t attr_;
486 pthread_t pthread_;
487};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488
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.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 image_file_location_oat_checksum_(0),
496 image_file_location_oat_data_begin_(0),
497 image_patch_delta_(0),
498 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700499 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800500 method_inliner_map_(),
501 runtime_(nullptr),
502 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
503 start_ns_(NanoTime()),
504 oat_fd_(-1),
505 zip_fd_(-1),
506 image_base_(0U),
507 image_classes_zip_filename_(nullptr),
508 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800509 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800510 compiled_classes_zip_filename_(nullptr),
511 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700512 compiled_methods_zip_filename_(nullptr),
513 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700514 app_image_(false),
515 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800516 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800517 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000518 class_loader_(nullptr),
519 elf_writers_(),
520 oat_writers_(),
521 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000522 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700523 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 opened_dex_files_maps_(),
525 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000526 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800527 dump_stats_(false),
528 dump_passes_(false),
529 dump_timing_(false),
530 dump_slow_timing_(kIsDebugBuild),
Calin Juravle2e2db782016-02-23 12:00:03 +0000531 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800532 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000533 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800534 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000535 force_determinism_(false)
536 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800537
538 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800539 // Log completion time before deleting the runtime_, because this accesses
540 // the runtime.
541 LogCompletionTime();
542
Vladimir Marko307dac92015-10-20 11:20:09 +0100543 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
544 // We want to just exit on non-debug builds, not bringing the runtime down
545 // in an orderly fashion. So release the following fields.
546 driver_.release();
547 image_writer_.release();
548 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
549 dex_file.release();
550 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000551 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
552 map.release();
553 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800554 for (std::unique_ptr<File>& oat_file : oat_files_) {
555 oat_file.release();
556 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100557 runtime_.release();
558 verification_results_.release();
559 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100560 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700561 }
562
Roland Levillain9ec5e222015-08-17 20:18:41 +0100563 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800564 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800565 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800566 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000567 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800568 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100569 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800570
Roland Levillain9ec5e222015-08-17 20:18:41 +0100571 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000572 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100573 }
574
575 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000576 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100577 }
578
Calin Juravle877fd962016-01-05 14:29:29 +0000579 void ParseFdForCollection(const StringPiece& option,
580 const char* arg_name,
581 std::vector<uint32_t>* fds) {
582 uint32_t fd;
583 ParseUintOption(option, arg_name, &fd, Usage);
584 fds->push_back(fd);
585 }
586
Roland Levillain9ec5e222015-08-17 20:18:41 +0100587 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000588 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100589 }
590
591 void ParseBase(const StringPiece& option) {
592 DCHECK(option.starts_with("--base="));
593 const char* image_base_str = option.substr(strlen("--base=")).data();
594 char* end;
595 image_base_ = strtoul(image_base_str, &end, 16);
596 if (end == image_base_str || *end != '\0') {
597 Usage("Failed to parse hexadecimal value for option %s", option.data());
598 }
599 }
600
601 void ParseInstructionSet(const StringPiece& option) {
602 DCHECK(option.starts_with("--instruction-set="));
603 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
604 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
605 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
606 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
607 buf.get()[instruction_set_str.length()] = 0;
608 instruction_set_ = GetInstructionSetFromString(buf.get());
609 // arm actually means thumb2.
610 if (instruction_set_ == InstructionSet::kArm) {
611 instruction_set_ = InstructionSet::kThumb2;
612 }
613 }
614
615 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
616 DCHECK(option.starts_with("--instruction-set-variant="));
617 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
618 instruction_set_features_.reset(
619 InstructionSetFeatures::FromVariant(
620 instruction_set_, str.as_string(), &parser_options->error_msg));
621 if (instruction_set_features_.get() == nullptr) {
622 Usage("%s", parser_options->error_msg.c_str());
623 }
624 }
625
626 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
627 DCHECK(option.starts_with("--instruction-set-features="));
628 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
629 if (instruction_set_features_.get() == nullptr) {
630 instruction_set_features_.reset(
631 InstructionSetFeatures::FromVariant(
632 instruction_set_, "default", &parser_options->error_msg));
633 if (instruction_set_features_.get() == nullptr) {
634 Usage("Problem initializing default instruction set features variant: %s",
635 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800637 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100638 instruction_set_features_.reset(
639 instruction_set_features_->AddFeaturesFromString(str.as_string(),
640 &parser_options->error_msg));
641 if (instruction_set_features_.get() == nullptr) {
642 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
643 }
644 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800645
Roland Levillain9ec5e222015-08-17 20:18:41 +0100646 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
647 DCHECK(option.starts_with("--compiler-backend="));
648 parser_options->requested_specific_compiler = true;
649 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
650 if (backend_str == "Quick") {
651 compiler_kind_ = Compiler::kQuick;
652 } else if (backend_str == "Optimizing") {
653 compiler_kind_ = Compiler::kOptimizing;
654 } else {
655 Usage("Unknown compiler backend: %s", backend_str.data());
656 }
657 }
658
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800659 void ParseImageFormat(const StringPiece& option) {
660 const StringPiece substr("--image-format=");
661 DCHECK(option.starts_with(substr));
662 const StringPiece format_str = option.substr(substr.length());
663 if (format_str == "lz4") {
664 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800665 } else if (format_str == "lz4hc") {
666 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800667 } else if (format_str == "uncompressed") {
668 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
669 } else {
670 Usage("Unknown image format: %s", format_str.data());
671 }
672 }
673
Jeff Hao436183f2016-01-12 16:36:50 -0800674 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800675 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700676 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
677
678 if (IsAppImage() && IsBootImage()) {
679 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
680 }
681
Jeff Haodcdc85b2015-12-04 14:06:18 -0800682 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800683 Usage("Output must be supplied with either --oat-file or --oat-fd");
684 }
685
Jeff Haodcdc85b2015-12-04 14:06:18 -0800686 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800687 Usage("--oat-file should not be used with --oat-fd");
688 }
689
Roland Levillain9ec5e222015-08-17 20:18:41 +0100690 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800691 Usage("--oat-symbols should not be used with --oat-fd");
692 }
693
Roland Levillain9ec5e222015-08-17 20:18:41 +0100694 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800695 Usage("--oat-symbols should not be used with --host");
696 }
697
Jeff Haodcdc85b2015-12-04 14:06:18 -0800698 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800699 Usage("--oat-fd should not be used with --image");
700 }
701
Jeff Haodcdc85b2015-12-04 14:06:18 -0800702 if (!parser_options->oat_symbols.empty() &&
703 parser_options->oat_symbols.size() != oat_filenames_.size()) {
704 Usage("--oat-file arguments do not match --oat-symbols arguments");
705 }
706
707 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
708 Usage("--oat-file arguments do not match --image arguments");
709 }
710
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 if (android_root_.empty()) {
712 const char* android_root_env_var = getenv("ANDROID_ROOT");
713 if (android_root_env_var == nullptr) {
714 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 android_root_ += android_root_env_var;
717 }
718
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700719 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100720 parser_options->boot_image_filename += android_root_;
721 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100723 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000724 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800725 }
726
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700727 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 Usage("--image-classes should only be used with --image");
729 }
730
Vladimir Marko49b0f452015-12-10 13:49:19 +0000731 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800732 Usage("--image-classes should not be used with --boot-image");
733 }
734
735 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
736 Usage("--image-classes-zip should be used with --image-classes");
737 }
738
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700739 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800740 Usage("--compiled-classes should only be used with --image");
741 }
742
Vladimir Marko49b0f452015-12-10 13:49:19 +0000743 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800744 Usage("--compiled-classes should not be used with --boot-image");
745 }
746
747 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
748 Usage("--compiled-classes-zip should be used with --compiled-classes");
749 }
750
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 if (dex_filenames_.empty() && zip_fd_ == -1) {
752 Usage("Input must be supplied with either --dex-file or --zip-fd");
753 }
754
755 if (!dex_filenames_.empty() && zip_fd_ != -1) {
756 Usage("--dex-file should not be used with --zip-fd");
757 }
758
759 if (!dex_filenames_.empty() && !zip_location_.empty()) {
760 Usage("--dex-file should not be used with --zip-location");
761 }
762
763 if (dex_locations_.empty()) {
764 for (const char* dex_file_name : dex_filenames_) {
765 dex_locations_.push_back(dex_file_name);
766 }
767 } else if (dex_locations_.size() != dex_filenames_.size()) {
768 Usage("--dex-location arguments do not match --dex-file arguments");
769 }
770
Jeff Haodcdc85b2015-12-04 14:06:18 -0800771 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
772 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
773 Usage("--oat-file arguments must be singular or match --dex-file arguments");
774 }
775 }
776
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800777 if (zip_fd_ != -1 && zip_location_.empty()) {
778 Usage("--zip-location should be supplied with --zip-fd");
779 }
780
Vladimir Marko49b0f452015-12-10 13:49:19 +0000781 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800782 if (image_base_ == 0) {
783 Usage("Non-zero --base not specified");
784 }
785 }
786
Mathieu Chartiera8077802016-03-16 19:08:31 -0700787 const bool have_profile_file = !profile_file_.empty();
788 const bool have_profile_fd = profile_file_fd_ != kInvalidFd;
789 if (have_profile_file && have_profile_fd) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000790 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200791 }
792
Roland Levillain9ec5e222015-08-17 20:18:41 +0100793 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800794 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 }
796
797 // If no instruction set feature was given, use the default one for the target
798 // instruction set.
799 if (instruction_set_features_.get() == nullptr) {
800 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100801 InstructionSetFeatures::FromVariant(
802 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800803 if (instruction_set_features_.get() == nullptr) {
804 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100805 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800806 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 }
808
809 if (instruction_set_ == kRuntimeISA) {
810 std::unique_ptr<const InstructionSetFeatures> runtime_features(
811 InstructionSetFeatures::FromCppDefines());
812 if (!instruction_set_features_->Equals(runtime_features.get())) {
813 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
814 << *instruction_set_features_ << ") and those of dex2oat executable ("
815 << *runtime_features <<") for the command line:\n"
816 << CommandLine();
817 }
818 }
819
Roland Levillaina215b952015-08-07 11:38:32 +0100820 // It they are not set, use default values for inlining settings.
821 // TODO: We should rethink the compiler filter. We mostly save
822 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000823 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
824 compiler_options_->inline_depth_limit_ =
Andreas Gampe29d38e72016-03-23 15:31:51 +0000825 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100826 // Implementation of the space filter: limit inlining depth.
827 ? CompilerOptions::kSpaceFilterInlineDepthLimit
828 : CompilerOptions::kDefaultInlineDepthLimit;
829 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000830 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
831 compiler_options_->inline_max_code_units_ =
Andreas Gampe29d38e72016-03-23 15:31:51 +0000832 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100833 // Implementation of the space filter: limit inlining max code units.
834 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
835 : CompilerOptions::kDefaultInlineMaxCodeUnits;
836 }
837
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800838 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800839 // Set the compilation target's implicit checks options.
840 switch (instruction_set_) {
841 case kArm:
842 case kThumb2:
843 case kArm64:
844 case kX86:
845 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700846 case kMips:
847 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000848 compiler_options_->implicit_null_checks_ = true;
849 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800850 break;
851
852 default:
853 // Defaults are correct.
854 break;
855 }
856
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000857 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800858
Jeff Hao436183f2016-01-12 16:36:50 -0800859 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800860 Usage("--multi-image can only be used when creating boot images");
861 }
Jeff Hao436183f2016-01-12 16:36:50 -0800862 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800863 Usage("--multi-image cannot be used with multiple image names");
864 }
865
866 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
867 if (!kIsTargetBuild && IsBootImage()) {
868 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800869 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800870 }
871 }
872
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800873 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100874 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800875 watchdog_.reset(new WatchDog(true));
876 }
877
878 // Fill some values into the key-value store for the oat header.
879 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800880
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800881 // Automatically force determinism for the boot image in a host build if the default GC is CMS
882 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
883 // one by passing the option `-Xgc:nonconcurrent` (see below).
884 if (!kIsTargetBuild && IsBootImage()) {
885 if (SupportsDeterministicCompilation()) {
886 force_determinism_ = true;
887 } else {
888 LOG(WARNING) << "Deterministic compilation is disabled.";
889 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800890 }
891 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100892 }
893
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800894 static bool SupportsDeterministicCompilation() {
895 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
896 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
897 !kEmitCompilerReadBarrier;
898 }
899
Jeff Hao436183f2016-01-12 16:36:50 -0800900 void ExpandOatAndImageFilenames() {
901 std::string base_oat = oat_filenames_[0];
902 size_t last_oat_slash = base_oat.rfind('/');
903 if (last_oat_slash == std::string::npos) {
904 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
905 }
906 // We also need to honor path components that were encoded through '@'. Otherwise the loading
907 // code won't be able to find the images.
908 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
909 last_oat_slash = base_oat.rfind('@');
910 }
911 base_oat = base_oat.substr(0, last_oat_slash + 1);
912
913 std::string base_img = image_filenames_[0];
914 size_t last_img_slash = base_img.rfind('/');
915 if (last_img_slash == std::string::npos) {
916 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
917 }
918 // We also need to honor path components that were encoded through '@'. Otherwise the loading
919 // code won't be able to find the images.
920 if (base_img.find('@', last_img_slash) != std::string::npos) {
921 last_img_slash = base_img.rfind('@');
922 }
923
924 // Get the prefix, which is the primary image name (without path components). Strip the
925 // extension.
926 std::string prefix = base_img.substr(last_img_slash + 1);
927 if (prefix.rfind('.') != std::string::npos) {
928 prefix = prefix.substr(0, prefix.rfind('.'));
929 }
930 if (!prefix.empty()) {
931 prefix = prefix + "-";
932 }
933
934 base_img = base_img.substr(0, last_img_slash + 1);
935
936 // Note: we have some special case here for our testing. We have to inject the differentiating
937 // parts for the different core images.
938 std::string infix; // Empty infix by default.
939 {
940 // Check the first name.
941 std::string dex_file = oat_filenames_[0];
942 size_t last_dex_slash = dex_file.rfind('/');
943 if (last_dex_slash != std::string::npos) {
944 dex_file = dex_file.substr(last_dex_slash + 1);
945 }
946 size_t last_dex_dot = dex_file.rfind('.');
947 if (last_dex_dot != std::string::npos) {
948 dex_file = dex_file.substr(0, last_dex_dot);
949 }
950 if (StartsWith(dex_file, "core-")) {
951 infix = dex_file.substr(strlen("core"));
952 }
953 }
954
955 // Now create the other names. Use a counted loop to skip the first one.
956 for (size_t i = 1; i < dex_locations_.size(); ++i) {
957 // TODO: Make everything properly std::string.
958 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
959 char_backing_storage_.push_back(base_img + image_name);
960 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
961
962 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
963 char_backing_storage_.push_back(base_oat + oat_name);
964 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
965 }
966 }
967
Andreas Gampe8994a042015-12-30 19:03:17 +0000968 // Modify the input string in the following way:
969 // 0) Assume input is /a/b/c.d
970 // 1) Strip the path -> c.d
971 // 2) Inject prefix p -> pc.d
972 // 3) Inject infix i -> pci.d
973 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800974 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000975 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800976 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000977 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800978 size_t last_dex_slash = in.rfind('/');
979 if (last_dex_slash != std::string::npos) {
980 in = in.substr(last_dex_slash + 1);
981 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000982 if (!prefix.empty()) {
983 in = prefix + in;
984 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800985 if (!infix.empty()) {
986 // Inject infix.
987 size_t last_dot = in.rfind('.');
988 if (last_dot != std::string::npos) {
989 in.insert(last_dot, infix);
990 }
991 }
992 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +0000993 in = in.substr(0, in.length() - strlen(".jar")) +
994 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800995 }
996 return in;
997 }
998
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000999 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001000 std::ostringstream oss;
1001 for (int i = 0; i < argc; ++i) {
1002 if (i > 0) {
1003 oss << ' ';
1004 }
1005 oss << argv[i];
1006 }
1007 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1008 oss.str(""); // Reset.
1009 oss << kRuntimeISA;
1010 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1011 key_value_store_->Put(
1012 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001013 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001014 key_value_store_->Put(
1015 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001016 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Srbecky5d950762016-03-07 20:47:29 +00001017 key_value_store_->Put(
1018 OatHeader::kNativeDebuggableKey,
David Srbecky346dc992016-03-13 22:00:07 +00001019 compiler_options_->GetNativeDebuggable() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe29d38e72016-03-23 15:31:51 +00001020 key_value_store_->Put(OatHeader::kCompilerFilter,
1021 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
Richard Uhlerd1537b52016-03-29 13:27:41 -07001022 key_value_store_->Put(OatHeader::kHasPatchInfoKey,
1023 compiler_options_->GetIncludePatchInformation() ? OatHeader::kTrueValue
1024 : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001025 }
1026
1027 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1028 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1029 // returns, arguments have been successfully parsed.
1030 void ParseArgs(int argc, char** argv) {
1031 original_argc = argc;
1032 original_argv = argv;
1033
1034 InitLogging(argv);
1035
1036 // Skip over argv[0].
1037 argv++;
1038 argc--;
1039
1040 if (argc == 0) {
1041 Usage("No arguments specified");
1042 }
1043
1044 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001045 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001046
1047 for (int i = 0; i < argc; i++) {
1048 const StringPiece option(argv[i]);
1049 const bool log_options = false;
1050 if (log_options) {
1051 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1052 }
1053 if (option.starts_with("--dex-file=")) {
1054 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1055 } else if (option.starts_with("--dex-location=")) {
1056 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1057 } else if (option.starts_with("--zip-fd=")) {
1058 ParseZipFd(option);
1059 } else if (option.starts_with("--zip-location=")) {
1060 zip_location_ = option.substr(strlen("--zip-location=")).data();
1061 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001062 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001063 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001064 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001065 } else if (option.starts_with("--oat-fd=")) {
1066 ParseOatFd(option);
1067 } else if (option == "--watch-dog") {
1068 parser_options->watch_dog_enabled = true;
1069 } else if (option == "--no-watch-dog") {
1070 parser_options->watch_dog_enabled = false;
1071 } else if (option.starts_with("-j")) {
1072 ParseJ(option);
1073 } else if (option.starts_with("--oat-location=")) {
1074 oat_location_ = option.substr(strlen("--oat-location=")).data();
1075 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001077 } else if (option.starts_with("--image-classes=")) {
1078 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1079 } else if (option.starts_with("--image-classes-zip=")) {
1080 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001081 } else if (option.starts_with("--image-format=")) {
1082 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001083 } else if (option.starts_with("--compiled-classes=")) {
1084 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1085 } else if (option.starts_with("--compiled-classes-zip=")) {
1086 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1087 } else if (option.starts_with("--compiled-methods=")) {
1088 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1089 } else if (option.starts_with("--compiled-methods-zip=")) {
1090 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1091 } else if (option.starts_with("--base=")) {
1092 ParseBase(option);
1093 } else if (option.starts_with("--boot-image=")) {
1094 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1095 } else if (option.starts_with("--android-root=")) {
1096 android_root_ = option.substr(strlen("--android-root=")).data();
1097 } else if (option.starts_with("--instruction-set=")) {
1098 ParseInstructionSet(option);
1099 } else if (option.starts_with("--instruction-set-variant=")) {
1100 ParseInstructionSetVariant(option, parser_options.get());
1101 } else if (option.starts_with("--instruction-set-features=")) {
1102 ParseInstructionSetFeatures(option, parser_options.get());
1103 } else if (option.starts_with("--compiler-backend=")) {
1104 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001105 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001106 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001107 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001108 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001109 } else if (option == "--host") {
1110 is_host_ = true;
1111 } else if (option == "--runtime-arg") {
1112 if (++i >= argc) {
1113 Usage("Missing required argument for --runtime-arg");
1114 }
1115 if (log_options) {
1116 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1117 }
1118 runtime_args_.push_back(argv[i]);
1119 } else if (option == "--dump-timing") {
1120 dump_timing_ = true;
1121 } else if (option == "--dump-passes") {
1122 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001123 } else if (option == "--dump-stats") {
1124 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001125 } else if (option.starts_with("--swap-file=")) {
1126 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1127 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001128 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
Andreas Gampee1459ae2016-06-29 09:36:30 -07001129 } else if (option.starts_with("--swap-dex-size-threshold=")) {
1130 ParseUintOption(option,
1131 "--swap-dex-size-threshold",
1132 &min_dex_file_cumulative_size_for_swap_,
1133 Usage);
1134 } else if (option.starts_with("--swap-dex-count-threshold=")) {
1135 ParseUintOption(option,
1136 "--swap-dex-count-threshold",
1137 &min_dex_files_for_swap_,
1138 Usage);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001139 } else if (option.starts_with("--app-image-file=")) {
1140 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1141 } else if (option.starts_with("--app-image-fd=")) {
1142 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001143 } else if (option.starts_with("--verbose-methods=")) {
1144 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1145 // conditional on having verbost methods.
1146 gLogVerbosity.compiler = false;
1147 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001148 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001149 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001150 } else if (option.starts_with("--no-inline-from=")) {
1151 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001152 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001153 if (!SupportsDeterministicCompilation()) {
1154 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001155 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001156 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001157 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001158 Usage("Unknown argument %s", option.data());
1159 }
1160 }
1161
Jeff Hao436183f2016-01-12 16:36:50 -08001162 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001163
1164 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001165 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001166 }
1167
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168 // Check whether the oat output files are writable, and open them for later. Also open a swap
1169 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001170 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001171 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1172 PruneNonExistentDexFiles();
1173
Jeff Hao436183f2016-01-12 16:36:50 -08001174 // Expand oat and image filenames for multi image.
1175 if (IsBootImage() && multi_image_) {
1176 ExpandOatAndImageFilenames();
1177 }
1178
Jeff Haodcdc85b2015-12-04 14:06:18 -08001179 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 for (const char* oat_filename : oat_filenames_) {
1182 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1183 if (oat_file.get() == nullptr) {
1184 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1185 return false;
1186 }
1187 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1188 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1189 oat_file->Erase();
1190 return false;
1191 }
1192 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001193 }
1194 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001195 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1196 oat_file->DisableAutoClose();
1197 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001198 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1199 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001200 if (oat_file.get() == nullptr) {
1201 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1202 return false;
1203 }
1204 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1205 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1206 oat_file->Erase();
1207 return false;
1208 }
1209 oat_filenames_.push_back(oat_location_.c_str());
1210 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001212
1213 // Swap file handling.
1214 //
1215 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1216 // that we can use for swap.
1217 //
1218 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1219 // will immediately unlink to satisfy the swap fd assumption.
1220 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1221 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1222 if (swap_file.get() == nullptr) {
1223 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1224 return false;
1225 }
1226 swap_fd_ = swap_file->Fd();
1227 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1228 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1229 // released immediately.
1230 unlink(swap_file_name_.c_str());
1231 }
Jeff Hao436183f2016-01-12 16:36:50 -08001232
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001233 return true;
1234 }
1235
Jeff Haodcdc85b2015-12-04 14:06:18 -08001236 void EraseOatFiles() {
1237 for (size_t i = 0; i < oat_files_.size(); ++i) {
1238 DCHECK(oat_files_[i].get() != nullptr);
1239 oat_files_[i]->Erase();
1240 oat_files_[i].reset();
1241 }
Andreas Gampea650e702014-12-03 14:28:02 -08001242 }
1243
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001244 void Shutdown() {
1245 ScopedObjectAccess soa(Thread::Current());
1246 for (jobject dex_cache : dex_caches_) {
1247 soa.Env()->DeleteLocalRef(dex_cache);
1248 }
1249 dex_caches_.clear();
1250 }
1251
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001252 void LoadClassProfileDescriptors() {
1253 if (profile_compilation_info_ != nullptr && app_image_) {
1254 Runtime* runtime = Runtime::Current();
1255 CHECK(runtime != nullptr);
1256 std::set<DexCacheResolvedClasses> resolved_classes(
1257 profile_compilation_info_->GetResolvedClasses());
Mathieu Chartier0b490842016-05-25 15:05:59 -07001258
1259 // Filter out class path classes since we don't want to include these in the image.
1260 std::unordered_set<std::string> dex_files_locations;
1261 for (const DexFile* dex_file : dex_files_) {
1262 dex_files_locations.insert(dex_file->GetLocation());
1263 }
1264 for (auto it = resolved_classes.begin(); it != resolved_classes.end(); ) {
1265 if (dex_files_locations.find(it->GetDexLocation()) == dex_files_locations.end()) {
1266 VLOG(compiler) << "Removed profile samples for non-app dex file " << it->GetDexLocation();
1267 it = resolved_classes.erase(it);
1268 } else {
1269 ++it;
1270 }
1271 }
1272
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001273 image_classes_.reset(new std::unordered_set<std::string>(
1274 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes)));
1275 VLOG(compiler) << "Loaded " << image_classes_->size()
1276 << " image class descriptors from profile";
1277 if (VLOG_IS_ON(compiler)) {
1278 for (const std::string& s : *image_classes_) {
1279 LOG(INFO) << "Image class " << s;
1280 }
1281 }
1282 }
1283 }
1284
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001285 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1286 // boot class path.
1287 bool Setup() {
1288 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001289 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001290
1291 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1292 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001293 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001294
Vladimir Marko307dac92015-10-20 11:20:09 +01001295 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001296 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001297 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001298 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001299 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001300 CompilerCallbacks::CallbackMode::kCompileBootImage :
1301 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001302
Vladimir Marko49b0f452015-12-10 13:49:19 +00001303 RuntimeArgumentMap runtime_options;
1304 if (!PrepareRuntimeOptions(&runtime_options)) {
1305 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001306 }
1307
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001308 CreateOatWriters();
1309 if (!AddDexFileSources()) {
1310 return false;
1311 }
1312
1313 if (IsBootImage() && image_filenames_.size() > 1) {
1314 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1315 // We need this for the multi-image case.
Jeff Haof0192c82016-03-28 20:39:50 -07001316 key_value_store_->Put(OatHeader::kBootClassPathKey, GetMultiImageBootClassPath());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001317 }
1318
1319 if (!IsBootImage()) {
1320 // When compiling an app, create the runtime early to retrieve
1321 // the image location key needed for the oat header.
1322 if (!CreateRuntime(std::move(runtime_options))) {
1323 return false;
1324 }
1325
Andreas Gampe29d38e72016-03-23 15:31:51 +00001326 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001327 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1328 std::vector<gc::space::ImageSpace*> image_spaces =
1329 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Jeff Haob11ffb72016-04-07 15:40:54 -07001330 image_file_location_oat_checksum_ = OatFileAssistant::CalculateCombinedImageChecksum();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001331 image_file_location_oat_data_begin_ =
1332 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1333 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1334 // Store the boot image filename(s).
1335 std::vector<std::string> image_filenames;
1336 for (const gc::space::ImageSpace* image_space : image_spaces) {
1337 image_filenames.push_back(image_space->GetImageFilename());
1338 }
1339 std::string image_file_location = Join(image_filenames, ':');
1340 if (!image_file_location.empty()) {
1341 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1342 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001343 } else {
1344 image_file_location_oat_checksum_ = 0u;
1345 image_file_location_oat_data_begin_ = 0u;
1346 image_patch_delta_ = 0;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001347 }
1348
1349 // Open dex files for class path.
1350 const std::vector<std::string> class_path_locations =
1351 GetClassPathLocations(runtime_->GetClassPathString());
Jeff Haofbeb1322016-04-26 14:27:31 -07001352 OpenClassPathFiles(class_path_locations,
1353 &class_path_files_,
1354 &opened_oat_files_,
1355 runtime_->GetInstructionSet());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001356
1357 // Store the classpath we have right now.
1358 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
Jeff Haof0192c82016-03-28 20:39:50 -07001359 std::string encoded_class_path;
1360 if (class_path_locations.size() == 1 &&
1361 class_path_locations[0] == OatFile::kSpecialSharedLibrary) {
1362 // When passing the special shared library as the classpath, it is the only path.
1363 encoded_class_path = OatFile::kSpecialSharedLibrary;
1364 } else {
1365 encoded_class_path = OatFile::EncodeDexFileDependencies(class_path_files);
1366 }
1367 key_value_store_->Put(OatHeader::kClassPathKey, encoded_class_path);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001368 }
1369
1370 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001371 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001372 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1373 rodata_.reserve(oat_writers_.size());
1374 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1375 rodata_.push_back(elf_writers_[i]->StartRoData());
1376 // Unzip or copy dex files straight to the oat file.
1377 std::unique_ptr<MemMap> opened_dex_files_map;
1378 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1379 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1380 oat_files_[i].get(),
1381 instruction_set_,
1382 instruction_set_features_.get(),
1383 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001384 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001385 &opened_dex_files_map,
1386 &opened_dex_files)) {
1387 return false;
1388 }
1389 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1390 if (opened_dex_files_map != nullptr) {
1391 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1392 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001393 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001394 opened_dex_files_.push_back(std::move(dex_file));
1395 }
1396 } else {
1397 DCHECK(opened_dex_files.empty());
1398 }
1399 }
1400 }
1401
1402 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
Andreas Gampe7386da42016-06-08 18:18:47 -07001403
1404 // We had to postpone the swap decision till now, as this is the point when we actually
1405 // know about the dex files we're going to use.
1406
1407 // Make sure that we didn't create the driver, yet.
1408 CHECK(driver_ == nullptr);
1409 // If we use a swap file, ensure we are above the threshold to make it necessary.
1410 if (swap_fd_ != -1) {
1411 if (!UseSwap(IsBootImage(), dex_files_)) {
1412 close(swap_fd_);
1413 swap_fd_ = -1;
1414 VLOG(compiler) << "Decided to run without swap.";
1415 } else {
1416 LOG(INFO) << "Large app, accepted running with swap.";
1417 }
1418 }
1419 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1420
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001421 if (IsBootImage()) {
1422 // For boot image, pass opened dex files to the Runtime::Create().
1423 // Note: Runtime acquires ownership of these dex files.
1424 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001425 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001426 return false;
1427 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001428 }
1429
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001430 // If we're doing the image, override the compiler filter to force full compilation. Must be
1431 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1432 // compilation of class initializers.
1433 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001434 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001435 WellKnownClasses::Init(self->GetJniEnv());
1436
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001437 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001438 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001439 constexpr bool kSaveDexInput = false;
1440 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001441 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001442 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001443
1444 // Handle and ClassLoader creation needs to come after Runtime::Create.
1445 ScopedObjectAccess soa(self);
1446
1447 // Classpath: first the class-path given.
1448 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1449
1450 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1451 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1452
1453 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001454 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001455
1456 // Ensure opened dex files are writable for dex-to-dex transformations.
1457 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1458 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1459 PLOG(ERROR) << "Failed to make .dex files writeable.";
1460 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001461 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001462 }
1463
1464 // Ensure that the dex caches stay live since we don't want class unloading
1465 // to occur during compilation.
1466 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001467 ScopedObjectAccess soa(self);
1468 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierf284d442016-06-02 11:48:30 -07001469 class_linker->RegisterDexFile(*dex_file,
1470 soa.Decode<mirror::ClassLoader*>(class_loader_))));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001471 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001472
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001473 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001474 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001475
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001476 // If we need to keep the oat file open for the image writer.
1477 bool ShouldKeepOatFileOpen() const {
1478 return IsImage() && oat_fd_ != kInvalidFd;
1479 }
1480
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001481 // Create and invoke the compiler driver. This will compile all the dex files.
1482 void Compile() {
1483 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1484 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001485
Vladimir Marko47496c22016-01-27 16:15:08 +00001486 // Find the dex files we should not inline from.
1487
1488 std::vector<std::string> no_inline_filters;
1489 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001490
1491 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001492 const std::string core_oj = "core-oj";
1493 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1494 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 }
1496
Vladimir Marko47496c22016-01-27 16:15:08 +00001497 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001498 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1499 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1500 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1501 &class_linker->GetBootClassPath(),
1502 &class_path_files,
1503 &dex_files_
1504 };
1505 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001506 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001507 for (const std::string& filter : no_inline_filters) {
1508 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1509 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1510 // base location passes the StartsWith() test, so do all extra locations.
1511 std::string dex_location = dex_file->GetLocation();
1512 if (filter.find('/') == std::string::npos) {
1513 // The filter does not contain the path. Remove the path from dex_location as well.
1514 size_t last_slash = dex_file->GetLocation().rfind('/');
1515 if (last_slash != std::string::npos) {
1516 dex_location = dex_location.substr(last_slash + 1);
1517 }
1518 }
1519
1520 if (StartsWith(dex_location, filter.c_str())) {
1521 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1522 no_inline_from_dex_files_.push_back(dex_file);
1523 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001524 }
1525 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001526 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001527 }
1528 if (!no_inline_from_dex_files_.empty()) {
1529 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001530 }
1531 }
1532
Vladimir Marko307dac92015-10-20 11:20:09 +01001533 driver_.reset(new CompilerDriver(compiler_options_.get(),
1534 verification_results_.get(),
1535 &method_inliner_map_,
1536 compiler_kind_,
1537 instruction_set_,
1538 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001539 IsBootImage(),
Mathieu Chartier91288d82016-04-28 09:44:54 -07001540 IsAppImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001541 image_classes_.release(),
1542 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001543 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001544 thread_count_,
1545 dump_stats_,
1546 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001547 compiler_phases_timings_.get(),
1548 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001549 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001550 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001551 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001552 }
1553
Jeff Hao436183f2016-01-12 16:36:50 -08001554 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001555 // ensure the references between the two are correct.
1556 //
1557 // Currently we have a memory layout that looks something like this:
1558 //
1559 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001560 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001561 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001562 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001563 // +--------------+
1564 // | alloc spaces |
1565 // +--------------+
1566 //
Jeff Hao436183f2016-01-12 16:36:50 -08001567 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 //
Jeff Hao436183f2016-01-12 16:36:50 -08001569 // 1. The images are expected to be loaded at an absolute address and
1570 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001571 //
Jeff Hao436183f2016-01-12 16:36:50 -08001572 // 2. There are absolute pointers from Methods in the images to their
1573 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001574 //
Jeff Hao436183f2016-01-12 16:36:50 -08001575 // 3. There are absolute pointers from the code in the oat files to Methods
1576 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001577 //
Jeff Hao436183f2016-01-12 16:36:50 -08001578 // 4. There are absolute pointers from code in the oat files to other code
1579 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001580 //
1581 // To get this all correct, we go through several steps.
1582 //
Jeff Hao436183f2016-01-12 16:36:50 -08001583 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001584 // the oat data size and code size. During this stage, we also set
1585 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586 //
Jeff Hao436183f2016-01-12 16:36:50 -08001587 // 2. We prepare offsets for the objects in the images and calculate
1588 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001589 //
Jeff Hao436183f2016-01-12 16:36:50 -08001590 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001591 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001592 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001593 // can prepare the ELF headers and we then know the ELF memory segment
1594 // layout and we can now resolve all references. The compiler provides
1595 // LinkerPatch information in each CompiledMethod and we resolve these,
1596 // using the layout information and image object locations provided by
1597 // image writer, as we're writing the method code.
1598 //
Jeff Hao436183f2016-01-12 16:36:50 -08001599 // 4. We create the image files. They need to know where the oat files
1600 // will be loaded after itself. Originally oat files were simply
1601 // memory mapped so we could predict where their contents were based
1602 // on the file size. Now that they are ELF files, we need to inspect
1603 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001604 // where the oat header is located within.
1605 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001606 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001607 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001608 // load the .so at the desired location at runtime by offsetting the
1609 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001610 // TODO: Do this in step 3. We already know the layout there.
1611 //
1612 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1613 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001614
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001615 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1616 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001617 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1618 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001619 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001620 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1621
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001622 // Sync the data to the file, in case we did dex2dex transformations.
1623 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1624 if (!map->Sync()) {
1625 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1626 return false;
1627 }
1628 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001629
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001630 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001631 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001632 gc::Heap* const heap = Runtime::Current()->GetHeap();
1633 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001634 image_base_ = std::max(image_base_, RoundUp(
1635 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1636 kPageSize));
1637 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001638 // The non moving space is right after the oat file. Put the preferred app image location
1639 // right after the non moving space so that we ideally get a continuous immune region for
1640 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001641 // Use the default non moving space capacity since dex2oat does not have a separate non-
1642 // moving space. This means the runtime's non moving space space size will be as large
1643 // as the growth limit for dex2oat, but smaller in the zygote.
1644 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001645 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001646 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1647 }
1648
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001649 image_writer_.reset(new ImageWriter(*driver_,
1650 image_base_,
1651 compiler_options_->GetCompilePic(),
1652 IsAppImage(),
1653 image_storage_mode_,
1654 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001655 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001656
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001657 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001658 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1659 if (!image_writer_->PrepareImageAddressSpace()) {
1660 LOG(ERROR) << "Failed to prepare image address space.";
1661 return false;
1662 }
1663 }
1664
Vladimir Marko944da602016-02-19 12:27:55 +00001665 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001666 {
1667 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001668 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001669 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1670 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1671
1672 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1673 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1674
1675 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1676 size_t text_size = oat_writer->GetSize() - rodata_size;
1677 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1678
1679 if (IsImage()) {
1680 // Update oat layout.
1681 DCHECK(image_writer_ != nullptr);
1682 DCHECK_LT(i, oat_filenames_.size());
1683 image_writer_->UpdateOatFileLayout(i,
1684 elf_writer->GetLoadedSize(),
1685 oat_writer->GetOatDataOffset(),
1686 oat_writer->GetSize());
1687 }
1688 }
1689
1690 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001691 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1693 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001694
David Srbecky09c2a6b2016-03-11 17:11:44 +00001695 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader()));
1696
David Srbecky0c4572e2016-01-22 19:19:25 +00001697 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001698 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1699 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001700
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001701 OutputStream*& rodata = rodata_[i];
1702 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001703 if (!oat_writer->WriteRodata(rodata)) {
1704 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1705 return false;
1706 }
1707 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001708 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001709
Jeff Haodcdc85b2015-12-04 14:06:18 -08001710 OutputStream* text = elf_writer->StartText();
1711 if (!oat_writer->WriteCode(text)) {
1712 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1713 return false;
1714 }
1715 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001716
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001717 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1718 image_file_location_oat_checksum_,
1719 image_file_location_oat_data_begin_,
1720 image_patch_delta_)) {
1721 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1722 return false;
1723 }
1724
Vladimir Marko944da602016-02-19 12:27:55 +00001725 if (IsImage()) {
1726 // Update oat header information.
1727 DCHECK(image_writer_ != nullptr);
1728 DCHECK_LT(i, oat_filenames_.size());
1729 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1730 }
1731
Jeff Haodcdc85b2015-12-04 14:06:18 -08001732 elf_writer->WriteDynamicSection();
1733 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1734 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001735
Jeff Haodcdc85b2015-12-04 14:06:18 -08001736 if (!elf_writer->End()) {
1737 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1738 return false;
1739 }
1740
1741 // Flush the oat file.
1742 if (oat_files_[i] != nullptr) {
1743 if (oat_files_[i]->Flush() != 0) {
1744 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 return false;
1746 }
1747 }
1748
Jeff Haodcdc85b2015-12-04 14:06:18 -08001749 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001750
1751 oat_writer.reset();
1752 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001753 }
1754 }
1755
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001756 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001757 }
1758
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001759 // If we are compiling an image, invoke the image creation routine. Else just skip.
1760 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001761 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001762 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1763 if (!CreateImageFile()) {
1764 return false;
1765 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001766 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001767 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001768 return true;
1769 }
1770
Jeff Haodcdc85b2015-12-04 14:06:18 -08001771 // Create a copy from stripped to unstripped.
1772 bool CopyStrippedToUnstripped() {
1773 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1774 // If we don't want to strip in place, copy from stripped location to unstripped location.
1775 // We need to strip after image creation because FixupElf needs to use .strtab.
1776 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1777 // If the oat file is still open, flush it.
1778 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1779 if (!FlushCloseOatFile(i)) {
1780 return false;
1781 }
1782 }
1783
1784 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1785 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1786 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1787 size_t buffer_size = 8192;
1788 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1789 while (true) {
1790 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1791 if (bytes_read <= 0) {
1792 break;
1793 }
1794 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1795 CHECK(write_ok);
1796 }
1797 if (out->FlushCloseOrErase() != 0) {
1798 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1799 return false;
1800 }
1801 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1802 }
1803 }
1804 return true;
1805 }
1806
1807 bool FlushOatFiles() {
1808 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1809 for (size_t i = 0; i < oat_files_.size(); ++i) {
1810 if (oat_files_[i].get() != nullptr) {
1811 if (oat_files_[i]->Flush() != 0) {
1812 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1813 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001814 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001815 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001816 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001817 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001818 return true;
1819 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001820
Jeff Haodcdc85b2015-12-04 14:06:18 -08001821 bool FlushCloseOatFile(size_t i) {
1822 if (oat_files_[i].get() != nullptr) {
1823 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001824 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001825 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001826 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001827 }
1828 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001829 return true;
1830 }
1831
Jeff Haodcdc85b2015-12-04 14:06:18 -08001832 bool FlushCloseOatFiles() {
1833 bool result = true;
1834 for (size_t i = 0; i < oat_files_.size(); ++i) {
1835 result &= FlushCloseOatFile(i);
1836 }
1837 return result;
1838 }
1839
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001840 void DumpTiming() {
1841 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1842 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1843 }
1844 if (dump_passes_) {
1845 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1846 }
1847 }
1848
Andreas Gampe10e477d2014-11-19 12:57:42 -08001849 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001850 return IsAppImage() || IsBootImage();
1851 }
1852
1853 bool IsAppImage() const {
1854 return app_image_;
1855 }
1856
1857 bool IsBootImage() const {
1858 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001859 }
1860
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001861 bool IsHost() const {
1862 return is_host_;
1863 }
1864
Calin Juravle998c2162015-12-21 15:39:33 +02001865 bool UseProfileGuidedCompilation() const {
Andreas Gampe29d38e72016-03-23 15:31:51 +00001866 return CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter());
Calin Juravle998c2162015-12-21 15:39:33 +02001867 }
1868
Calin Juravle2e2db782016-02-23 12:00:03 +00001869 bool LoadProfile() {
Calin Juravle998c2162015-12-21 15:39:33 +02001870 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001871
1872 profile_compilation_info_.reset(new ProfileCompilationInfo());
1873 ScopedFlock flock;
Andreas Gampe29d38e72016-03-23 15:31:51 +00001874 bool success = true;
Calin Juravle2e2db782016-02-23 12:00:03 +00001875 std::string error;
1876 if (profile_file_fd_ != -1) {
1877 // The file doesn't need to be flushed so don't check the usage.
1878 // Pass a bogus path so that we can easily attribute any reported error.
1879 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1880 if (flock.Init(&file, &error)) {
1881 success = profile_compilation_info_->Load(profile_file_fd_);
1882 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001883 } else if (profile_file_ != "") {
Calin Juravle2e2db782016-02-23 12:00:03 +00001884 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1885 success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1886 }
1887 }
1888 if (!error.empty()) {
1889 LOG(WARNING) << "Cannot lock profiles: " << error;
Calin Juravle998c2162015-12-21 15:39:33 +02001890 }
Calin Juravle877fd962016-01-05 14:29:29 +00001891
Calin Juravle2e2db782016-02-23 12:00:03 +00001892 if (!success) {
1893 profile_compilation_info_.reset(nullptr);
1894 }
Calin Juravle877fd962016-01-05 14:29:29 +00001895
Calin Juravle2e2db782016-02-23 12:00:03 +00001896 return success;
Calin Juravle998c2162015-12-21 15:39:33 +02001897 }
1898
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001899 private:
Andreas Gampee1459ae2016-06-29 09:36:30 -07001900 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) {
1901 if (is_image) {
1902 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
1903 return false;
1904 }
1905 if (dex_files.size() < min_dex_files_for_swap_) {
1906 // If there are less dex files than the threshold, assume it's gonna be fine.
1907 return false;
1908 }
1909 size_t dex_files_size = 0;
1910 for (const auto* dex_file : dex_files) {
1911 dex_files_size += dex_file->GetHeader().file_size_;
1912 }
1913 return dex_files_size >= min_dex_file_cumulative_size_for_swap_;
1914 }
1915
Vladimir Marko49b0f452015-12-10 13:49:19 +00001916 template <typename T>
1917 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1918 std::vector<T*> result;
1919 result.reserve(src.size());
1920 for (const std::unique_ptr<T>& t : src) {
1921 result.push_back(t.get());
1922 }
1923 return result;
1924 }
1925
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001926 std::string GetMultiImageBootClassPath() {
1927 DCHECK(IsBootImage());
1928 DCHECK_GT(oat_filenames_.size(), 1u);
1929 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1930 // too, but need to strip all path components (they will be re-established when loading).
1931 std::ostringstream bootcp_oss;
1932 bool first_bootcp = true;
1933 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1934 if (!first_bootcp) {
1935 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001936 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001937
1938 std::string dex_loc = dex_locations_[i];
1939 std::string image_filename = image_filenames_[i];
1940
1941 // Use the dex_loc path, but the image_filename name (without path elements).
1942 size_t dex_last_slash = dex_loc.rfind('/');
1943
1944 // npos is max(size_t). That makes this a bit ugly.
1945 size_t image_last_slash = image_filename.rfind('/');
1946 size_t image_last_at = image_filename.rfind('@');
1947 size_t image_last_sep = (image_last_slash == std::string::npos)
1948 ? image_last_at
1949 : (image_last_at == std::string::npos)
1950 ? std::string::npos
1951 : std::max(image_last_slash, image_last_at);
1952 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1953
1954 if (dex_last_slash == std::string::npos) {
1955 dex_loc = image_filename.substr(image_last_sep + 1);
1956 } else {
1957 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1958 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001959 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001960
1961 // Image filenames already end with .art, no need to replace.
1962
1963 bootcp_oss << dex_loc;
1964 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001965 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001966 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001967 }
1968
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001969 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1970 // This function is used only for apps and for an app we have exactly one oat file.
1971 DCHECK(!IsBootImage());
1972 DCHECK_EQ(oat_writers_.size(), 1u);
1973 std::vector<std::string> dex_files_canonical_locations;
1974 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1975 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001976 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001977
Vladimir Marko919f5532016-01-20 19:13:01 +00001978 std::vector<std::string> parsed;
1979 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001980 auto kept_it = std::remove_if(parsed.begin(),
1981 parsed.end(),
1982 [dex_files_canonical_locations](const std::string& location) {
1983 return ContainsElement(dex_files_canonical_locations,
1984 DexFile::GetDexCanonicalLocation(location.c_str()));
1985 });
1986 parsed.erase(kept_it, parsed.end());
1987 return parsed;
1988 }
1989
Jeff Haofbeb1322016-04-26 14:27:31 -07001990 // Opens requested class path files and appends them to opened_dex_files. If the dex files have
1991 // been stripped, this opens them from their oat files and appends them to opened_oat_files.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001992 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
Jeff Haof0192c82016-03-28 20:39:50 -07001993 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files,
Jeff Haofbeb1322016-04-26 14:27:31 -07001994 std::vector<std::unique_ptr<OatFile>>* opened_oat_files,
Jeff Haof0192c82016-03-28 20:39:50 -07001995 InstructionSet isa) {
Jeff Haofbeb1322016-04-26 14:27:31 -07001996 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles dex out-param is nullptr";
1997 DCHECK(opened_oat_files != nullptr) << "OpenClassPathFiles oat out-param is nullptr";
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001998 for (const std::string& location : class_path_locations) {
Jeff Haof0192c82016-03-28 20:39:50 -07001999 // Stop early if we detect the special shared library, which may be passed as the classpath
2000 // for dex2oat when we want to skip the shared libraries check.
2001 if (location == OatFile::kSpecialSharedLibrary) {
2002 break;
2003 }
Aart Bik37d6a3b2016-06-21 18:30:10 -07002004 static constexpr bool kVerifyChecksum = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002005 std::string error_msg;
Aart Bik37d6a3b2016-06-21 18:30:10 -07002006 if (!DexFile::Open(
2007 location.c_str(), location.c_str(), kVerifyChecksum, &error_msg, opened_dex_files)) {
Jeff Haof0192c82016-03-28 20:39:50 -07002008 // If we fail to open the dex file because it's been stripped, try to open the dex file
2009 // from its corresponding oat file.
2010 OatFileAssistant oat_file_assistant(location.c_str(), isa, false, false);
2011 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
2012 if (oat_file == nullptr) {
2013 LOG(WARNING) << "Failed to open dex file and associated oat file for '" << location
2014 << "': " << error_msg;
2015 } else {
2016 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
2017 oat_file_assistant.LoadDexFiles(*oat_file, location.c_str());
Jeff Haofbeb1322016-04-26 14:27:31 -07002018 opened_oat_files->push_back(std::move(oat_file));
Jeff Haof0192c82016-03-28 20:39:50 -07002019 opened_dex_files->insert(opened_dex_files->end(),
2020 std::make_move_iterator(oat_dex_files.begin()),
2021 std::make_move_iterator(oat_dex_files.end()));
2022 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002023 }
2024 }
2025 }
2026
Vladimir Marko49b0f452015-12-10 13:49:19 +00002027 bool PrepareImageClasses() {
2028 // If --image-classes was specified, calculate the full list of classes to include in the image.
2029 if (image_classes_filename_ != nullptr) {
2030 image_classes_ =
2031 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
2032 if (image_classes_ == nullptr) {
2033 return false;
2034 }
2035 } else if (IsBootImage()) {
2036 image_classes_.reset(new std::unordered_set<std::string>);
2037 }
2038 return true;
2039 }
2040
2041 bool PrepareCompiledClasses() {
2042 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2043 // image.
2044 if (compiled_classes_filename_ != nullptr) {
2045 compiled_classes_ =
2046 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2047 if (compiled_classes_ == nullptr) {
2048 return false;
2049 }
2050 } else {
2051 compiled_classes_.reset(nullptr); // By default compile everything.
2052 }
2053 return true;
2054 }
2055
2056 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2057 const char* classes_filename,
2058 const char* tag) {
2059 std::unique_ptr<std::unordered_set<std::string>> classes;
2060 std::string error_msg;
2061 if (zip_filename != nullptr) {
2062 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2063 } else {
2064 classes.reset(ReadImageClassesFromFile(classes_filename));
2065 }
2066 if (classes == nullptr) {
2067 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2068 << classes_filename << "': " << error_msg;
2069 }
2070 return classes;
2071 }
2072
2073 bool PrepareCompiledMethods() {
2074 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2075 if (compiled_methods_filename_ != nullptr) {
2076 std::string error_msg;
2077 if (compiled_methods_zip_filename_ != nullptr) {
2078 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2079 compiled_methods_filename_,
2080 nullptr, // No post-processing.
2081 &error_msg));
2082 } else {
2083 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2084 nullptr)); // No post-processing.
2085 }
2086 if (compiled_methods_.get() == nullptr) {
2087 LOG(ERROR) << "Failed to create list of compiled methods from '"
2088 << compiled_methods_filename_ << "': " << error_msg;
2089 return false;
2090 }
2091 } else {
2092 compiled_methods_.reset(nullptr); // By default compile everything.
2093 }
2094 return true;
2095 }
2096
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002097 void PruneNonExistentDexFiles() {
2098 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2099 size_t kept = 0u;
2100 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2101 if (!OS::FileExists(dex_filenames_[i])) {
2102 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2103 } else {
2104 dex_filenames_[kept] = dex_filenames_[i];
2105 dex_locations_[kept] = dex_locations_[i];
2106 ++kept;
2107 }
2108 }
2109 dex_filenames_.resize(kept);
2110 dex_locations_.resize(kept);
2111 }
2112
2113 bool AddDexFileSources() {
2114 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2115 if (zip_fd_ != -1) {
2116 DCHECK_EQ(oat_writers_.size(), 1u);
2117 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2118 return false;
2119 }
2120 } else if (oat_writers_.size() > 1u) {
2121 // Multi-image.
2122 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2123 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2124 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2125 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2126 return false;
2127 }
2128 }
2129 } else {
2130 DCHECK_EQ(oat_writers_.size(), 1u);
2131 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2132 DCHECK_NE(dex_filenames_.size(), 0u);
2133 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2134 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2135 return false;
2136 }
2137 }
2138 }
2139 return true;
2140 }
2141
2142 void CreateOatWriters() {
2143 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2144 elf_writers_.reserve(oat_files_.size());
2145 oat_writers_.reserve(oat_files_.size());
2146 for (const std::unique_ptr<File>& oat_file : oat_files_) {
David Srbecky5d811202016-03-08 13:21:22 +00002147 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2148 instruction_set_features_.get(),
2149 compiler_options_.get(),
2150 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002151 elf_writers_.back()->Start();
2152 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2153 }
2154 }
2155
Vladimir Marko49b0f452015-12-10 13:49:19 +00002156 void SaveDexInput() {
2157 for (size_t i = 0; i < dex_files_.size(); ++i) {
2158 const DexFile* dex_file = dex_files_[i];
2159 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2160 getpid(), i));
2161 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2162 if (tmp_file.get() == nullptr) {
2163 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2164 << ". Try: adb shell chmod 777 /data/local/tmp";
2165 continue;
2166 }
2167 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2168 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2169 UNUSED(tmp_file->Flush());
2170 UNUSED(tmp_file->Close());
2171 LOG(INFO) << "Wrote input to " << tmp_file_name;
2172 }
2173 }
2174
2175 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2176 RuntimeOptions raw_options;
2177 if (boot_image_filename_.empty()) {
2178 std::string boot_class_path = "-Xbootclasspath:";
2179 boot_class_path += Join(dex_filenames_, ':');
2180 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2181 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2182 boot_class_path_locations += Join(dex_locations_, ':');
2183 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2184 } else {
2185 std::string boot_image_option = "-Ximage:";
2186 boot_image_option += boot_image_filename_;
2187 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2188 }
2189 for (size_t i = 0; i < runtime_args_.size(); i++) {
2190 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2191 }
2192
2193 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2194 raw_options.push_back(
2195 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2196
2197 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2198 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2199 // have been stripped in preopting, anyways).
2200 if (!IsBootImage()) {
2201 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2202 }
2203 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2204 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2205 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002206 // Disable Hspace compaction to save heap size virtual space.
2207 // Only need disable Hspace for OOM becasue background collector is equal to
2208 // foreground collector by default for dex2oat.
2209 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002210
Andreas Gampeace0dc12016-01-20 13:33:13 -08002211 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2212 // force the free-list implementation for large objects.
2213 if (compiler_options_->IsForceDeterminism()) {
2214 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2215 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2216
2217 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2218 // compaction (done above) and ensure that neither foreground nor background collectors
2219 // are concurrent.
2220 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2221
2222 // To make identity hashcode deterministic, set a known seed.
2223 mirror::Object::SetHashCodeSeed(987654321U);
2224 }
2225
Vladimir Marko49b0f452015-12-10 13:49:19 +00002226 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2227 LOG(ERROR) << "Failed to parse runtime options";
2228 return false;
2229 }
2230 return true;
2231 }
2232
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002233 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002234 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2235 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002236 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002237 LOG(ERROR) << "Failed to create runtime";
2238 return false;
2239 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002240 runtime_.reset(Runtime::Current());
2241 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002242 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2243 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002244 if (!runtime_->HasCalleeSaveMethod(type)) {
2245 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002246 }
2247 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002248 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002249
2250 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2251 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002252 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002253
Vladimir Marko307dac92015-10-20 11:20:09 +01002254 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002255
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002256 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2257 // Runtime::Start, give it away now so that we don't starve GC.
2258 Thread* self = Thread::Current();
2259 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002260
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002261 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002262 }
2263
Jeff Haodcdc85b2015-12-04 14:06:18 -08002264 // 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 -08002265 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002266 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002267 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002268 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002269 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002270 image_filenames_.push_back(app_image_file_name_.c_str());
2271 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002272 if (!image_writer_->Write(app_image_fd_,
2273 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002274 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002275 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002276 return false;
2277 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002278
Jeff Haodcdc85b2015-12-04 14:06:18 -08002279 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002280 dchecked_vector<uintptr_t> oat_data_begins;
2281 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2282 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002283 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002284 // Destroy ImageWriter before doing FixupElf.
2285 image_writer_.reset();
2286
Vladimir Marko944da602016-02-19 12:27:55 +00002287 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2288 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002289 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2290 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2291 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2292 if (oat_file.get() == nullptr) {
2293 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2294 return false;
2295 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002296
Vladimir Marko944da602016-02-19 12:27:55 +00002297 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002298 oat_file->Erase();
2299 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2300 return false;
2301 }
2302
2303 if (oat_file->FlushCloseOrErase()) {
2304 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2305 return false;
2306 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002307 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002308 }
2309
2310 return true;
2311 }
2312
2313 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002314 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2315 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002316 std::function<std::string(const char*)> process = DotToDescriptor;
2317 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002318 }
2319
2320 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002321 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002322 const char* zip_filename,
2323 const char* image_classes_filename,
2324 std::string* error_msg) {
2325 std::function<std::string(const char*)> process = DotToDescriptor;
2326 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2327 }
2328
2329 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2330 // the given function.
2331 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2332 const char* input_filename, std::function<std::string(const char*)>* process) {
2333 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2334 if (input_file.get() == nullptr) {
2335 LOG(ERROR) << "Failed to open input file " << input_filename;
2336 return nullptr;
2337 }
2338 std::unique_ptr<std::unordered_set<std::string>> result(
2339 ReadCommentedInputStream(*input_file, process));
2340 input_file->close();
2341 return result.release();
2342 }
2343
2344 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2345 // Post-process each line with the given function.
2346 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002347 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002348 const char* input_filename,
2349 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002350 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002351 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2352 if (zip_archive.get() == nullptr) {
2353 return nullptr;
2354 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002355 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002356 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002357 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002358 zip_filename, error_msg->c_str());
2359 return nullptr;
2360 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002361 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2362 input_filename,
2363 error_msg));
2364 if (input_file.get() == nullptr) {
2365 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002366 zip_filename, error_msg->c_str());
2367 return nullptr;
2368 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002369 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2370 input_file->Size());
2371 std::istringstream input_stream(input_string);
2372 return ReadCommentedInputStream(input_stream, process);
2373 }
2374
2375 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2376 // with the given function.
2377 static std::unordered_set<std::string>* ReadCommentedInputStream(
2378 std::istream& in_stream,
2379 std::function<std::string(const char*)>* process) {
2380 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2381 new std::unordered_set<std::string>);
2382 while (in_stream.good()) {
2383 std::string dot;
2384 std::getline(in_stream, dot);
2385 if (StartsWith(dot, "#") || dot.empty()) {
2386 continue;
2387 }
2388 if (process != nullptr) {
2389 std::string descriptor((*process)(dot.c_str()));
2390 image_classes->insert(descriptor);
2391 } else {
2392 image_classes->insert(dot);
2393 }
2394 }
2395 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002396 }
2397
Mathieu Chartier49285c52014-12-02 15:43:48 -08002398 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002399 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2400 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002401 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002402 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002403 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002404 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002405 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2406 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002407 }
2408
Jeff Haodcdc85b2015-12-04 14:06:18 -08002409 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2410 std::string res(image_filename);
2411 size_t last_slash = res.rfind('/');
2412 if (last_slash == std::string::npos || last_slash == 0) {
2413 return res;
2414 }
2415 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2416 if (penultimate_slash == std::string::npos) {
2417 return res;
2418 }
2419 // Check that the string in-between is the expected one.
2420 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2421 GetInstructionSetString(isa)) {
2422 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2423 return res;
2424 }
2425 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2426 }
2427
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002428 std::unique_ptr<CompilerOptions> compiler_options_;
2429 Compiler::Kind compiler_kind_;
2430
2431 InstructionSet instruction_set_;
2432 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2433
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002434 uint32_t image_file_location_oat_checksum_;
2435 uintptr_t image_file_location_oat_data_begin_;
2436 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002437 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2438
Vladimir Marko307dac92015-10-20 11:20:09 +01002439 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002440
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002441 DexFileToMethodInlinerMap method_inliner_map_;
2442 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2443
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002444 std::unique_ptr<Runtime> runtime_;
2445
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002446 // Ownership for the class path files.
2447 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2448
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002449 size_t thread_count_;
2450 uint64_t start_ns_;
2451 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002452 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002453 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002454 std::vector<const char*> oat_filenames_;
2455 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002456 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002457 std::vector<const char*> dex_filenames_;
2458 std::vector<const char*> dex_locations_;
2459 int zip_fd_;
2460 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002461 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002462 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002463 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002464 uintptr_t image_base_;
2465 const char* image_classes_zip_filename_;
2466 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002467 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002468 const char* compiled_classes_zip_filename_;
2469 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002470 const char* compiled_methods_zip_filename_;
2471 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002472 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2473 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002474 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002475 bool app_image_;
2476 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002477 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002478 bool is_host_;
2479 std::string android_root_;
Mathieu Chartier0b490842016-05-25 15:05:59 -07002480 // Dex files we are compiling, does not include the class path dex files.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002481 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002482 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002483 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002484 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002485
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002486 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2487 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2488 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002489 std::unique_ptr<ImageWriter> image_writer_;
2490 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002491
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002492 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
Jeff Haofbeb1322016-04-26 14:27:31 -07002493 std::vector<std::unique_ptr<OatFile>> opened_oat_files_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002494 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2495
Vladimir Marko47496c22016-01-27 16:15:08 +00002496 std::vector<const DexFile*> no_inline_from_dex_files_;
2497
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002498 std::vector<std::string> verbose_methods_;
2499 bool dump_stats_;
2500 bool dump_passes_;
2501 bool dump_timing_;
2502 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002503 std::string swap_file_name_;
2504 int swap_fd_;
Andreas Gampee1459ae2016-06-29 09:36:30 -07002505 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap;
2506 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002507 std::string app_image_file_name_;
2508 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002509 std::string profile_file_;
2510 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002511 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002512 TimingLogger* timings_;
2513 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002514 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002515 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002516
2517 // Backing storage.
2518 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002519
Andreas Gampeace0dc12016-01-20 13:33:13 -08002520 // See CompilerOptions.force_determinism_.
2521 bool force_determinism_;
2522
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002523 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2524};
2525
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002526static void b13564922() {
2527#if defined(__linux__) && defined(__arm__)
2528 int major, minor;
2529 struct utsname uts;
2530 if (uname(&uts) != -1 &&
2531 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2532 ((major < 3) || ((major == 3) && (minor < 4)))) {
2533 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2534 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2535 int old_personality = personality(0xffffffff);
2536 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2537 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2538 if (new_personality == -1) {
2539 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2540 }
2541 }
2542 }
2543#endif
2544}
2545
Andreas Gampe10e477d2014-11-19 12:57:42 -08002546static int CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002547 dex2oat.LoadClassProfileDescriptors();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002548 dex2oat.Compile();
2549
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002550 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002551 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002552 return EXIT_FAILURE;
2553 }
2554
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002555 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2556 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2557 // image writer will require this fd to generate the image.
2558 if (dex2oat.ShouldKeepOatFileOpen()) {
2559 if (!dex2oat.FlushOatFiles()) {
2560 return EXIT_FAILURE;
2561 }
2562 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002563 return EXIT_FAILURE;
2564 }
2565
Jeff Haodcdc85b2015-12-04 14:06:18 -08002566 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002567 if (!dex2oat.HandleImage()) {
2568 return EXIT_FAILURE;
2569 }
2570
2571 // When given --host, finish early without stripping.
2572 if (dex2oat.IsHost()) {
2573 dex2oat.DumpTiming();
2574 return EXIT_SUCCESS;
2575 }
2576
Jeff Haodcdc85b2015-12-04 14:06:18 -08002577 // Copy stripped to unstripped location, if necessary.
2578 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002579 return EXIT_FAILURE;
2580 }
2581
Jeff Haodcdc85b2015-12-04 14:06:18 -08002582 // FlushClose again, as stripping might have re-opened the oat files.
2583 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002584 return EXIT_FAILURE;
2585 }
2586
2587 dex2oat.DumpTiming();
2588 return EXIT_SUCCESS;
2589}
2590
2591static int CompileApp(Dex2Oat& dex2oat) {
2592 dex2oat.Compile();
2593
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002594 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002595 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002596 return EXIT_FAILURE;
2597 }
2598
Jeff Haodcdc85b2015-12-04 14:06:18 -08002599 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002600 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002601
2602 // When given --host, finish early without stripping.
2603 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002604 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002605 return EXIT_FAILURE;
2606 }
2607
2608 dex2oat.DumpTiming();
2609 return EXIT_SUCCESS;
2610 }
2611
Jeff Haodcdc85b2015-12-04 14:06:18 -08002612 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2613 // stripped versions. If this is given, we expect to be able to open writable files by name.
2614 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002615 return EXIT_FAILURE;
2616 }
2617
Jeff Haodcdc85b2015-12-04 14:06:18 -08002618 // Flush and close the files.
2619 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002620 return EXIT_FAILURE;
2621 }
2622
2623 dex2oat.DumpTiming();
2624 return EXIT_SUCCESS;
2625}
2626
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002627static int dex2oat(int argc, char** argv) {
2628 b13564922();
2629
2630 TimingLogger timings("compiler", false, false);
2631
Roland Levillain5c7e2602016-02-23 18:08:53 +00002632 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2633 // might produce a stack frame too large for this function or for
2634 // functions inlining it (such as main), that would not fit the
2635 // requirements of the `-Wframe-larger-than` option.
2636 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002637
2638 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002639 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002640
Calin Juravleb077e152016-02-18 18:47:37 +00002641 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02002642 // This operation involves I/O.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002643 if (dex2oat->UseProfileGuidedCompilation()) {
Calin Juravleb077e152016-02-18 18:47:37 +00002644 if (!dex2oat->LoadProfile()) {
2645 LOG(ERROR) << "Failed to process profile file";
Calin Juravle998c2162015-12-21 15:39:33 +02002646 return EXIT_FAILURE;
2647 }
2648 }
2649
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002650 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00002651 if (!dex2oat->OpenFile()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002652 return EXIT_FAILURE;
2653 }
2654
Andreas Gampe046c7062015-05-18 23:22:54 -07002655 // Print the complete line when any of the following is true:
2656 // 1) Debug build
2657 // 2) Compiling an image
2658 // 3) Compiling with --host
2659 // 4) Compiling on the host (not a target build)
2660 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002661 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002662 LOG(INFO) << CommandLine();
2663 } else {
2664 LOG(INFO) << StrippedCommandLine();
2665 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002666
Roland Levillain5c7e2602016-02-23 18:08:53 +00002667 if (!dex2oat->Setup()) {
2668 dex2oat->EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002669 return EXIT_FAILURE;
2670 }
2671
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002672 bool result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00002673 if (dex2oat->IsImage()) {
2674 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002675 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00002676 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002677 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002678
Roland Levillain5c7e2602016-02-23 18:08:53 +00002679 dex2oat->Shutdown();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002680 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002681}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002682} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002683
2684int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002685 int result = art::dex2oat(argc, argv);
2686 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2687 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2688 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002689 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002690 exit(result);
2691 }
2692 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002693}