blob: 370583e3bad4b63c2c09b36677e2384dda748bb2 [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
Brian Carlstrom6449c622014-02-10 23:48:36 -080084static int original_argc;
85static char** original_argv;
86
87static std::string CommandLine() {
88 std::vector<std::string> command;
89 for (int i = 0; i < original_argc; ++i) {
90 command.push_back(original_argv[i]);
91 }
92 return Join(command, ' ');
93}
94
Andreas Gampe046c7062015-05-18 23:22:54 -070095// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
96// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
97// locations are all staged).
98static std::string StrippedCommandLine() {
99 std::vector<std::string> command;
100
101 // Do a pre-pass to look for zip-fd.
102 bool saw_zip_fd = false;
103 for (int i = 0; i < original_argc; ++i) {
104 if (StartsWith(original_argv[i], "--zip-fd=")) {
105 saw_zip_fd = true;
106 break;
107 }
108 }
109
110 // Now filter out things.
111 for (int i = 0; i < original_argc; ++i) {
112 // All runtime-arg parameters are dropped.
113 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
114 i++; // Drop the next part, too.
115 continue;
116 }
117
118 // Any instruction-setXXX is dropped.
119 if (StartsWith(original_argv[i], "--instruction-set")) {
120 continue;
121 }
122
123 // The boot image is dropped.
124 if (StartsWith(original_argv[i], "--boot-image=")) {
125 continue;
126 }
127
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800128 // The image format is dropped.
129 if (StartsWith(original_argv[i], "--image-format=")) {
130 continue;
131 }
132
Andreas Gampe046c7062015-05-18 23:22:54 -0700133 // This should leave any dex-file and oat-file options, describing what we compiled.
134
135 // However, we prefer to drop this when we saw --zip-fd.
136 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700137 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700138 if (StartsWith(original_argv[i], "--zip-") ||
139 StartsWith(original_argv[i], "--dex-") ||
140 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700141 StartsWith(original_argv[i], "--swap-") ||
142 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700143 continue;
144 }
145 }
146
147 command.push_back(original_argv[i]);
148 }
149
150 // Construct the final output.
151 if (command.size() <= 1U) {
152 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
153 return "Starting dex2oat.";
154 }
155 return Join(command, ' ');
156}
157
Brian Carlstrom7940e442013-07-12 13:46:57 -0700158static void UsageErrorV(const char* fmt, va_list ap) {
159 std::string error;
160 StringAppendV(&error, fmt, ap);
161 LOG(ERROR) << error;
162}
163
164static void UsageError(const char* fmt, ...) {
165 va_list ap;
166 va_start(ap, fmt);
167 UsageErrorV(fmt, ap);
168 va_end(ap);
169}
170
Andreas Gampe794ad762015-02-23 08:12:24 -0800171NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 va_list ap;
173 va_start(ap, fmt);
174 UsageErrorV(fmt, ap);
175 va_end(ap);
176
Brian Carlstrom6449c622014-02-10 23:48:36 -0800177 UsageError("Command: %s", CommandLine().c_str());
178
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 UsageError("Usage: dex2oat [options]...");
180 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100181 UsageError(" -j<number>: specifies the number of threads used for compilation.");
182 UsageError(" Default is the number of detected hardware threads available on the");
183 UsageError(" host system.");
184 UsageError(" Example: -j12");
185 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700186 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700187 UsageError(" Example: --dex-file=/system/framework/core.jar");
188 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700189 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
190 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
191 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
192 UsageError(" --dex-location=/system/framework/core.jar");
193 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
195 UsageError(" containing a classes.dex file to compile.");
196 UsageError(" Example: --zip-fd=5");
197 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700198 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
199 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
201 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800202 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError(" Example: --oat-file=/system/framework/boot.oat");
204 UsageError("");
205 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900206 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700207 UsageError("");
208 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
209 UsageError(" to the file descriptor specified by --oat-fd.");
210 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
211 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
214 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 UsageError(" Example: --image=/system/framework/boot.art");
217 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800218 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 UsageError(" Which format to store the image.");
220 UsageError(" Example: --image-format=lz4");
221 UsageError(" Default: uncompressed");
222 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700223 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
224 UsageError(" Example: --image=frameworks/base/preloaded-classes");
225 UsageError("");
226 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
227 UsageError(" Example: --base=0x50000000");
228 UsageError("");
229 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000230 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000232 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000233 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError("");
235 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
236 UsageError(" Example: --android-root=out/host/linux-x86");
237 UsageError(" Default: $ANDROID_ROOT");
238 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800239 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700240 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 UsageError(" Example: --instruction-set=x86");
242 UsageError(" Default: arm");
243 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700244 UsageError(" --instruction-set-features=...,: Specify instruction set features");
245 UsageError(" Example: --instruction-set-features=div");
246 UsageError(" Default: default");
247 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700248 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
249 UsageError(" Default: disabled");
250 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800251 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800253 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100254 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100256 UsageError(" --compiler-filter="
257 "(verify-none"
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700258 "|verify-at-runtime"
Mathieu Chartiera8077802016-03-16 19:08:31 -0700259 "|verify-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100260 "|interpret-only"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000261 "|time"
262 "|space-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100263 "|space"
264 "|balanced"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000265 "|speed-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100266 "|speed"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000267 "|everything-profile"
268 "|everything):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700269 UsageError(" select compiler filter.");
Mathieu Chartiera8077802016-03-16 19:08:31 -0700270 UsageError(" verify-profile requires a --profile(-fd) to also be passed in.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800271 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800272 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800273 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800274 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
275 UsageError(" method for compiler filter tuning.");
276 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
278 UsageError("");
279 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
280 UsageError(" method for compiler filter tuning.");
281 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
282 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
283 UsageError("");
284 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
285 UsageError(" method for compiler filter tuning.");
286 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
287 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
288 UsageError("");
289 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
290 UsageError(" method for compiler filter tuning.");
291 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
292 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
293 UsageError("");
294 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
295 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700296 UsageError(" and the filter is not interpret-only or verify-none or verify-at-runtime, ");
297 UsageError(" overrides the filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800298 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
299 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
300 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100301 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
302 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100303 UsageError(" Has priority over the --compiler-filter option. Intended for ");
304 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100305 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
306 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
307 UsageError("");
308 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
309 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100310 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
311 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100312 UsageError(" Example: --inline-max-code-units=%d",
313 CompilerOptions::kDefaultInlineMaxCodeUnits);
314 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
315 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700316 UsageError(" --dump-timing: display a breakdown of where time was spent");
317 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700318 UsageError(" --include-patch-information: Include patching information so the generated code");
319 UsageError(" can have its base address moved without full recompilation.");
320 UsageError("");
321 UsageError(" --no-include-patch-information: Do not include patching information.");
322 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100323 UsageError(" -g");
324 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
325 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky346dc992016-03-13 22:00:07 +0000326 UsageError(" If used without --debuggable, it will be best-effort only.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000327 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700328 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100329 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100330 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000331 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
332 UsageError(" debug information necessary to print backtraces. (disabled by default)");
333 UsageError("");
David Srbecky346dc992016-03-13 22:00:07 +0000334 UsageError(" --no-generate-mini-debug-info: Do not generate backtrace info.");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000335 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000336 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000337 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
339 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
340 UsageError(" Use a separate --runtime-arg switch for each argument.");
341 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700342 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000343 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000345 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
346 UsageError(" Cannot be used together with --profile-file.");
347 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800348 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
349 UsageError(" Example: --swap-file=/data/tmp/swap.001");
350 UsageError("");
351 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
352 UsageError(" Example: --swap-fd=10");
353 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700354 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
355 UsageError(" Example: --app-image-fd=10");
356 UsageError("");
357 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
358 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
359 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800360 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
361 "input dex file.");
362 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000363 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
364 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
365 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
366 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367 std::cerr << "See log for usage error information\n";
368 exit(EXIT_FAILURE);
369}
370
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371// The primary goal of the watchdog is to prevent stuck build servers
372// during development when fatal aborts lead to a cascade of failures
373// that result in a deadlock.
374class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800375// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376#undef CHECK_PTHREAD_CALL
377#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
378 do { \
379 int rc = call args; \
380 if (rc != 0) { \
381 errno = rc; \
382 std::string message(# call); \
383 message += " failed for "; \
384 message += reason; \
385 Fatal(message); \
386 } \
387 } while (false)
388
389 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700390 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700391 is_watch_dog_enabled_ = is_watch_dog_enabled;
392 if (!is_watch_dog_enabled_) {
393 return;
394 }
395 shutting_down_ = false;
396 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700397 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
398 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
400 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
401 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
402 }
403 ~WatchDog() {
404 if (!is_watch_dog_enabled_) {
405 return;
406 }
407 const char* reason = "dex2oat watch dog thread shutdown";
408 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
409 shutting_down_ = true;
410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
412
Kenny Root51316382014-05-13 14:59:37 -0700413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414
415 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
416 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
417 }
418
419 private:
420 static void* CallBack(void* arg) {
421 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
422 ::art::SetThreadName("dex2oat watch dog");
423 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700424 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 }
426
Andreas Gampe794ad762015-02-23 08:12:24 -0800427 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700428 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
429 // it's rather easy to hang in unwinding.
430 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
431 // logcat logging or stderr output.
432 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433 exit(1);
434 }
435
436 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
438 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700439 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 timespec timeout_ts;
441 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
442 const char* reason = "dex2oat watch dog thread waiting";
443 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
444 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800445 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700447 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
448 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449 } else if (rc != 0) {
450 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
451 strerror(errno)));
452 Fatal(message.c_str());
453 }
454 }
455 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
456 }
457
458 // 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 -0700459 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700460 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800461
Andreas Gampe540138a2015-09-14 15:34:38 -0700462 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
463 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
464 // itself before that watchdog would take down the system server.
465 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466
467 bool is_watch_dog_enabled_;
468 bool shutting_down_;
469 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
470 pthread_mutex_t mutex_;
471 pthread_cond_t cond_;
472 pthread_attr_t attr_;
473 pthread_t pthread_;
474};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800476static constexpr size_t kMinDexFilesForSwap = 2;
477static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
478
479static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
480 if (is_image) {
481 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
482 return false;
483 }
484 if (dex_files.size() < kMinDexFilesForSwap) {
485 // If there are less dex files than the threshold, assume it's gonna be fine.
486 return false;
487 }
488 size_t dex_files_size = 0;
489 for (const auto* dex_file : dex_files) {
490 dex_files_size += dex_file->GetHeader().file_size_;
491 }
492 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
493}
494
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800495class Dex2Oat FINAL {
496 public:
497 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100498 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800499 instruction_set_(kRuntimeISA),
500 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 image_file_location_oat_checksum_(0),
502 image_file_location_oat_data_begin_(0),
503 image_patch_delta_(0),
504 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700505 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 method_inliner_map_(),
507 runtime_(nullptr),
508 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
509 start_ns_(NanoTime()),
510 oat_fd_(-1),
511 zip_fd_(-1),
512 image_base_(0U),
513 image_classes_zip_filename_(nullptr),
514 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800515 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800516 compiled_classes_zip_filename_(nullptr),
517 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700518 compiled_methods_zip_filename_(nullptr),
519 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700520 app_image_(false),
521 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800522 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800523 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 class_loader_(nullptr),
525 elf_writers_(),
526 oat_writers_(),
527 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000528 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700529 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 opened_dex_files_maps_(),
531 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000532 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800533 dump_stats_(false),
534 dump_passes_(false),
535 dump_timing_(false),
536 dump_slow_timing_(kIsDebugBuild),
Calin Juravle2e2db782016-02-23 12:00:03 +0000537 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800538 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000539 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800540 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000541 force_determinism_(false)
542 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800543
544 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800545 // Log completion time before deleting the runtime_, because this accesses
546 // the runtime.
547 LogCompletionTime();
548
Vladimir Marko307dac92015-10-20 11:20:09 +0100549 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
550 // We want to just exit on non-debug builds, not bringing the runtime down
551 // in an orderly fashion. So release the following fields.
552 driver_.release();
553 image_writer_.release();
554 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
555 dex_file.release();
556 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
558 map.release();
559 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800560 for (std::unique_ptr<File>& oat_file : oat_files_) {
561 oat_file.release();
562 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100563 runtime_.release();
564 verification_results_.release();
565 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100566 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700567 }
568
Roland Levillain9ec5e222015-08-17 20:18:41 +0100569 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800570 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800571 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800572 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000573 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800574 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100575 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800576
Roland Levillain9ec5e222015-08-17 20:18:41 +0100577 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000578 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100579 }
580
581 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000582 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100583 }
584
Calin Juravle877fd962016-01-05 14:29:29 +0000585 void ParseFdForCollection(const StringPiece& option,
586 const char* arg_name,
587 std::vector<uint32_t>* fds) {
588 uint32_t fd;
589 ParseUintOption(option, arg_name, &fd, Usage);
590 fds->push_back(fd);
591 }
592
Roland Levillain9ec5e222015-08-17 20:18:41 +0100593 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000594 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100595 }
596
597 void ParseBase(const StringPiece& option) {
598 DCHECK(option.starts_with("--base="));
599 const char* image_base_str = option.substr(strlen("--base=")).data();
600 char* end;
601 image_base_ = strtoul(image_base_str, &end, 16);
602 if (end == image_base_str || *end != '\0') {
603 Usage("Failed to parse hexadecimal value for option %s", option.data());
604 }
605 }
606
607 void ParseInstructionSet(const StringPiece& option) {
608 DCHECK(option.starts_with("--instruction-set="));
609 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
610 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
611 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
612 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
613 buf.get()[instruction_set_str.length()] = 0;
614 instruction_set_ = GetInstructionSetFromString(buf.get());
615 // arm actually means thumb2.
616 if (instruction_set_ == InstructionSet::kArm) {
617 instruction_set_ = InstructionSet::kThumb2;
618 }
619 }
620
621 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
622 DCHECK(option.starts_with("--instruction-set-variant="));
623 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
624 instruction_set_features_.reset(
625 InstructionSetFeatures::FromVariant(
626 instruction_set_, str.as_string(), &parser_options->error_msg));
627 if (instruction_set_features_.get() == nullptr) {
628 Usage("%s", parser_options->error_msg.c_str());
629 }
630 }
631
632 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
633 DCHECK(option.starts_with("--instruction-set-features="));
634 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
635 if (instruction_set_features_.get() == nullptr) {
636 instruction_set_features_.reset(
637 InstructionSetFeatures::FromVariant(
638 instruction_set_, "default", &parser_options->error_msg));
639 if (instruction_set_features_.get() == nullptr) {
640 Usage("Problem initializing default instruction set features variant: %s",
641 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800643 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100644 instruction_set_features_.reset(
645 instruction_set_features_->AddFeaturesFromString(str.as_string(),
646 &parser_options->error_msg));
647 if (instruction_set_features_.get() == nullptr) {
648 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
649 }
650 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800651
Roland Levillain9ec5e222015-08-17 20:18:41 +0100652 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
653 DCHECK(option.starts_with("--compiler-backend="));
654 parser_options->requested_specific_compiler = true;
655 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
656 if (backend_str == "Quick") {
657 compiler_kind_ = Compiler::kQuick;
658 } else if (backend_str == "Optimizing") {
659 compiler_kind_ = Compiler::kOptimizing;
660 } else {
661 Usage("Unknown compiler backend: %s", backend_str.data());
662 }
663 }
664
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800665 void ParseImageFormat(const StringPiece& option) {
666 const StringPiece substr("--image-format=");
667 DCHECK(option.starts_with(substr));
668 const StringPiece format_str = option.substr(substr.length());
669 if (format_str == "lz4") {
670 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800671 } else if (format_str == "lz4hc") {
672 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800673 } else if (format_str == "uncompressed") {
674 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
675 } else {
676 Usage("Unknown image format: %s", format_str.data());
677 }
678 }
679
Jeff Hao436183f2016-01-12 16:36:50 -0800680 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800681 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700682 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
683
684 if (IsAppImage() && IsBootImage()) {
685 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
686 }
687
Nicolas Geoffray0c6e3342016-03-04 11:38:14 +0000688 if (IsBootImage()) {
689 // We need the boot image to always be debuggable.
690 // TODO: Remove this once we better deal with full frame deoptimization.
691 compiler_options_->debuggable_ = true;
692 }
693
Jeff Haodcdc85b2015-12-04 14:06:18 -0800694 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800695 Usage("Output must be supplied with either --oat-file or --oat-fd");
696 }
697
Jeff Haodcdc85b2015-12-04 14:06:18 -0800698 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800699 Usage("--oat-file should not be used with --oat-fd");
700 }
701
Roland Levillain9ec5e222015-08-17 20:18:41 +0100702 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800703 Usage("--oat-symbols should not be used with --oat-fd");
704 }
705
Roland Levillain9ec5e222015-08-17 20:18:41 +0100706 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800707 Usage("--oat-symbols should not be used with --host");
708 }
709
Jeff Haodcdc85b2015-12-04 14:06:18 -0800710 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 Usage("--oat-fd should not be used with --image");
712 }
713
Jeff Haodcdc85b2015-12-04 14:06:18 -0800714 if (!parser_options->oat_symbols.empty() &&
715 parser_options->oat_symbols.size() != oat_filenames_.size()) {
716 Usage("--oat-file arguments do not match --oat-symbols arguments");
717 }
718
719 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
720 Usage("--oat-file arguments do not match --image arguments");
721 }
722
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 if (android_root_.empty()) {
724 const char* android_root_env_var = getenv("ANDROID_ROOT");
725 if (android_root_env_var == nullptr) {
726 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 android_root_ += android_root_env_var;
729 }
730
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700731 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100732 parser_options->boot_image_filename += android_root_;
733 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100735 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000736 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800737 }
738
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700739 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800740 Usage("--image-classes should only be used with --image");
741 }
742
Vladimir Marko49b0f452015-12-10 13:49:19 +0000743 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800744 Usage("--image-classes should not be used with --boot-image");
745 }
746
747 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
748 Usage("--image-classes-zip should be used with --image-classes");
749 }
750
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700751 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800752 Usage("--compiled-classes should only be used with --image");
753 }
754
Vladimir Marko49b0f452015-12-10 13:49:19 +0000755 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800756 Usage("--compiled-classes should not be used with --boot-image");
757 }
758
759 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
760 Usage("--compiled-classes-zip should be used with --compiled-classes");
761 }
762
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800763 if (dex_filenames_.empty() && zip_fd_ == -1) {
764 Usage("Input must be supplied with either --dex-file or --zip-fd");
765 }
766
767 if (!dex_filenames_.empty() && zip_fd_ != -1) {
768 Usage("--dex-file should not be used with --zip-fd");
769 }
770
771 if (!dex_filenames_.empty() && !zip_location_.empty()) {
772 Usage("--dex-file should not be used with --zip-location");
773 }
774
775 if (dex_locations_.empty()) {
776 for (const char* dex_file_name : dex_filenames_) {
777 dex_locations_.push_back(dex_file_name);
778 }
779 } else if (dex_locations_.size() != dex_filenames_.size()) {
780 Usage("--dex-location arguments do not match --dex-file arguments");
781 }
782
Jeff Haodcdc85b2015-12-04 14:06:18 -0800783 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
784 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
785 Usage("--oat-file arguments must be singular or match --dex-file arguments");
786 }
787 }
788
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800789 if (zip_fd_ != -1 && zip_location_.empty()) {
790 Usage("--zip-location should be supplied with --zip-fd");
791 }
792
Vladimir Marko49b0f452015-12-10 13:49:19 +0000793 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800794 if (image_base_ == 0) {
795 Usage("Non-zero --base not specified");
796 }
797 }
798
Mathieu Chartiera8077802016-03-16 19:08:31 -0700799 const bool have_profile_file = !profile_file_.empty();
800 const bool have_profile_fd = profile_file_fd_ != kInvalidFd;
801 if (have_profile_file && have_profile_fd) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000802 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200803 }
804
Roland Levillain9ec5e222015-08-17 20:18:41 +0100805 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800806 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 }
808
809 // If no instruction set feature was given, use the default one for the target
810 // instruction set.
811 if (instruction_set_features_.get() == nullptr) {
812 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100813 InstructionSetFeatures::FromVariant(
814 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800815 if (instruction_set_features_.get() == nullptr) {
816 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100817 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800818 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800819 }
820
821 if (instruction_set_ == kRuntimeISA) {
822 std::unique_ptr<const InstructionSetFeatures> runtime_features(
823 InstructionSetFeatures::FromCppDefines());
824 if (!instruction_set_features_->Equals(runtime_features.get())) {
825 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
826 << *instruction_set_features_ << ") and those of dex2oat executable ("
827 << *runtime_features <<") for the command line:\n"
828 << CommandLine();
829 }
830 }
831
Roland Levillaina215b952015-08-07 11:38:32 +0100832 // It they are not set, use default values for inlining settings.
833 // TODO: We should rethink the compiler filter. We mostly save
834 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000835 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
836 compiler_options_->inline_depth_limit_ =
Andreas Gampe29d38e72016-03-23 15:31:51 +0000837 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100838 // Implementation of the space filter: limit inlining depth.
839 ? CompilerOptions::kSpaceFilterInlineDepthLimit
840 : CompilerOptions::kDefaultInlineDepthLimit;
841 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000842 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
843 compiler_options_->inline_max_code_units_ =
Andreas Gampe29d38e72016-03-23 15:31:51 +0000844 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100845 // Implementation of the space filter: limit inlining max code units.
846 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
847 : CompilerOptions::kDefaultInlineMaxCodeUnits;
848 }
849
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800850 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800851 // Set the compilation target's implicit checks options.
852 switch (instruction_set_) {
853 case kArm:
854 case kThumb2:
855 case kArm64:
856 case kX86:
857 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700858 case kMips:
859 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000860 compiler_options_->implicit_null_checks_ = true;
861 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800862 break;
863
864 default:
865 // Defaults are correct.
866 break;
867 }
868
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000869 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800870
Jeff Hao436183f2016-01-12 16:36:50 -0800871 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800872 Usage("--multi-image can only be used when creating boot images");
873 }
Jeff Hao436183f2016-01-12 16:36:50 -0800874 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800875 Usage("--multi-image cannot be used with multiple image names");
876 }
877
878 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
879 if (!kIsTargetBuild && IsBootImage()) {
880 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800881 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800882 }
883 }
884
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800885 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100886 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800887 watchdog_.reset(new WatchDog(true));
888 }
889
890 // Fill some values into the key-value store for the oat header.
891 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800892
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800893 // Automatically force determinism for the boot image in a host build if the default GC is CMS
894 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
895 // one by passing the option `-Xgc:nonconcurrent` (see below).
896 if (!kIsTargetBuild && IsBootImage()) {
897 if (SupportsDeterministicCompilation()) {
898 force_determinism_ = true;
899 } else {
900 LOG(WARNING) << "Deterministic compilation is disabled.";
901 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800902 }
903 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100904 }
905
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800906 static bool SupportsDeterministicCompilation() {
907 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
908 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
909 !kEmitCompilerReadBarrier;
910 }
911
Jeff Hao436183f2016-01-12 16:36:50 -0800912 void ExpandOatAndImageFilenames() {
913 std::string base_oat = oat_filenames_[0];
914 size_t last_oat_slash = base_oat.rfind('/');
915 if (last_oat_slash == std::string::npos) {
916 Usage("--multi-image used with unusable oat filename %s", base_oat.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_oat.find('@', last_oat_slash) != std::string::npos) {
921 last_oat_slash = base_oat.rfind('@');
922 }
923 base_oat = base_oat.substr(0, last_oat_slash + 1);
924
925 std::string base_img = image_filenames_[0];
926 size_t last_img_slash = base_img.rfind('/');
927 if (last_img_slash == std::string::npos) {
928 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
929 }
930 // We also need to honor path components that were encoded through '@'. Otherwise the loading
931 // code won't be able to find the images.
932 if (base_img.find('@', last_img_slash) != std::string::npos) {
933 last_img_slash = base_img.rfind('@');
934 }
935
936 // Get the prefix, which is the primary image name (without path components). Strip the
937 // extension.
938 std::string prefix = base_img.substr(last_img_slash + 1);
939 if (prefix.rfind('.') != std::string::npos) {
940 prefix = prefix.substr(0, prefix.rfind('.'));
941 }
942 if (!prefix.empty()) {
943 prefix = prefix + "-";
944 }
945
946 base_img = base_img.substr(0, last_img_slash + 1);
947
948 // Note: we have some special case here for our testing. We have to inject the differentiating
949 // parts for the different core images.
950 std::string infix; // Empty infix by default.
951 {
952 // Check the first name.
953 std::string dex_file = oat_filenames_[0];
954 size_t last_dex_slash = dex_file.rfind('/');
955 if (last_dex_slash != std::string::npos) {
956 dex_file = dex_file.substr(last_dex_slash + 1);
957 }
958 size_t last_dex_dot = dex_file.rfind('.');
959 if (last_dex_dot != std::string::npos) {
960 dex_file = dex_file.substr(0, last_dex_dot);
961 }
962 if (StartsWith(dex_file, "core-")) {
963 infix = dex_file.substr(strlen("core"));
964 }
965 }
966
967 // Now create the other names. Use a counted loop to skip the first one.
968 for (size_t i = 1; i < dex_locations_.size(); ++i) {
969 // TODO: Make everything properly std::string.
970 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
971 char_backing_storage_.push_back(base_img + image_name);
972 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
973
974 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
975 char_backing_storage_.push_back(base_oat + oat_name);
976 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
977 }
978 }
979
Andreas Gampe8994a042015-12-30 19:03:17 +0000980 // Modify the input string in the following way:
981 // 0) Assume input is /a/b/c.d
982 // 1) Strip the path -> c.d
983 // 2) Inject prefix p -> pc.d
984 // 3) Inject infix i -> pci.d
985 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800986 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000987 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800988 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000989 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800990 size_t last_dex_slash = in.rfind('/');
991 if (last_dex_slash != std::string::npos) {
992 in = in.substr(last_dex_slash + 1);
993 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000994 if (!prefix.empty()) {
995 in = prefix + in;
996 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800997 if (!infix.empty()) {
998 // Inject infix.
999 size_t last_dot = in.rfind('.');
1000 if (last_dot != std::string::npos) {
1001 in.insert(last_dot, infix);
1002 }
1003 }
1004 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001005 in = in.substr(0, in.length() - strlen(".jar")) +
1006 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001007 }
1008 return in;
1009 }
1010
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001011 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001012 std::ostringstream oss;
1013 for (int i = 0; i < argc; ++i) {
1014 if (i > 0) {
1015 oss << ' ';
1016 }
1017 oss << argv[i];
1018 }
1019 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1020 oss.str(""); // Reset.
1021 oss << kRuntimeISA;
1022 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1023 key_value_store_->Put(
1024 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001025 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001026 key_value_store_->Put(
1027 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001028 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Srbecky5d950762016-03-07 20:47:29 +00001029 key_value_store_->Put(
1030 OatHeader::kNativeDebuggableKey,
David Srbecky346dc992016-03-13 22:00:07 +00001031 compiler_options_->GetNativeDebuggable() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe29d38e72016-03-23 15:31:51 +00001032 key_value_store_->Put(OatHeader::kCompilerFilter,
1033 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
Richard Uhlerd1537b52016-03-29 13:27:41 -07001034 key_value_store_->Put(OatHeader::kHasPatchInfoKey,
1035 compiler_options_->GetIncludePatchInformation() ? OatHeader::kTrueValue
1036 : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001037 }
1038
1039 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1040 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1041 // returns, arguments have been successfully parsed.
1042 void ParseArgs(int argc, char** argv) {
1043 original_argc = argc;
1044 original_argv = argv;
1045
1046 InitLogging(argv);
1047
1048 // Skip over argv[0].
1049 argv++;
1050 argc--;
1051
1052 if (argc == 0) {
1053 Usage("No arguments specified");
1054 }
1055
1056 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001057 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001058
1059 for (int i = 0; i < argc; i++) {
1060 const StringPiece option(argv[i]);
1061 const bool log_options = false;
1062 if (log_options) {
1063 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1064 }
1065 if (option.starts_with("--dex-file=")) {
1066 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1067 } else if (option.starts_with("--dex-location=")) {
1068 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1069 } else if (option.starts_with("--zip-fd=")) {
1070 ParseZipFd(option);
1071 } else if (option.starts_with("--zip-location=")) {
1072 zip_location_ = option.substr(strlen("--zip-location=")).data();
1073 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001075 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001077 } else if (option.starts_with("--oat-fd=")) {
1078 ParseOatFd(option);
1079 } else if (option == "--watch-dog") {
1080 parser_options->watch_dog_enabled = true;
1081 } else if (option == "--no-watch-dog") {
1082 parser_options->watch_dog_enabled = false;
1083 } else if (option.starts_with("-j")) {
1084 ParseJ(option);
1085 } else if (option.starts_with("--oat-location=")) {
1086 oat_location_ = option.substr(strlen("--oat-location=")).data();
1087 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001088 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001089 } else if (option.starts_with("--image-classes=")) {
1090 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1091 } else if (option.starts_with("--image-classes-zip=")) {
1092 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001093 } else if (option.starts_with("--image-format=")) {
1094 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001095 } else if (option.starts_with("--compiled-classes=")) {
1096 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1097 } else if (option.starts_with("--compiled-classes-zip=")) {
1098 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1099 } else if (option.starts_with("--compiled-methods=")) {
1100 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1101 } else if (option.starts_with("--compiled-methods-zip=")) {
1102 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1103 } else if (option.starts_with("--base=")) {
1104 ParseBase(option);
1105 } else if (option.starts_with("--boot-image=")) {
1106 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1107 } else if (option.starts_with("--android-root=")) {
1108 android_root_ = option.substr(strlen("--android-root=")).data();
1109 } else if (option.starts_with("--instruction-set=")) {
1110 ParseInstructionSet(option);
1111 } else if (option.starts_with("--instruction-set-variant=")) {
1112 ParseInstructionSetVariant(option, parser_options.get());
1113 } else if (option.starts_with("--instruction-set-features=")) {
1114 ParseInstructionSetFeatures(option, parser_options.get());
1115 } else if (option.starts_with("--compiler-backend=")) {
1116 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001117 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001118 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001119 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001120 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001121 } else if (option == "--host") {
1122 is_host_ = true;
1123 } else if (option == "--runtime-arg") {
1124 if (++i >= argc) {
1125 Usage("Missing required argument for --runtime-arg");
1126 }
1127 if (log_options) {
1128 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1129 }
1130 runtime_args_.push_back(argv[i]);
1131 } else if (option == "--dump-timing") {
1132 dump_timing_ = true;
1133 } else if (option == "--dump-passes") {
1134 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001135 } else if (option == "--dump-stats") {
1136 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001137 } else if (option.starts_with("--swap-file=")) {
1138 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1139 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001140 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1141 } else if (option.starts_with("--app-image-file=")) {
1142 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1143 } else if (option.starts_with("--app-image-fd=")) {
1144 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001145 } else if (option.starts_with("--verbose-methods=")) {
1146 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1147 // conditional on having verbost methods.
1148 gLogVerbosity.compiler = false;
1149 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001150 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001151 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001152 } else if (option.starts_with("--no-inline-from=")) {
1153 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001154 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001155 if (!SupportsDeterministicCompilation()) {
1156 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001157 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001158 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001159 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001160 Usage("Unknown argument %s", option.data());
1161 }
1162 }
1163
Jeff Hao436183f2016-01-12 16:36:50 -08001164 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001165
1166 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001167 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168 }
1169
Jeff Haodcdc85b2015-12-04 14:06:18 -08001170 // Check whether the oat output files are writable, and open them for later. Also open a swap
1171 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001173 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1174 PruneNonExistentDexFiles();
1175
Jeff Hao436183f2016-01-12 16:36:50 -08001176 // Expand oat and image filenames for multi image.
1177 if (IsBootImage() && multi_image_) {
1178 ExpandOatAndImageFilenames();
1179 }
1180
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001182 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001183 for (const char* oat_filename : oat_filenames_) {
1184 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1185 if (oat_file.get() == nullptr) {
1186 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1187 return false;
1188 }
1189 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1190 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1191 oat_file->Erase();
1192 return false;
1193 }
1194 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001195 }
1196 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001197 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1198 oat_file->DisableAutoClose();
1199 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001200 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1201 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001202 if (oat_file.get() == nullptr) {
1203 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1204 return false;
1205 }
1206 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1207 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1208 oat_file->Erase();
1209 return false;
1210 }
1211 oat_filenames_.push_back(oat_location_.c_str());
1212 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001213 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001214
1215 // Swap file handling.
1216 //
1217 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1218 // that we can use for swap.
1219 //
1220 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1221 // will immediately unlink to satisfy the swap fd assumption.
1222 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1223 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1224 if (swap_file.get() == nullptr) {
1225 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1226 return false;
1227 }
1228 swap_fd_ = swap_file->Fd();
1229 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1230 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1231 // released immediately.
1232 unlink(swap_file_name_.c_str());
1233 }
Jeff Hao436183f2016-01-12 16:36:50 -08001234
1235 // If we use a swap file, ensure we are above the threshold to make it necessary.
1236 if (swap_fd_ != -1) {
1237 if (!UseSwap(IsBootImage(), dex_files_)) {
1238 close(swap_fd_);
1239 swap_fd_ = -1;
1240 VLOG(compiler) << "Decided to run without swap.";
1241 } else {
1242 LOG(INFO) << "Large app, accepted running with swap.";
1243 }
1244 }
1245 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1246
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001247 return true;
1248 }
1249
Jeff Haodcdc85b2015-12-04 14:06:18 -08001250 void EraseOatFiles() {
1251 for (size_t i = 0; i < oat_files_.size(); ++i) {
1252 DCHECK(oat_files_[i].get() != nullptr);
1253 oat_files_[i]->Erase();
1254 oat_files_[i].reset();
1255 }
Andreas Gampea650e702014-12-03 14:28:02 -08001256 }
1257
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001258 void Shutdown() {
1259 ScopedObjectAccess soa(Thread::Current());
1260 for (jobject dex_cache : dex_caches_) {
1261 soa.Env()->DeleteLocalRef(dex_cache);
1262 }
1263 dex_caches_.clear();
1264 }
1265
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001266 void LoadClassProfileDescriptors() {
1267 if (profile_compilation_info_ != nullptr && app_image_) {
1268 Runtime* runtime = Runtime::Current();
1269 CHECK(runtime != nullptr);
1270 std::set<DexCacheResolvedClasses> resolved_classes(
1271 profile_compilation_info_->GetResolvedClasses());
1272 image_classes_.reset(new std::unordered_set<std::string>(
1273 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes)));
1274 VLOG(compiler) << "Loaded " << image_classes_->size()
1275 << " image class descriptors from profile";
1276 if (VLOG_IS_ON(compiler)) {
1277 for (const std::string& s : *image_classes_) {
1278 LOG(INFO) << "Image class " << s;
1279 }
1280 }
1281 }
1282 }
1283
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001284 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1285 // boot class path.
1286 bool Setup() {
1287 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001288 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001289
1290 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1291 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001293
Vladimir Marko307dac92015-10-20 11:20:09 +01001294 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001295 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001296 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001297 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001298 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001299 CompilerCallbacks::CallbackMode::kCompileBootImage :
1300 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001301
Vladimir Marko49b0f452015-12-10 13:49:19 +00001302 RuntimeArgumentMap runtime_options;
1303 if (!PrepareRuntimeOptions(&runtime_options)) {
1304 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001305 }
1306
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001307 CreateOatWriters();
1308 if (!AddDexFileSources()) {
1309 return false;
1310 }
1311
1312 if (IsBootImage() && image_filenames_.size() > 1) {
1313 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1314 // We need this for the multi-image case.
1315 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1316 }
1317
1318 if (!IsBootImage()) {
1319 // When compiling an app, create the runtime early to retrieve
1320 // the image location key needed for the oat header.
1321 if (!CreateRuntime(std::move(runtime_options))) {
1322 return false;
1323 }
1324
Andreas Gampe29d38e72016-03-23 15:31:51 +00001325 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001326 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1327 std::vector<gc::space::ImageSpace*> image_spaces =
1328 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Jeff Haob11ffb72016-04-07 15:40:54 -07001329 image_file_location_oat_checksum_ = OatFileAssistant::CalculateCombinedImageChecksum();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001330 image_file_location_oat_data_begin_ =
1331 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1332 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1333 // Store the boot image filename(s).
1334 std::vector<std::string> image_filenames;
1335 for (const gc::space::ImageSpace* image_space : image_spaces) {
1336 image_filenames.push_back(image_space->GetImageFilename());
1337 }
1338 std::string image_file_location = Join(image_filenames, ':');
1339 if (!image_file_location.empty()) {
1340 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1341 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001342 } else {
1343 image_file_location_oat_checksum_ = 0u;
1344 image_file_location_oat_data_begin_ = 0u;
1345 image_patch_delta_ = 0;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001346 }
1347
1348 // Open dex files for class path.
1349 const std::vector<std::string> class_path_locations =
1350 GetClassPathLocations(runtime_->GetClassPathString());
1351 OpenClassPathFiles(class_path_locations, &class_path_files_);
1352
1353 // Store the classpath we have right now.
1354 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1355 key_value_store_->Put(OatHeader::kClassPathKey,
1356 OatFile::EncodeDexFileDependencies(class_path_files));
1357 }
1358
1359 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001360 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001361 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1362 rodata_.reserve(oat_writers_.size());
1363 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1364 rodata_.push_back(elf_writers_[i]->StartRoData());
1365 // Unzip or copy dex files straight to the oat file.
1366 std::unique_ptr<MemMap> opened_dex_files_map;
1367 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1368 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1369 oat_files_[i].get(),
1370 instruction_set_,
1371 instruction_set_features_.get(),
1372 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001373 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001374 &opened_dex_files_map,
1375 &opened_dex_files)) {
1376 return false;
1377 }
1378 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1379 if (opened_dex_files_map != nullptr) {
1380 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1381 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001382 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001383 opened_dex_files_.push_back(std::move(dex_file));
1384 }
1385 } else {
1386 DCHECK(opened_dex_files.empty());
1387 }
1388 }
1389 }
1390
1391 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1392 if (IsBootImage()) {
1393 // For boot image, pass opened dex files to the Runtime::Create().
1394 // Note: Runtime acquires ownership of these dex files.
1395 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001396 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001397 return false;
1398 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001399 }
1400
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001401 // If we're doing the image, override the compiler filter to force full compilation. Must be
1402 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1403 // compilation of class initializers.
1404 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001405 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 WellKnownClasses::Init(self->GetJniEnv());
1407
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001408 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001409 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001410 constexpr bool kSaveDexInput = false;
1411 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001412 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001413 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001414
1415 // Handle and ClassLoader creation needs to come after Runtime::Create.
1416 ScopedObjectAccess soa(self);
1417
1418 // Classpath: first the class-path given.
1419 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1420
1421 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1422 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1423
1424 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001425 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001426
1427 // Ensure opened dex files are writable for dex-to-dex transformations.
1428 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1429 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1430 PLOG(ERROR) << "Failed to make .dex files writeable.";
1431 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001432 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001433 }
1434
1435 // Ensure that the dex caches stay live since we don't want class unloading
1436 // to occur during compilation.
1437 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001438 ScopedObjectAccess soa(self);
1439 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001440 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001441 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001442
1443 /*
Mathieu Chartiera8077802016-03-16 19:08:31 -07001444 * If we're not in interpret-only or verify-none or verify-at-runtime or verify-profile mode,
1445 * go ahead and compile small applications. Don't bother to check if we're doing the image.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001446 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001447 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001448 compiler_options_->IsCompilationEnabled() &&
1449 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001450 size_t num_methods = 0;
1451 for (size_t i = 0; i != dex_files_.size(); ++i) {
1452 const DexFile* dex_file = dex_files_[i];
1453 CHECK(dex_file != nullptr);
1454 num_methods += dex_file->NumMethodIds();
1455 }
1456 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
Andreas Gampe29d38e72016-03-23 15:31:51 +00001457 compiler_options_->SetCompilerFilter(CompilerFilter::kSpeed);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001458 VLOG(compiler) << "Below method threshold, compiling anyways";
1459 }
1460 }
1461
1462 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001463 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001464
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001465 // If we need to keep the oat file open for the image writer.
1466 bool ShouldKeepOatFileOpen() const {
1467 return IsImage() && oat_fd_ != kInvalidFd;
1468 }
1469
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001470 // Create and invoke the compiler driver. This will compile all the dex files.
1471 void Compile() {
1472 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1473 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001474
Vladimir Marko47496c22016-01-27 16:15:08 +00001475 // Find the dex files we should not inline from.
1476
1477 std::vector<std::string> no_inline_filters;
1478 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001479
1480 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001481 const std::string core_oj = "core-oj";
1482 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1483 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001484 }
1485
Vladimir Marko47496c22016-01-27 16:15:08 +00001486 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001487 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1488 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1489 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1490 &class_linker->GetBootClassPath(),
1491 &class_path_files,
1492 &dex_files_
1493 };
1494 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001496 for (const std::string& filter : no_inline_filters) {
1497 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1498 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1499 // base location passes the StartsWith() test, so do all extra locations.
1500 std::string dex_location = dex_file->GetLocation();
1501 if (filter.find('/') == std::string::npos) {
1502 // The filter does not contain the path. Remove the path from dex_location as well.
1503 size_t last_slash = dex_file->GetLocation().rfind('/');
1504 if (last_slash != std::string::npos) {
1505 dex_location = dex_location.substr(last_slash + 1);
1506 }
1507 }
1508
1509 if (StartsWith(dex_location, filter.c_str())) {
1510 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1511 no_inline_from_dex_files_.push_back(dex_file);
1512 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001513 }
1514 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001515 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001516 }
1517 if (!no_inline_from_dex_files_.empty()) {
1518 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001519 }
1520 }
1521
Vladimir Marko307dac92015-10-20 11:20:09 +01001522 driver_.reset(new CompilerDriver(compiler_options_.get(),
1523 verification_results_.get(),
1524 &method_inliner_map_,
1525 compiler_kind_,
1526 instruction_set_,
1527 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001528 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001529 image_classes_.release(),
1530 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001531 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001532 thread_count_,
1533 dump_stats_,
1534 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001535 compiler_phases_timings_.get(),
1536 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001537 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001538 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001539 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001540 }
1541
Jeff Hao436183f2016-01-12 16:36:50 -08001542 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001543 // ensure the references between the two are correct.
1544 //
1545 // Currently we have a memory layout that looks something like this:
1546 //
1547 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001548 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001549 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001550 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001551 // +--------------+
1552 // | alloc spaces |
1553 // +--------------+
1554 //
Jeff Hao436183f2016-01-12 16:36:50 -08001555 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556 //
Jeff Hao436183f2016-01-12 16:36:50 -08001557 // 1. The images are expected to be loaded at an absolute address and
1558 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001559 //
Jeff Hao436183f2016-01-12 16:36:50 -08001560 // 2. There are absolute pointers from Methods in the images to their
1561 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001562 //
Jeff Hao436183f2016-01-12 16:36:50 -08001563 // 3. There are absolute pointers from the code in the oat files to Methods
1564 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001565 //
Jeff Hao436183f2016-01-12 16:36:50 -08001566 // 4. There are absolute pointers from code in the oat files to other code
1567 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 //
1569 // To get this all correct, we go through several steps.
1570 //
Jeff Hao436183f2016-01-12 16:36:50 -08001571 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001572 // the oat data size and code size. During this stage, we also set
1573 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001574 //
Jeff Hao436183f2016-01-12 16:36:50 -08001575 // 2. We prepare offsets for the objects in the images and calculate
1576 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001577 //
Jeff Hao436183f2016-01-12 16:36:50 -08001578 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001579 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001580 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001581 // can prepare the ELF headers and we then know the ELF memory segment
1582 // layout and we can now resolve all references. The compiler provides
1583 // LinkerPatch information in each CompiledMethod and we resolve these,
1584 // using the layout information and image object locations provided by
1585 // image writer, as we're writing the method code.
1586 //
Jeff Hao436183f2016-01-12 16:36:50 -08001587 // 4. We create the image files. They need to know where the oat files
1588 // will be loaded after itself. Originally oat files were simply
1589 // memory mapped so we could predict where their contents were based
1590 // on the file size. Now that they are ELF files, we need to inspect
1591 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001592 // where the oat header is located within.
1593 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001594 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001595 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001596 // load the .so at the desired location at runtime by offsetting the
1597 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001598 // TODO: Do this in step 3. We already know the layout there.
1599 //
1600 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1601 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001602
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1604 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001605 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1606 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001607 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001608 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1609
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001610 // Sync the data to the file, in case we did dex2dex transformations.
1611 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1612 if (!map->Sync()) {
1613 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1614 return false;
1615 }
1616 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001617
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001618 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001619 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001620 gc::Heap* const heap = Runtime::Current()->GetHeap();
1621 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001622 image_base_ = std::max(image_base_, RoundUp(
1623 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1624 kPageSize));
1625 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001626 // The non moving space is right after the oat file. Put the preferred app image location
1627 // right after the non moving space so that we ideally get a continuous immune region for
1628 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001629 // Use the default non moving space capacity since dex2oat does not have a separate non-
1630 // moving space. This means the runtime's non moving space space size will be as large
1631 // as the growth limit for dex2oat, but smaller in the zygote.
1632 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001634 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1635 }
1636
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 image_writer_.reset(new ImageWriter(*driver_,
1638 image_base_,
1639 compiler_options_->GetCompilePic(),
1640 IsAppImage(),
1641 image_storage_mode_,
1642 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001643 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001644
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001646 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1647 if (!image_writer_->PrepareImageAddressSpace()) {
1648 LOG(ERROR) << "Failed to prepare image address space.";
1649 return false;
1650 }
1651 }
1652
Vladimir Marko944da602016-02-19 12:27:55 +00001653 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001654 {
1655 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001656 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001657 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1658 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1659
1660 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1661 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1662
1663 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1664 size_t text_size = oat_writer->GetSize() - rodata_size;
1665 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1666
1667 if (IsImage()) {
1668 // Update oat layout.
1669 DCHECK(image_writer_ != nullptr);
1670 DCHECK_LT(i, oat_filenames_.size());
1671 image_writer_->UpdateOatFileLayout(i,
1672 elf_writer->GetLoadedSize(),
1673 oat_writer->GetOatDataOffset(),
1674 oat_writer->GetSize());
1675 }
1676 }
1677
1678 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001679 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001680 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1681 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001682
David Srbecky09c2a6b2016-03-11 17:11:44 +00001683 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader()));
1684
David Srbecky0c4572e2016-01-22 19:19:25 +00001685 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001686 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1687 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001688
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001689 OutputStream*& rodata = rodata_[i];
1690 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001691 if (!oat_writer->WriteRodata(rodata)) {
1692 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1693 return false;
1694 }
1695 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001696 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001697
Jeff Haodcdc85b2015-12-04 14:06:18 -08001698 OutputStream* text = elf_writer->StartText();
1699 if (!oat_writer->WriteCode(text)) {
1700 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1701 return false;
1702 }
1703 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001704
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001705 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1706 image_file_location_oat_checksum_,
1707 image_file_location_oat_data_begin_,
1708 image_patch_delta_)) {
1709 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1710 return false;
1711 }
1712
Vladimir Marko944da602016-02-19 12:27:55 +00001713 if (IsImage()) {
1714 // Update oat header information.
1715 DCHECK(image_writer_ != nullptr);
1716 DCHECK_LT(i, oat_filenames_.size());
1717 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1718 }
1719
Jeff Haodcdc85b2015-12-04 14:06:18 -08001720 elf_writer->WriteDynamicSection();
1721 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1722 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001723
Jeff Haodcdc85b2015-12-04 14:06:18 -08001724 if (!elf_writer->End()) {
1725 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1726 return false;
1727 }
1728
1729 // Flush the oat file.
1730 if (oat_files_[i] != nullptr) {
1731 if (oat_files_[i]->Flush() != 0) {
1732 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001733 return false;
1734 }
1735 }
1736
Jeff Haodcdc85b2015-12-04 14:06:18 -08001737 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001738
1739 oat_writer.reset();
1740 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001741 }
1742 }
1743
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001744 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001745 }
1746
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001747 // If we are compiling an image, invoke the image creation routine. Else just skip.
1748 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001749 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001750 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1751 if (!CreateImageFile()) {
1752 return false;
1753 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001754 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001755 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001756 return true;
1757 }
1758
Jeff Haodcdc85b2015-12-04 14:06:18 -08001759 // Create a copy from stripped to unstripped.
1760 bool CopyStrippedToUnstripped() {
1761 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1762 // If we don't want to strip in place, copy from stripped location to unstripped location.
1763 // We need to strip after image creation because FixupElf needs to use .strtab.
1764 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1765 // If the oat file is still open, flush it.
1766 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1767 if (!FlushCloseOatFile(i)) {
1768 return false;
1769 }
1770 }
1771
1772 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1773 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1774 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1775 size_t buffer_size = 8192;
1776 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1777 while (true) {
1778 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1779 if (bytes_read <= 0) {
1780 break;
1781 }
1782 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1783 CHECK(write_ok);
1784 }
1785 if (out->FlushCloseOrErase() != 0) {
1786 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1787 return false;
1788 }
1789 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1790 }
1791 }
1792 return true;
1793 }
1794
1795 bool FlushOatFiles() {
1796 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1797 for (size_t i = 0; i < oat_files_.size(); ++i) {
1798 if (oat_files_[i].get() != nullptr) {
1799 if (oat_files_[i]->Flush() != 0) {
1800 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1801 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001802 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001803 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001804 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001805 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001806 return true;
1807 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001808
Jeff Haodcdc85b2015-12-04 14:06:18 -08001809 bool FlushCloseOatFile(size_t i) {
1810 if (oat_files_[i].get() != nullptr) {
1811 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001812 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001813 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001814 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001815 }
1816 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001817 return true;
1818 }
1819
Jeff Haodcdc85b2015-12-04 14:06:18 -08001820 bool FlushCloseOatFiles() {
1821 bool result = true;
1822 for (size_t i = 0; i < oat_files_.size(); ++i) {
1823 result &= FlushCloseOatFile(i);
1824 }
1825 return result;
1826 }
1827
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001828 void DumpTiming() {
1829 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1830 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1831 }
1832 if (dump_passes_) {
1833 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1834 }
1835 }
1836
1837 CompilerOptions* GetCompilerOptions() const {
1838 return compiler_options_.get();
1839 }
1840
Andreas Gampe10e477d2014-11-19 12:57:42 -08001841 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001842 return IsAppImage() || IsBootImage();
1843 }
1844
1845 bool IsAppImage() const {
1846 return app_image_;
1847 }
1848
1849 bool IsBootImage() const {
1850 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001851 }
1852
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001853 bool IsHost() const {
1854 return is_host_;
1855 }
1856
Calin Juravle998c2162015-12-21 15:39:33 +02001857 bool UseProfileGuidedCompilation() const {
Andreas Gampe29d38e72016-03-23 15:31:51 +00001858 return CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter());
Calin Juravle998c2162015-12-21 15:39:33 +02001859 }
1860
Calin Juravle2e2db782016-02-23 12:00:03 +00001861 bool LoadProfile() {
Calin Juravle998c2162015-12-21 15:39:33 +02001862 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001863
1864 profile_compilation_info_.reset(new ProfileCompilationInfo());
1865 ScopedFlock flock;
Andreas Gampe29d38e72016-03-23 15:31:51 +00001866 bool success = true;
Calin Juravle2e2db782016-02-23 12:00:03 +00001867 std::string error;
1868 if (profile_file_fd_ != -1) {
1869 // The file doesn't need to be flushed so don't check the usage.
1870 // Pass a bogus path so that we can easily attribute any reported error.
1871 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1872 if (flock.Init(&file, &error)) {
1873 success = profile_compilation_info_->Load(profile_file_fd_);
1874 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001875 } else if (profile_file_ != "") {
Calin Juravle2e2db782016-02-23 12:00:03 +00001876 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1877 success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1878 }
1879 }
1880 if (!error.empty()) {
1881 LOG(WARNING) << "Cannot lock profiles: " << error;
Calin Juravle998c2162015-12-21 15:39:33 +02001882 }
Calin Juravle877fd962016-01-05 14:29:29 +00001883
Calin Juravle2e2db782016-02-23 12:00:03 +00001884 if (!success) {
1885 profile_compilation_info_.reset(nullptr);
1886 }
Calin Juravle877fd962016-01-05 14:29:29 +00001887
Calin Juravle2e2db782016-02-23 12:00:03 +00001888 return success;
Calin Juravle998c2162015-12-21 15:39:33 +02001889 }
1890
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001891 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001892 template <typename T>
1893 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1894 std::vector<T*> result;
1895 result.reserve(src.size());
1896 for (const std::unique_ptr<T>& t : src) {
1897 result.push_back(t.get());
1898 }
1899 return result;
1900 }
1901
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001902 std::string GetMultiImageBootClassPath() {
1903 DCHECK(IsBootImage());
1904 DCHECK_GT(oat_filenames_.size(), 1u);
1905 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1906 // too, but need to strip all path components (they will be re-established when loading).
1907 std::ostringstream bootcp_oss;
1908 bool first_bootcp = true;
1909 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1910 if (!first_bootcp) {
1911 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001912 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001913
1914 std::string dex_loc = dex_locations_[i];
1915 std::string image_filename = image_filenames_[i];
1916
1917 // Use the dex_loc path, but the image_filename name (without path elements).
1918 size_t dex_last_slash = dex_loc.rfind('/');
1919
1920 // npos is max(size_t). That makes this a bit ugly.
1921 size_t image_last_slash = image_filename.rfind('/');
1922 size_t image_last_at = image_filename.rfind('@');
1923 size_t image_last_sep = (image_last_slash == std::string::npos)
1924 ? image_last_at
1925 : (image_last_at == std::string::npos)
1926 ? std::string::npos
1927 : std::max(image_last_slash, image_last_at);
1928 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1929
1930 if (dex_last_slash == std::string::npos) {
1931 dex_loc = image_filename.substr(image_last_sep + 1);
1932 } else {
1933 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1934 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001935 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001936
1937 // Image filenames already end with .art, no need to replace.
1938
1939 bootcp_oss << dex_loc;
1940 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001941 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001942 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001943 }
1944
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001945 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1946 // This function is used only for apps and for an app we have exactly one oat file.
1947 DCHECK(!IsBootImage());
1948 DCHECK_EQ(oat_writers_.size(), 1u);
1949 std::vector<std::string> dex_files_canonical_locations;
1950 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1951 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001952 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001953
Vladimir Marko919f5532016-01-20 19:13:01 +00001954 std::vector<std::string> parsed;
1955 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001956 auto kept_it = std::remove_if(parsed.begin(),
1957 parsed.end(),
1958 [dex_files_canonical_locations](const std::string& location) {
1959 return ContainsElement(dex_files_canonical_locations,
1960 DexFile::GetDexCanonicalLocation(location.c_str()));
1961 });
1962 parsed.erase(kept_it, parsed.end());
1963 return parsed;
1964 }
1965
1966 // Opens requested class path files and appends them to opened_dex_files.
1967 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1968 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1969 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1970 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001971 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001972 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1973 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001974 }
1975 }
1976 }
1977
Vladimir Marko49b0f452015-12-10 13:49:19 +00001978 bool PrepareImageClasses() {
1979 // If --image-classes was specified, calculate the full list of classes to include in the image.
1980 if (image_classes_filename_ != nullptr) {
1981 image_classes_ =
1982 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1983 if (image_classes_ == nullptr) {
1984 return false;
1985 }
1986 } else if (IsBootImage()) {
1987 image_classes_.reset(new std::unordered_set<std::string>);
1988 }
1989 return true;
1990 }
1991
1992 bool PrepareCompiledClasses() {
1993 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1994 // image.
1995 if (compiled_classes_filename_ != nullptr) {
1996 compiled_classes_ =
1997 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1998 if (compiled_classes_ == nullptr) {
1999 return false;
2000 }
2001 } else {
2002 compiled_classes_.reset(nullptr); // By default compile everything.
2003 }
2004 return true;
2005 }
2006
2007 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2008 const char* classes_filename,
2009 const char* tag) {
2010 std::unique_ptr<std::unordered_set<std::string>> classes;
2011 std::string error_msg;
2012 if (zip_filename != nullptr) {
2013 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2014 } else {
2015 classes.reset(ReadImageClassesFromFile(classes_filename));
2016 }
2017 if (classes == nullptr) {
2018 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2019 << classes_filename << "': " << error_msg;
2020 }
2021 return classes;
2022 }
2023
2024 bool PrepareCompiledMethods() {
2025 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2026 if (compiled_methods_filename_ != nullptr) {
2027 std::string error_msg;
2028 if (compiled_methods_zip_filename_ != nullptr) {
2029 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2030 compiled_methods_filename_,
2031 nullptr, // No post-processing.
2032 &error_msg));
2033 } else {
2034 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2035 nullptr)); // No post-processing.
2036 }
2037 if (compiled_methods_.get() == nullptr) {
2038 LOG(ERROR) << "Failed to create list of compiled methods from '"
2039 << compiled_methods_filename_ << "': " << error_msg;
2040 return false;
2041 }
2042 } else {
2043 compiled_methods_.reset(nullptr); // By default compile everything.
2044 }
2045 return true;
2046 }
2047
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002048 void PruneNonExistentDexFiles() {
2049 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2050 size_t kept = 0u;
2051 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2052 if (!OS::FileExists(dex_filenames_[i])) {
2053 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2054 } else {
2055 dex_filenames_[kept] = dex_filenames_[i];
2056 dex_locations_[kept] = dex_locations_[i];
2057 ++kept;
2058 }
2059 }
2060 dex_filenames_.resize(kept);
2061 dex_locations_.resize(kept);
2062 }
2063
2064 bool AddDexFileSources() {
2065 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2066 if (zip_fd_ != -1) {
2067 DCHECK_EQ(oat_writers_.size(), 1u);
2068 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2069 return false;
2070 }
2071 } else if (oat_writers_.size() > 1u) {
2072 // Multi-image.
2073 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2074 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2075 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2076 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2077 return false;
2078 }
2079 }
2080 } else {
2081 DCHECK_EQ(oat_writers_.size(), 1u);
2082 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2083 DCHECK_NE(dex_filenames_.size(), 0u);
2084 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2085 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2086 return false;
2087 }
2088 }
2089 }
2090 return true;
2091 }
2092
2093 void CreateOatWriters() {
2094 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2095 elf_writers_.reserve(oat_files_.size());
2096 oat_writers_.reserve(oat_files_.size());
2097 for (const std::unique_ptr<File>& oat_file : oat_files_) {
David Srbecky5d811202016-03-08 13:21:22 +00002098 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2099 instruction_set_features_.get(),
2100 compiler_options_.get(),
2101 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002102 elf_writers_.back()->Start();
2103 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2104 }
2105 }
2106
Vladimir Marko49b0f452015-12-10 13:49:19 +00002107 void SaveDexInput() {
2108 for (size_t i = 0; i < dex_files_.size(); ++i) {
2109 const DexFile* dex_file = dex_files_[i];
2110 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2111 getpid(), i));
2112 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2113 if (tmp_file.get() == nullptr) {
2114 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2115 << ". Try: adb shell chmod 777 /data/local/tmp";
2116 continue;
2117 }
2118 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2119 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2120 UNUSED(tmp_file->Flush());
2121 UNUSED(tmp_file->Close());
2122 LOG(INFO) << "Wrote input to " << tmp_file_name;
2123 }
2124 }
2125
2126 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2127 RuntimeOptions raw_options;
2128 if (boot_image_filename_.empty()) {
2129 std::string boot_class_path = "-Xbootclasspath:";
2130 boot_class_path += Join(dex_filenames_, ':');
2131 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2132 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2133 boot_class_path_locations += Join(dex_locations_, ':');
2134 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2135 } else {
2136 std::string boot_image_option = "-Ximage:";
2137 boot_image_option += boot_image_filename_;
2138 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2139 }
2140 for (size_t i = 0; i < runtime_args_.size(); i++) {
2141 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2142 }
2143
2144 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2145 raw_options.push_back(
2146 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2147
2148 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2149 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2150 // have been stripped in preopting, anyways).
2151 if (!IsBootImage()) {
2152 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2153 }
2154 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2155 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2156 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002157 // Disable Hspace compaction to save heap size virtual space.
2158 // Only need disable Hspace for OOM becasue background collector is equal to
2159 // foreground collector by default for dex2oat.
2160 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002161
Andreas Gampeace0dc12016-01-20 13:33:13 -08002162 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2163 // force the free-list implementation for large objects.
2164 if (compiler_options_->IsForceDeterminism()) {
2165 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2166 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2167
2168 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2169 // compaction (done above) and ensure that neither foreground nor background collectors
2170 // are concurrent.
2171 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2172
2173 // To make identity hashcode deterministic, set a known seed.
2174 mirror::Object::SetHashCodeSeed(987654321U);
2175 }
2176
Vladimir Marko49b0f452015-12-10 13:49:19 +00002177 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2178 LOG(ERROR) << "Failed to parse runtime options";
2179 return false;
2180 }
2181 return true;
2182 }
2183
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002184 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002185 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2186 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002187 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002188 LOG(ERROR) << "Failed to create runtime";
2189 return false;
2190 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002191 runtime_.reset(Runtime::Current());
2192 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002193 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2194 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002195 if (!runtime_->HasCalleeSaveMethod(type)) {
2196 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002197 }
2198 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002199 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002200
2201 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2202 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002203 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002204
Vladimir Marko307dac92015-10-20 11:20:09 +01002205 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002206
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002207 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2208 // Runtime::Start, give it away now so that we don't starve GC.
2209 Thread* self = Thread::Current();
2210 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002211
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002212 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002213 }
2214
Jeff Haodcdc85b2015-12-04 14:06:18 -08002215 // 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 -08002216 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002217 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002218 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002219 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002220 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002221 image_filenames_.push_back(app_image_file_name_.c_str());
2222 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002223 if (!image_writer_->Write(app_image_fd_,
2224 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002225 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002226 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002227 return false;
2228 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002229
Jeff Haodcdc85b2015-12-04 14:06:18 -08002230 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002231 dchecked_vector<uintptr_t> oat_data_begins;
2232 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2233 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002234 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002235 // Destroy ImageWriter before doing FixupElf.
2236 image_writer_.reset();
2237
Vladimir Marko944da602016-02-19 12:27:55 +00002238 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2239 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002240 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2241 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2242 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2243 if (oat_file.get() == nullptr) {
2244 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2245 return false;
2246 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002247
Vladimir Marko944da602016-02-19 12:27:55 +00002248 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002249 oat_file->Erase();
2250 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2251 return false;
2252 }
2253
2254 if (oat_file->FlushCloseOrErase()) {
2255 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2256 return false;
2257 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002258 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002259 }
2260
2261 return true;
2262 }
2263
2264 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002265 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2266 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002267 std::function<std::string(const char*)> process = DotToDescriptor;
2268 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002269 }
2270
2271 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002272 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002273 const char* zip_filename,
2274 const char* image_classes_filename,
2275 std::string* error_msg) {
2276 std::function<std::string(const char*)> process = DotToDescriptor;
2277 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2278 }
2279
2280 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2281 // the given function.
2282 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2283 const char* input_filename, std::function<std::string(const char*)>* process) {
2284 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2285 if (input_file.get() == nullptr) {
2286 LOG(ERROR) << "Failed to open input file " << input_filename;
2287 return nullptr;
2288 }
2289 std::unique_ptr<std::unordered_set<std::string>> result(
2290 ReadCommentedInputStream(*input_file, process));
2291 input_file->close();
2292 return result.release();
2293 }
2294
2295 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2296 // Post-process each line with the given function.
2297 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002298 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002299 const char* input_filename,
2300 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002301 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002302 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2303 if (zip_archive.get() == nullptr) {
2304 return nullptr;
2305 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002306 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002307 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002308 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002309 zip_filename, error_msg->c_str());
2310 return nullptr;
2311 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002312 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2313 input_filename,
2314 error_msg));
2315 if (input_file.get() == nullptr) {
2316 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002317 zip_filename, error_msg->c_str());
2318 return nullptr;
2319 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002320 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2321 input_file->Size());
2322 std::istringstream input_stream(input_string);
2323 return ReadCommentedInputStream(input_stream, process);
2324 }
2325
2326 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2327 // with the given function.
2328 static std::unordered_set<std::string>* ReadCommentedInputStream(
2329 std::istream& in_stream,
2330 std::function<std::string(const char*)>* process) {
2331 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2332 new std::unordered_set<std::string>);
2333 while (in_stream.good()) {
2334 std::string dot;
2335 std::getline(in_stream, dot);
2336 if (StartsWith(dot, "#") || dot.empty()) {
2337 continue;
2338 }
2339 if (process != nullptr) {
2340 std::string descriptor((*process)(dot.c_str()));
2341 image_classes->insert(descriptor);
2342 } else {
2343 image_classes->insert(dot);
2344 }
2345 }
2346 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002347 }
2348
Mathieu Chartier49285c52014-12-02 15:43:48 -08002349 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002350 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2351 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002352 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002353 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002354 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002355 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002356 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2357 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002358 }
2359
Jeff Haodcdc85b2015-12-04 14:06:18 -08002360 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2361 std::string res(image_filename);
2362 size_t last_slash = res.rfind('/');
2363 if (last_slash == std::string::npos || last_slash == 0) {
2364 return res;
2365 }
2366 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2367 if (penultimate_slash == std::string::npos) {
2368 return res;
2369 }
2370 // Check that the string in-between is the expected one.
2371 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2372 GetInstructionSetString(isa)) {
2373 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2374 return res;
2375 }
2376 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2377 }
2378
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002379 std::unique_ptr<CompilerOptions> compiler_options_;
2380 Compiler::Kind compiler_kind_;
2381
2382 InstructionSet instruction_set_;
2383 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2384
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002385 uint32_t image_file_location_oat_checksum_;
2386 uintptr_t image_file_location_oat_data_begin_;
2387 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002388 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2389
Vladimir Marko307dac92015-10-20 11:20:09 +01002390 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002391
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002392 DexFileToMethodInlinerMap method_inliner_map_;
2393 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2394
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002395 std::unique_ptr<Runtime> runtime_;
2396
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002397 // Ownership for the class path files.
2398 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2399
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002400 size_t thread_count_;
2401 uint64_t start_ns_;
2402 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002403 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002404 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002405 std::vector<const char*> oat_filenames_;
2406 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002407 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002408 std::vector<const char*> dex_filenames_;
2409 std::vector<const char*> dex_locations_;
2410 int zip_fd_;
2411 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002412 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002413 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002414 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002415 uintptr_t image_base_;
2416 const char* image_classes_zip_filename_;
2417 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002418 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002419 const char* compiled_classes_zip_filename_;
2420 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002421 const char* compiled_methods_zip_filename_;
2422 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002423 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2424 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002425 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002426 bool app_image_;
2427 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002428 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002429 bool is_host_;
2430 std::string android_root_;
2431 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002432 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002433 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002434 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002435
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002436 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2437 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2438 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002439 std::unique_ptr<ImageWriter> image_writer_;
2440 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002441
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002442 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2443 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2444
Vladimir Marko47496c22016-01-27 16:15:08 +00002445 std::vector<const DexFile*> no_inline_from_dex_files_;
2446
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002447 std::vector<std::string> verbose_methods_;
2448 bool dump_stats_;
2449 bool dump_passes_;
2450 bool dump_timing_;
2451 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002452 std::string swap_file_name_;
2453 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002454 std::string app_image_file_name_;
2455 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002456 std::string profile_file_;
2457 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002458 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002459 TimingLogger* timings_;
2460 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002461 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002462 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002463
2464 // Backing storage.
2465 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002466
Andreas Gampeace0dc12016-01-20 13:33:13 -08002467 // See CompilerOptions.force_determinism_.
2468 bool force_determinism_;
2469
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002470 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2471};
2472
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002473static void b13564922() {
2474#if defined(__linux__) && defined(__arm__)
2475 int major, minor;
2476 struct utsname uts;
2477 if (uname(&uts) != -1 &&
2478 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2479 ((major < 3) || ((major == 3) && (minor < 4)))) {
2480 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2481 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2482 int old_personality = personality(0xffffffff);
2483 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2484 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2485 if (new_personality == -1) {
2486 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2487 }
2488 }
2489 }
2490#endif
2491}
2492
Andreas Gampe10e477d2014-11-19 12:57:42 -08002493static int CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002494 dex2oat.LoadClassProfileDescriptors();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002495 dex2oat.Compile();
2496
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002497 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002498 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002499 return EXIT_FAILURE;
2500 }
2501
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002502 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2503 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2504 // image writer will require this fd to generate the image.
2505 if (dex2oat.ShouldKeepOatFileOpen()) {
2506 if (!dex2oat.FlushOatFiles()) {
2507 return EXIT_FAILURE;
2508 }
2509 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002510 return EXIT_FAILURE;
2511 }
2512
Jeff Haodcdc85b2015-12-04 14:06:18 -08002513 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002514 if (!dex2oat.HandleImage()) {
2515 return EXIT_FAILURE;
2516 }
2517
2518 // When given --host, finish early without stripping.
2519 if (dex2oat.IsHost()) {
2520 dex2oat.DumpTiming();
2521 return EXIT_SUCCESS;
2522 }
2523
Jeff Haodcdc85b2015-12-04 14:06:18 -08002524 // Copy stripped to unstripped location, if necessary.
2525 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002526 return EXIT_FAILURE;
2527 }
2528
Jeff Haodcdc85b2015-12-04 14:06:18 -08002529 // FlushClose again, as stripping might have re-opened the oat files.
2530 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002531 return EXIT_FAILURE;
2532 }
2533
2534 dex2oat.DumpTiming();
2535 return EXIT_SUCCESS;
2536}
2537
2538static int CompileApp(Dex2Oat& dex2oat) {
2539 dex2oat.Compile();
2540
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002541 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002542 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002543 return EXIT_FAILURE;
2544 }
2545
Jeff Haodcdc85b2015-12-04 14:06:18 -08002546 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002547 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002548
2549 // When given --host, finish early without stripping.
2550 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002551 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002552 return EXIT_FAILURE;
2553 }
2554
2555 dex2oat.DumpTiming();
2556 return EXIT_SUCCESS;
2557 }
2558
Jeff Haodcdc85b2015-12-04 14:06:18 -08002559 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2560 // stripped versions. If this is given, we expect to be able to open writable files by name.
2561 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002562 return EXIT_FAILURE;
2563 }
2564
Jeff Haodcdc85b2015-12-04 14:06:18 -08002565 // Flush and close the files.
2566 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002567 return EXIT_FAILURE;
2568 }
2569
2570 dex2oat.DumpTiming();
2571 return EXIT_SUCCESS;
2572}
2573
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002574static int dex2oat(int argc, char** argv) {
2575 b13564922();
2576
2577 TimingLogger timings("compiler", false, false);
2578
Roland Levillain5c7e2602016-02-23 18:08:53 +00002579 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2580 // might produce a stack frame too large for this function or for
2581 // functions inlining it (such as main), that would not fit the
2582 // requirements of the `-Wframe-larger-than` option.
2583 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002584
2585 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002586 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002587
Calin Juravleb077e152016-02-18 18:47:37 +00002588 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02002589 // This operation involves I/O.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002590 if (dex2oat->UseProfileGuidedCompilation()) {
Calin Juravleb077e152016-02-18 18:47:37 +00002591 if (!dex2oat->LoadProfile()) {
2592 LOG(ERROR) << "Failed to process profile file";
Calin Juravle998c2162015-12-21 15:39:33 +02002593 return EXIT_FAILURE;
2594 }
2595 }
2596
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002597 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00002598 if (!dex2oat->OpenFile()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002599 return EXIT_FAILURE;
2600 }
2601
Andreas Gampe046c7062015-05-18 23:22:54 -07002602 // Print the complete line when any of the following is true:
2603 // 1) Debug build
2604 // 2) Compiling an image
2605 // 3) Compiling with --host
2606 // 4) Compiling on the host (not a target build)
2607 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002608 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002609 LOG(INFO) << CommandLine();
2610 } else {
2611 LOG(INFO) << StrippedCommandLine();
2612 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002613
Roland Levillain5c7e2602016-02-23 18:08:53 +00002614 if (!dex2oat->Setup()) {
2615 dex2oat->EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002616 return EXIT_FAILURE;
2617 }
2618
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002619 bool result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00002620 if (dex2oat->IsImage()) {
2621 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002622 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00002623 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002624 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002625
Roland Levillain5c7e2602016-02-23 18:08:53 +00002626 dex2oat->Shutdown();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002627 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002628}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002629} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002630
2631int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002632 int result = art::dex2oat(argc, argv);
2633 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2634 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2635 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002636 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002637 exit(result);
2638 }
2639 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002640}