blob: e3e01804dbb68274b9a6ed52e62748801bc60660 [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>
Andreas Gampe67f02822016-06-24 21:05:23 -070025#include <limits>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <sstream>
27#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070028#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include <vector>
30
Vladimir Markof94b7812014-06-05 15:48:04 +010031#if defined(__linux__) && defined(__arm__)
32#include <sys/personality.h>
33#include <sys/utsname.h>
34#endif
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080037#include "android-base/strings.h"
38
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000041#include "art_method-inl.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070042#include "base/callee_save_type.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070043#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080044#include "base/macros.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000045#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/stl_util.h"
47#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010048#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "base/timing_logger.h"
50#include "base/unix_file/fd_file.h"
51#include "class_linker.h"
Calin Juravle1ce70852017-06-28 10:59:03 -070052#include "class_loader_context.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000053#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000054#include "compiler_callbacks.h"
David Srbecky09c2a6b2016-03-11 17:11:44 +000055#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000056#include "debug/method_debug_info.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000057#include "dex/quick_compiler_callbacks.h"
58#include "dex/verification_results.h"
Andreas Gampe7b565912017-03-20 15:48:52 -070059#include "dex2oat_return_codes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000060#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080062#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080063#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070064#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000065#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "gc/space/image_space.h"
67#include "gc/space/space-inl.h"
Mathieu Chartier72041a02017-07-14 18:23:25 -070068#include "gc/verification.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070070#include "interpreter/unstarted_runtime.h"
Mathieu Chartier72041a02017-07-14 18:23:25 -070071#include "java_vm_ext.h"
Calin Juravle33083d62017-01-18 15:29:12 -080072#include "jit/profile_compilation_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "leb128.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010074#include "linker/buffered_output_stream.h"
75#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000076#include "linker/multi_oat_relative_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "mirror/class-inl.h"
78#include "mirror/class_loader.h"
79#include "mirror/object-inl.h"
80#include "mirror/object_array-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070081#include "nativehelper/ScopedLocalRef.h"
Andreas Gampe2ff3b972017-06-05 18:14:53 -070082#include "oat_file.h"
Jeff Haob11ffb72016-04-07 15:40:54 -070083#include "oat_file_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070084#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070085#include "os.h"
86#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000087#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070088#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070089#include "utils.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000090#include "vdex_file.h"
David Brazdilca3c8c32016-09-06 14:04:48 +010091#include "verifier/verifier_deps.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070092#include "well_known_classes.h"
93#include "zip_archive.h"
94
95namespace art {
96
Andreas Gampe46ee31b2016-12-14 10:11:49 -080097using android::base::StringAppendV;
98using android::base::StringPrintf;
99
Andreas Gampee1459ae2016-06-29 09:36:30 -0700100static constexpr size_t kDefaultMinDexFilesForSwap = 2;
101static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB;
102
Mathieu Chartier010126f2017-07-15 15:44:18 -0700103// Compiler filter override for very large apps.
104static constexpr CompilerFilter::Filter kLargeAppFilter = CompilerFilter::kVerify;
105
Brian Carlstrom6449c622014-02-10 23:48:36 -0800106static int original_argc;
107static char** original_argv;
108
109static std::string CommandLine() {
110 std::vector<std::string> command;
111 for (int i = 0; i < original_argc; ++i) {
112 command.push_back(original_argv[i]);
113 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800114 return android::base::Join(command, ' ');
Brian Carlstrom6449c622014-02-10 23:48:36 -0800115}
116
Andreas Gampe046c7062015-05-18 23:22:54 -0700117// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
118// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
119// locations are all staged).
120static std::string StrippedCommandLine() {
121 std::vector<std::string> command;
122
Calin Juravle07c6d722017-06-07 17:06:12 +0000123 // Do a pre-pass to look for zip-fd and the compiler filter.
Andreas Gampe046c7062015-05-18 23:22:54 -0700124 bool saw_zip_fd = false;
Calin Juravle07c6d722017-06-07 17:06:12 +0000125 bool saw_compiler_filter = false;
Andreas Gampe046c7062015-05-18 23:22:54 -0700126 for (int i = 0; i < original_argc; ++i) {
Andreas Gampe9186ced2016-12-12 14:28:21 -0800127 if (android::base::StartsWith(original_argv[i], "--zip-fd=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700128 saw_zip_fd = true;
Andreas Gampe046c7062015-05-18 23:22:54 -0700129 }
Calin Juravle07c6d722017-06-07 17:06:12 +0000130 if (android::base::StartsWith(original_argv[i], "--compiler-filter=")) {
131 saw_compiler_filter = true;
Calin Juravle07c6d722017-06-07 17:06:12 +0000132 }
Andreas Gampe046c7062015-05-18 23:22:54 -0700133 }
134
135 // Now filter out things.
136 for (int i = 0; i < original_argc; ++i) {
137 // All runtime-arg parameters are dropped.
138 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
139 i++; // Drop the next part, too.
140 continue;
141 }
142
143 // Any instruction-setXXX is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800144 if (android::base::StartsWith(original_argv[i], "--instruction-set")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700145 continue;
146 }
147
148 // The boot image is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800149 if (android::base::StartsWith(original_argv[i], "--boot-image=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700150 continue;
151 }
152
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800153 // The image format is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800154 if (android::base::StartsWith(original_argv[i], "--image-format=")) {
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800155 continue;
156 }
157
Andreas Gampe046c7062015-05-18 23:22:54 -0700158 // This should leave any dex-file and oat-file options, describing what we compiled.
159
160 // However, we prefer to drop this when we saw --zip-fd.
161 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700162 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe9186ced2016-12-12 14:28:21 -0800163 if (android::base::StartsWith(original_argv[i], "--zip-") ||
164 android::base::StartsWith(original_argv[i], "--dex-") ||
165 android::base::StartsWith(original_argv[i], "--oat-") ||
166 android::base::StartsWith(original_argv[i], "--swap-") ||
167 android::base::StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700168 continue;
169 }
170 }
171
172 command.push_back(original_argv[i]);
173 }
174
Calin Juravle07c6d722017-06-07 17:06:12 +0000175 if (!saw_compiler_filter) {
176 command.push_back("--compiler-filter=" +
177 CompilerFilter::NameOfFilter(CompilerFilter::kDefaultCompilerFilter));
178 }
179
Andreas Gampe046c7062015-05-18 23:22:54 -0700180 // Construct the final output.
181 if (command.size() <= 1U) {
182 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
183 return "Starting dex2oat.";
184 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800185 return android::base::Join(command, ' ');
Andreas Gampe046c7062015-05-18 23:22:54 -0700186}
187
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188static void UsageErrorV(const char* fmt, va_list ap) {
189 std::string error;
190 StringAppendV(&error, fmt, ap);
191 LOG(ERROR) << error;
192}
193
194static void UsageError(const char* fmt, ...) {
195 va_list ap;
196 va_start(ap, fmt);
197 UsageErrorV(fmt, ap);
198 va_end(ap);
199}
200
Andreas Gampe794ad762015-02-23 08:12:24 -0800201NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 va_list ap;
203 va_start(ap, fmt);
204 UsageErrorV(fmt, ap);
205 va_end(ap);
206
Brian Carlstrom6449c622014-02-10 23:48:36 -0800207 UsageError("Command: %s", CommandLine().c_str());
208
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError("Usage: dex2oat [options]...");
210 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100211 UsageError(" -j<number>: specifies the number of threads used for compilation.");
212 UsageError(" Default is the number of detected hardware threads available on the");
213 UsageError(" host system.");
214 UsageError(" Example: -j12");
215 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700216 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError(" Example: --dex-file=/system/framework/core.jar");
218 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700219 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
220 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
221 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
222 UsageError(" --dex-location=/system/framework/core.jar");
223 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
225 UsageError(" containing a classes.dex file to compile.");
226 UsageError(" Example: --zip-fd=5");
227 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700228 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
229 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
231 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800232 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 UsageError(" Example: --oat-file=/system/framework/boot.oat");
234 UsageError("");
235 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900236 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError("");
238 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
239 UsageError(" to the file descriptor specified by --oat-fd.");
240 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
241 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800242 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
244 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800245 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 UsageError(" Example: --image=/system/framework/boot.art");
247 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800248 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800249 UsageError(" Which format to store the image.");
250 UsageError(" Example: --image-format=lz4");
251 UsageError(" Default: uncompressed");
252 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
254 UsageError(" Example: --image=frameworks/base/preloaded-classes");
255 UsageError("");
256 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
257 UsageError(" Example: --base=0x50000000");
258 UsageError("");
259 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000260 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000262 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000263 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700264 UsageError("");
265 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
266 UsageError(" Example: --android-root=out/host/linux-x86");
267 UsageError(" Default: $ANDROID_ROOT");
268 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800269 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700270 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700271 UsageError(" Example: --instruction-set=x86");
272 UsageError(" Default: arm");
273 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700274 UsageError(" --instruction-set-features=...,: Specify instruction set features");
275 UsageError(" Example: --instruction-set-features=div");
276 UsageError(" Default: default");
277 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700278 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
279 UsageError(" Default: disabled");
280 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800281 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700282 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800283 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100284 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700285 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100286 UsageError(" --compiler-filter="
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100287 "(assume-verified"
288 "|extract"
289 "|verify"
290 "|quicken"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000291 "|space-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100292 "|space"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000293 "|speed-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100294 "|speed"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000295 "|everything-profile"
296 "|everything):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700297 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800298 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800299 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800300 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800301 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
302 UsageError(" method for compiler filter tuning.");
303 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
304 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
305 UsageError("");
306 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
307 UsageError(" method for compiler filter tuning.");
308 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
309 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
310 UsageError("");
311 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
312 UsageError(" method for compiler filter tuning.");
313 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
314 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
315 UsageError("");
316 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
317 UsageError(" method for compiler filter tuning.");
318 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
319 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
320 UsageError("");
321 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
322 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700323 UsageError(" and the filter is not interpret-only or verify-none or verify-at-runtime, ");
324 UsageError(" overrides the filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800325 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
326 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
327 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100328 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
329 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100330 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
331 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100332 UsageError(" Example: --inline-max-code-units=%d",
333 CompilerOptions::kDefaultInlineMaxCodeUnits);
334 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
335 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700336 UsageError(" --dump-timing: display a breakdown of where time was spent");
337 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100338 UsageError(" -g");
339 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
340 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky346dc992016-03-13 22:00:07 +0000341 UsageError(" If used without --debuggable, it will be best-effort only.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000342 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700343 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100344 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100345 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000346 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
347 UsageError(" debug information necessary to print backtraces. (disabled by default)");
348 UsageError("");
David Srbecky346dc992016-03-13 22:00:07 +0000349 UsageError(" --no-generate-mini-debug-info: Do not generate backtrace info.");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000350 UsageError("");
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700351 UsageError(" --generate-build-id: Generate GNU-compatible linker build ID ELF section with");
352 UsageError(" SHA-1 of the file content (and thus stable across identical builds)");
353 UsageError("");
354 UsageError(" --no-generate-build-id: Do not generate the build ID ELF section.");
355 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000356 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000357 UsageError("");
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700358 UsageError(" --avoid-storing-invocation: Avoid storing the invocation args in the key value");
359 UsageError(" store. Used to test determinism with different args.");
360 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700361 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
362 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
363 UsageError(" Use a separate --runtime-arg switch for each argument.");
364 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700365 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000366 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000368 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
369 UsageError(" Cannot be used together with --profile-file.");
370 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100371 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800372 UsageError(" Example: --swap-file=/data/tmp/swap.001");
373 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100374 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800375 UsageError(" Example: --swap-fd=10");
376 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100377 UsageError(" --swap-dex-size-threshold=<size>: specifies the minimum total dex file size in");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700378 UsageError(" bytes to allow the use of swap.");
379 UsageError(" Example: --swap-dex-size-threshold=1000000");
380 UsageError(" Default: %zu", kDefaultMinDexFileCumulativeSizeForSwap);
381 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100382 UsageError(" --swap-dex-count-threshold=<count>: specifies the minimum number of dex files to");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700383 UsageError(" allow the use of swap.");
384 UsageError(" Example: --swap-dex-count-threshold=10");
385 UsageError(" Default: %zu", kDefaultMinDexFilesForSwap);
386 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100387 UsageError(" --very-large-app-threshold=<size>: specifies the minimum total dex file size in");
Mathieu Chartier010126f2017-07-15 15:44:18 -0700388 UsageError(" bytes to consider the input \"very large\" and reduce compilation done.");
Andreas Gampe67f02822016-06-24 21:05:23 -0700389 UsageError(" Example: --very-large-app-threshold=100000000");
390 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700391 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
392 UsageError(" Example: --app-image-fd=10");
393 UsageError("");
394 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
395 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
396 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800397 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
398 "input dex file.");
399 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000400 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000401 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100402 UsageError(" --dump-cfg=<cfg-file>: dump control-flow graphs (CFGs) to specified file.");
403 UsageError(" Example: --dump-cfg=output.cfg");
404 UsageError("");
405 UsageError(" --dump-cfg-append: when dumping CFGs to an existing file, append new CFG data to");
406 UsageError(" existing data (instead of overwriting existing data with new data, which is");
407 UsageError(" the default behavior). This option is only meaningful when used with");
408 UsageError(" --dump-cfg.");
409 UsageError("");
Jeff Hao16d48432017-04-05 17:05:46 -0700410 UsageError(" --classpath-dir=<directory-path>: directory used to resolve relative class paths.");
411 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700412 UsageError(" --class-loader-context=<string spec>: a string specifying the intended");
413 UsageError(" runtime loading context for the compiled dex files.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700414 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700415 UsageError(" It describes how the class loader chain should be built in order to ensure");
416 UsageError(" classes are resolved during dex2aot as they would be resolved at runtime.");
417 UsageError(" This spec will be encoded in the oat file. If at runtime the dex file is");
418 UsageError(" loaded in a different context, the oat file will be rejected.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700419 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700420 UsageError(" The chain is interpreted in the natural 'parent order', meaning that class");
421 UsageError(" loader 'i+1' will be the parent of class loader 'i'.");
Calin Juravlec79470d2017-07-12 17:37:42 -0700422 UsageError(" The compilation sources will be appended to the classpath of the first class");
423 UsageError(" loader.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700424 UsageError("");
Calin Juravlec79470d2017-07-12 17:37:42 -0700425 UsageError(" E.g. if the context is 'PCL[lib1.dex];DLC[lib2.dex]' and ");
426 UsageError(" --dex-file=src.dex then dex2oat will setup a PathClassLoader with classpath ");
427 UsageError(" 'lib1.dex:src.dex' and set its parent to a DelegateLastClassLoader with ");
428 UsageError(" classpath 'lib2.dex'.");
Calin Juravle1ce70852017-06-28 10:59:03 -0700429 UsageError(" ");
430 UsageError(" Note that the compiler will be tolerant if the source dex files specified");
431 UsageError(" with --dex-file are found in the classpath. The source dex files will be");
432 UsageError(" removed from any class loader's classpath possibly resulting in empty");
433 UsageError(" class loaders.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700434 UsageError("");
Calin Juravlec79470d2017-07-12 17:37:42 -0700435 UsageError(" Example: --class-loader-context=PCL[lib1.dex:lib2.dex];DLC[lib3.dex]");
Calin Juravle1ce70852017-06-28 10:59:03 -0700436 UsageError("");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700437 UsageError(" --dirty-image-objects=<directory-path>: list of known dirty objects in the image.");
438 UsageError(" The image writer will group them together.");
439 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 std::cerr << "See log for usage error information\n";
441 exit(EXIT_FAILURE);
442}
443
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444// The primary goal of the watchdog is to prevent stuck build servers
445// during development when fatal aborts lead to a cascade of failures
446// that result in a deadlock.
447class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800448// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449#undef CHECK_PTHREAD_CALL
450#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
451 do { \
452 int rc = call args; \
453 if (rc != 0) { \
454 errno = rc; \
455 std::string message(# call); \
456 message += " failed for "; \
457 message += reason; \
458 Fatal(message); \
459 } \
460 } while (false)
461
462 public:
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800463 explicit WatchDog(int64_t timeout_in_milliseconds)
464 : timeout_in_milliseconds_(timeout_in_milliseconds),
465 shutting_down_(false) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700467 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800468#ifndef __APPLE__
469 pthread_condattr_t condattr;
liulvping8f7101e2017-01-16 15:14:43 +0800470 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_init, (&condattr), reason);
471 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_setclock, (&condattr, CLOCK_MONOTONIC), reason);
472 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, &condattr), reason);
473 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_destroy, (&condattr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800474#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
476 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
478 }
479 ~WatchDog() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480 const char* reason = "dex2oat watch dog thread shutdown";
481 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
482 shutting_down_ = true;
483 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
484 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
485
Kenny Root51316382014-05-13 14:59:37 -0700486 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700487
488 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
489 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
490 }
491
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800492 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
493 // large.
494 static constexpr int64_t kWatchdogVerifyMultiplier =
495 kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
496
497 // When setting timeouts, keep in mind that the build server may not be as fast as your
498 // desktop. Debug builds are slower so they have larger timeouts.
499 static constexpr int64_t kWatchdogSlowdownFactor = kIsDebugBuild ? 5U : 1U;
500
501 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
502 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
503 // itself before that watchdog would take down the system server.
504 static constexpr int64_t kWatchDogTimeoutSeconds = kWatchdogSlowdownFactor * (9 * 60 + 30);
505
506 static constexpr int64_t kDefaultWatchdogTimeoutInMS =
507 kWatchdogVerifyMultiplier * kWatchDogTimeoutSeconds * 1000;
508
Brian Carlstrom7940e442013-07-12 13:46:57 -0700509 private:
510 static void* CallBack(void* arg) {
511 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
512 ::art::SetThreadName("dex2oat watch dog");
513 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700514 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700515 }
516
Andreas Gampe794ad762015-02-23 08:12:24 -0800517 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700518 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
519 // it's rather easy to hang in unwinding.
520 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
521 // logcat logging or stderr output.
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700522 android::base::LogMessage::LogLine(__FILE__,
523 __LINE__,
524 android::base::LogId::DEFAULT,
525 LogSeverity::FATAL,
526 message.c_str());
Andreas Gampe48fde372017-06-06 07:43:46 -0700527 // If we're on the host, try to dump all threads to get a sense of what's going on. This is
528 // restricted to the host as the dump may itself go bad.
529 // TODO: Use a double watchdog timeout, so we can enable this on-device.
530 if (!kIsTargetBuild && Runtime::Current() != nullptr) {
Andreas Gampecd607312017-06-05 17:03:05 -0700531 Runtime::Current()->AttachCurrentThread("Watchdog thread attached for dumping",
532 true,
533 nullptr,
534 false);
535 Runtime::Current()->DumpForSigQuit(std::cerr);
536 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700537 exit(1);
538 }
539
540 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700541 timespec timeout_ts;
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800542#if defined(__APPLE__)
543 InitTimeSpec(true, CLOCK_REALTIME, timeout_in_milliseconds_, 0, &timeout_ts);
544#else
liulvping8f7101e2017-01-16 15:14:43 +0800545 InitTimeSpec(true, CLOCK_MONOTONIC, timeout_in_milliseconds_, 0, &timeout_ts);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800546#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 const char* reason = "dex2oat watch dog thread waiting";
548 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
549 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800550 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700551 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700552 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800553 timeout_in_milliseconds_/1000));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700554 } else if (rc != 0) {
555 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
556 strerror(errno)));
557 Fatal(message.c_str());
558 }
559 }
560 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
561 }
562
Brian Carlstrom7940e442013-07-12 13:46:57 -0700563 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
564 pthread_mutex_t mutex_;
565 pthread_cond_t cond_;
566 pthread_attr_t attr_;
567 pthread_t pthread_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700568
569 const int64_t timeout_in_milliseconds_;
570 bool shutting_down_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700571};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800573class Dex2Oat FINAL {
574 public:
575 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100576 compiler_kind_(Compiler::kOptimizing),
Artem Serovba6b6792016-08-15 14:22:07 +0100577 instruction_set_(kRuntimeISA == kArm ? kThumb2 : kRuntimeISA),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800578 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000579 image_file_location_oat_checksum_(0),
580 image_file_location_oat_data_begin_(0),
581 image_patch_delta_(0),
582 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700583 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800584 runtime_(nullptr),
585 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
586 start_ns_(NanoTime()),
Andreas Gampec560fc02014-07-16 09:57:39 -0700587 start_cputime_ns_(ProcessCpuNanoTime()),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800588 oat_fd_(-1),
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000589 input_vdex_fd_(-1),
590 output_vdex_fd_(-1),
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000591 input_vdex_file_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800592 zip_fd_(-1),
593 image_base_(0U),
594 image_classes_zip_filename_(nullptr),
595 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800596 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800597 compiled_classes_zip_filename_(nullptr),
598 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700599 compiled_methods_zip_filename_(nullptr),
600 compiled_methods_filename_(nullptr),
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700601 passes_to_run_filename_(nullptr),
Mathieu Chartierff0baff2017-08-02 23:04:19 -0700602 dirty_image_objects_filename_(nullptr),
Jeff Hao436183f2016-01-12 16:36:50 -0800603 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800604 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000605 elf_writers_(),
606 oat_writers_(),
607 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000608 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700609 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000610 opened_dex_files_maps_(),
611 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000612 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800613 dump_stats_(false),
614 dump_passes_(false),
615 dump_timing_(false),
616 dump_slow_timing_(kIsDebugBuild),
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700617 avoid_storing_invocation_(false),
Calin Juravle2e2db782016-02-23 12:00:03 +0000618 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800619 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000620 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800621 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000622 force_determinism_(false)
623 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800624
625 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800626 // Log completion time before deleting the runtime_, because this accesses
627 // the runtime.
628 LogCompletionTime();
629
Vladimir Marko307dac92015-10-20 11:20:09 +0100630 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
631 // We want to just exit on non-debug builds, not bringing the runtime down
632 // in an orderly fashion. So release the following fields.
633 driver_.release();
634 image_writer_.release();
635 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
636 dex_file.release();
637 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000638 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
639 map.release();
640 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100641 for (std::unique_ptr<File>& vdex_file : vdex_files_) {
642 vdex_file.release();
643 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800644 for (std::unique_ptr<File>& oat_file : oat_files_) {
645 oat_file.release();
646 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100647 runtime_.release();
648 verification_results_.release();
649 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100650 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700651 }
652
Roland Levillain9ec5e222015-08-17 20:18:41 +0100653 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800654 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800655 std::string boot_image_filename;
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800656 int64_t watch_dog_timeout_in_ms = -1;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800657 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000658 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800659 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100660 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800661
Roland Levillain9ec5e222015-08-17 20:18:41 +0100662 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000663 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100664 }
665
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000666 void ParseInputVdexFd(const StringPiece& option) {
667 // Note that the input vdex fd might be -1.
668 ParseIntOption(option, "--input-vdex-fd", &input_vdex_fd_, Usage);
669 }
670
671 void ParseOutputVdexFd(const StringPiece& option) {
672 ParseUintOption(option, "--output-vdex-fd", &output_vdex_fd_, Usage);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100673 }
674
Roland Levillain9ec5e222015-08-17 20:18:41 +0100675 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000676 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100677 }
678
Calin Juravle877fd962016-01-05 14:29:29 +0000679 void ParseFdForCollection(const StringPiece& option,
680 const char* arg_name,
681 std::vector<uint32_t>* fds) {
682 uint32_t fd;
683 ParseUintOption(option, arg_name, &fd, Usage);
684 fds->push_back(fd);
685 }
686
Roland Levillain9ec5e222015-08-17 20:18:41 +0100687 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000688 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100689 }
690
691 void ParseBase(const StringPiece& option) {
692 DCHECK(option.starts_with("--base="));
693 const char* image_base_str = option.substr(strlen("--base=")).data();
694 char* end;
695 image_base_ = strtoul(image_base_str, &end, 16);
696 if (end == image_base_str || *end != '\0') {
697 Usage("Failed to parse hexadecimal value for option %s", option.data());
698 }
699 }
700
701 void ParseInstructionSet(const StringPiece& option) {
702 DCHECK(option.starts_with("--instruction-set="));
703 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
704 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
705 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
706 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
707 buf.get()[instruction_set_str.length()] = 0;
708 instruction_set_ = GetInstructionSetFromString(buf.get());
709 // arm actually means thumb2.
710 if (instruction_set_ == InstructionSet::kArm) {
711 instruction_set_ = InstructionSet::kThumb2;
712 }
713 }
714
715 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
716 DCHECK(option.starts_with("--instruction-set-variant="));
717 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800718 instruction_set_features_ = InstructionSetFeatures::FromVariant(
719 instruction_set_, str.as_string(), &parser_options->error_msg);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100720 if (instruction_set_features_.get() == nullptr) {
721 Usage("%s", parser_options->error_msg.c_str());
722 }
723 }
724
725 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
726 DCHECK(option.starts_with("--instruction-set-features="));
727 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800728 if (instruction_set_features_ == nullptr) {
729 instruction_set_features_ = InstructionSetFeatures::FromVariant(
730 instruction_set_, "default", &parser_options->error_msg);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100731 if (instruction_set_features_.get() == nullptr) {
732 Usage("Problem initializing default instruction set features variant: %s",
733 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800735 }
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800736 instruction_set_features_ =
Roland Levillain9ec5e222015-08-17 20:18:41 +0100737 instruction_set_features_->AddFeaturesFromString(str.as_string(),
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800738 &parser_options->error_msg);
739 if (instruction_set_features_ == nullptr) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100740 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
741 }
742 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800743
Roland Levillain9ec5e222015-08-17 20:18:41 +0100744 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
745 DCHECK(option.starts_with("--compiler-backend="));
746 parser_options->requested_specific_compiler = true;
747 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
748 if (backend_str == "Quick") {
749 compiler_kind_ = Compiler::kQuick;
750 } else if (backend_str == "Optimizing") {
751 compiler_kind_ = Compiler::kOptimizing;
752 } else {
753 Usage("Unknown compiler backend: %s", backend_str.data());
754 }
755 }
756
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800757 void ParseImageFormat(const StringPiece& option) {
758 const StringPiece substr("--image-format=");
759 DCHECK(option.starts_with(substr));
760 const StringPiece format_str = option.substr(substr.length());
761 if (format_str == "lz4") {
762 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800763 } else if (format_str == "lz4hc") {
764 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800765 } else if (format_str == "uncompressed") {
766 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
767 } else {
768 Usage("Unknown image format: %s", format_str.data());
769 }
770 }
771
Jeff Hao436183f2016-01-12 16:36:50 -0800772 void ProcessOptions(ParserOptions* parser_options) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000773 compiler_options_->boot_image_ = !image_filenames_.empty();
774 compiler_options_->app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700775
Roland Levillain2b03a1f2017-06-06 16:09:59 +0100776 if (IsBootImage() && image_filenames_.size() == 1) {
777 const std::string& boot_image_filename = image_filenames_[0];
778 compiler_options_->core_image_ = CompilerDriver::IsCoreImageFilename(boot_image_filename);
779 }
780
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700781 if (IsAppImage() && IsBootImage()) {
782 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
783 }
784
Jeff Haodcdc85b2015-12-04 14:06:18 -0800785 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800786 Usage("Output must be supplied with either --oat-file or --oat-fd");
787 }
788
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000789 if (input_vdex_fd_ != -1 && !input_vdex_.empty()) {
790 Usage("Can't have both --input-vdex-fd and --input-vdex");
791 }
792
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100793 if (output_vdex_fd_ != -1 && !output_vdex_.empty()) {
794 Usage("Can't have both --output-vdex-fd and --output-vdex");
795 }
796
Jeff Haodcdc85b2015-12-04 14:06:18 -0800797 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 Usage("--oat-file should not be used with --oat-fd");
799 }
800
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000801 if ((output_vdex_fd_ == -1) != (oat_fd_ == -1)) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100802 Usage("VDEX and OAT output must be specified either with one --oat-filename "
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000803 "or with --oat-fd and --output-vdex-fd file descriptors");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100804 }
805
Roland Levillain9ec5e222015-08-17 20:18:41 +0100806 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 Usage("--oat-symbols should not be used with --oat-fd");
808 }
809
Roland Levillain9ec5e222015-08-17 20:18:41 +0100810 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800811 Usage("--oat-symbols should not be used with --host");
812 }
813
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000814 if (output_vdex_fd_ != -1 && !image_filenames_.empty()) {
815 Usage("--output-vdex-fd should not be used with --image");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100816 }
817
Jeff Haodcdc85b2015-12-04 14:06:18 -0800818 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800819 Usage("--oat-fd should not be used with --image");
820 }
821
Jeff Haodcdc85b2015-12-04 14:06:18 -0800822 if (!parser_options->oat_symbols.empty() &&
823 parser_options->oat_symbols.size() != oat_filenames_.size()) {
824 Usage("--oat-file arguments do not match --oat-symbols arguments");
825 }
826
827 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
828 Usage("--oat-file arguments do not match --image arguments");
829 }
830
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800831 if (android_root_.empty()) {
832 const char* android_root_env_var = getenv("ANDROID_ROOT");
833 if (android_root_env_var == nullptr) {
834 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800836 android_root_ += android_root_env_var;
837 }
838
Vladimir Markoaad75c62016-10-03 08:46:48 +0000839 if (!IsBootImage() && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100840 parser_options->boot_image_filename += android_root_;
841 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800842 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100843 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000844 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800845 }
846
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700847 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800848 Usage("--image-classes should only be used with --image");
849 }
850
Vladimir Marko49b0f452015-12-10 13:49:19 +0000851 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800852 Usage("--image-classes should not be used with --boot-image");
853 }
854
855 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
856 Usage("--image-classes-zip should be used with --image-classes");
857 }
858
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700859 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800860 Usage("--compiled-classes should only be used with --image");
861 }
862
Vladimir Marko49b0f452015-12-10 13:49:19 +0000863 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800864 Usage("--compiled-classes should not be used with --boot-image");
865 }
866
867 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
868 Usage("--compiled-classes-zip should be used with --compiled-classes");
869 }
870
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800871 if (dex_filenames_.empty() && zip_fd_ == -1) {
872 Usage("Input must be supplied with either --dex-file or --zip-fd");
873 }
874
875 if (!dex_filenames_.empty() && zip_fd_ != -1) {
876 Usage("--dex-file should not be used with --zip-fd");
877 }
878
879 if (!dex_filenames_.empty() && !zip_location_.empty()) {
880 Usage("--dex-file should not be used with --zip-location");
881 }
882
883 if (dex_locations_.empty()) {
884 for (const char* dex_file_name : dex_filenames_) {
885 dex_locations_.push_back(dex_file_name);
886 }
887 } else if (dex_locations_.size() != dex_filenames_.size()) {
888 Usage("--dex-location arguments do not match --dex-file arguments");
889 }
890
Jeff Haodcdc85b2015-12-04 14:06:18 -0800891 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
892 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
893 Usage("--oat-file arguments must be singular or match --dex-file arguments");
894 }
895 }
896
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800897 if (zip_fd_ != -1 && zip_location_.empty()) {
898 Usage("--zip-location should be supplied with --zip-fd");
899 }
900
Vladimir Marko49b0f452015-12-10 13:49:19 +0000901 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800902 if (image_base_ == 0) {
903 Usage("Non-zero --base not specified");
904 }
905 }
906
Mathieu Chartiera8077802016-03-16 19:08:31 -0700907 const bool have_profile_file = !profile_file_.empty();
908 const bool have_profile_fd = profile_file_fd_ != kInvalidFd;
909 if (have_profile_file && have_profile_fd) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000910 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200911 }
912
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700913 if (have_profile_file || have_profile_fd) {
914 if (compiled_classes_filename_ != nullptr ||
915 compiled_classes_zip_filename_ != nullptr ||
916 image_classes_filename_ != nullptr ||
917 image_classes_zip_filename_ != nullptr) {
918 Usage("Profile based image creation is not supported with image or compiled classes");
919 }
920 }
921
Roland Levillain9ec5e222015-08-17 20:18:41 +0100922 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800923 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800924 }
925
926 // If no instruction set feature was given, use the default one for the target
927 // instruction set.
928 if (instruction_set_features_.get() == nullptr) {
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800929 instruction_set_features_ = InstructionSetFeatures::FromVariant(
930 instruction_set_, "default", &parser_options->error_msg);
Ian Rogersd582fa42014-11-05 23:46:43 -0800931 if (instruction_set_features_.get() == nullptr) {
932 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100933 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800934 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800935 }
936
937 if (instruction_set_ == kRuntimeISA) {
938 std::unique_ptr<const InstructionSetFeatures> runtime_features(
939 InstructionSetFeatures::FromCppDefines());
940 if (!instruction_set_features_->Equals(runtime_features.get())) {
941 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
942 << *instruction_set_features_ << ") and those of dex2oat executable ("
943 << *runtime_features <<") for the command line:\n"
944 << CommandLine();
945 }
946 }
947
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000948 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000949 compiler_options_->inline_max_code_units_ = CompilerOptions::kDefaultInlineMaxCodeUnits;
Roland Levillaina215b952015-08-07 11:38:32 +0100950 }
951
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800952 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800953 // Set the compilation target's implicit checks options.
954 switch (instruction_set_) {
955 case kArm:
956 case kThumb2:
957 case kArm64:
958 case kX86:
959 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700960 case kMips:
961 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000962 compiler_options_->implicit_null_checks_ = true;
963 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800964 break;
965
966 default:
967 // Defaults are correct.
968 break;
969 }
970
Jeff Hao436183f2016-01-12 16:36:50 -0800971 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800972 Usage("--multi-image can only be used when creating boot images");
973 }
Jeff Hao436183f2016-01-12 16:36:50 -0800974 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800975 Usage("--multi-image cannot be used with multiple image names");
976 }
977
978 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
979 if (!kIsTargetBuild && IsBootImage()) {
980 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800981 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800982 }
983 }
984
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800985 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100986 if (parser_options->watch_dog_enabled) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800987 int64_t timeout = parser_options->watch_dog_timeout_in_ms > 0
988 ? parser_options->watch_dog_timeout_in_ms
989 : WatchDog::kDefaultWatchdogTimeoutInMS;
990 watchdog_.reset(new WatchDog(timeout));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800991 }
992
993 // Fill some values into the key-value store for the oat header.
994 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800995
Roland Levillainb81e9e92017-04-20 17:35:32 +0100996 // Automatically force determinism for the boot image in a host build if read barriers
997 // are enabled, or if the default GC is CMS or MS. When the default GC is CMS
998 // (Concurrent Mark-Sweep), the GC is switched to a non-concurrent one by passing the
999 // option `-Xgc:nonconcurrent` (see below).
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001000 if (!kIsTargetBuild && IsBootImage()) {
1001 if (SupportsDeterministicCompilation()) {
1002 force_determinism_ = true;
1003 } else {
1004 LOG(WARNING) << "Deterministic compilation is disabled.";
1005 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001006 }
1007 compiler_options_->force_determinism_ = force_determinism_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07001008
1009 if (passes_to_run_filename_ != nullptr) {
1010 passes_to_run_.reset(ReadCommentedInputFromFile<std::vector<std::string>>(
1011 passes_to_run_filename_,
1012 nullptr)); // No post-processing.
1013 if (passes_to_run_.get() == nullptr) {
1014 Usage("Failed to read list of passes to run.");
1015 }
1016 }
1017 compiler_options_->passes_to_run_ = passes_to_run_.get();
Roland Levillain9ec5e222015-08-17 20:18:41 +01001018 }
1019
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001020 static bool SupportsDeterministicCompilation() {
Roland Levillainb81e9e92017-04-20 17:35:32 +01001021 return (kUseReadBarrier ||
1022 gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
1023 gc::kCollectorTypeDefault == gc::kCollectorTypeMS);
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001024 }
1025
Jeff Hao436183f2016-01-12 16:36:50 -08001026 void ExpandOatAndImageFilenames() {
1027 std::string base_oat = oat_filenames_[0];
1028 size_t last_oat_slash = base_oat.rfind('/');
1029 if (last_oat_slash == std::string::npos) {
1030 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
1031 }
1032 // We also need to honor path components that were encoded through '@'. Otherwise the loading
1033 // code won't be able to find the images.
1034 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
1035 last_oat_slash = base_oat.rfind('@');
1036 }
1037 base_oat = base_oat.substr(0, last_oat_slash + 1);
1038
1039 std::string base_img = image_filenames_[0];
1040 size_t last_img_slash = base_img.rfind('/');
1041 if (last_img_slash == std::string::npos) {
1042 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
1043 }
1044 // We also need to honor path components that were encoded through '@'. Otherwise the loading
1045 // code won't be able to find the images.
1046 if (base_img.find('@', last_img_slash) != std::string::npos) {
1047 last_img_slash = base_img.rfind('@');
1048 }
1049
1050 // Get the prefix, which is the primary image name (without path components). Strip the
1051 // extension.
1052 std::string prefix = base_img.substr(last_img_slash + 1);
1053 if (prefix.rfind('.') != std::string::npos) {
1054 prefix = prefix.substr(0, prefix.rfind('.'));
1055 }
1056 if (!prefix.empty()) {
1057 prefix = prefix + "-";
1058 }
1059
1060 base_img = base_img.substr(0, last_img_slash + 1);
1061
1062 // Note: we have some special case here for our testing. We have to inject the differentiating
1063 // parts for the different core images.
1064 std::string infix; // Empty infix by default.
1065 {
1066 // Check the first name.
1067 std::string dex_file = oat_filenames_[0];
1068 size_t last_dex_slash = dex_file.rfind('/');
1069 if (last_dex_slash != std::string::npos) {
1070 dex_file = dex_file.substr(last_dex_slash + 1);
1071 }
1072 size_t last_dex_dot = dex_file.rfind('.');
1073 if (last_dex_dot != std::string::npos) {
1074 dex_file = dex_file.substr(0, last_dex_dot);
1075 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001076 if (android::base::StartsWith(dex_file, "core-")) {
Jeff Hao436183f2016-01-12 16:36:50 -08001077 infix = dex_file.substr(strlen("core"));
1078 }
1079 }
1080
bowen_lai8bd36c02016-10-12 13:28:55 +08001081 std::string base_symbol_oat;
1082 if (!oat_unstripped_.empty()) {
1083 base_symbol_oat = oat_unstripped_[0];
1084 size_t last_symbol_oat_slash = base_symbol_oat.rfind('/');
1085 if (last_symbol_oat_slash == std::string::npos) {
1086 Usage("--multi-image used with unusable symbol filename %s", base_symbol_oat.c_str());
1087 }
1088 base_symbol_oat = base_symbol_oat.substr(0, last_symbol_oat_slash + 1);
1089 }
1090
1091 const size_t num_expanded_files = 2 + (base_symbol_oat.empty() ? 0 : 1);
1092 char_backing_storage_.reserve((dex_locations_.size() - 1) * num_expanded_files);
Ben Gruvera0fc3262016-09-30 13:10:42 -07001093
Jeff Hao436183f2016-01-12 16:36:50 -08001094 // Now create the other names. Use a counted loop to skip the first one.
1095 for (size_t i = 1; i < dex_locations_.size(); ++i) {
1096 // TODO: Make everything properly std::string.
1097 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
1098 char_backing_storage_.push_back(base_img + image_name);
1099 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1100
1101 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
1102 char_backing_storage_.push_back(base_oat + oat_name);
1103 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
bowen_lai8bd36c02016-10-12 13:28:55 +08001104
1105 if (!base_symbol_oat.empty()) {
1106 char_backing_storage_.push_back(base_symbol_oat + oat_name);
1107 oat_unstripped_.push_back((char_backing_storage_.end() - 1)->c_str());
1108 }
Jeff Hao436183f2016-01-12 16:36:50 -08001109 }
1110 }
1111
Andreas Gampe8994a042015-12-30 19:03:17 +00001112 // Modify the input string in the following way:
1113 // 0) Assume input is /a/b/c.d
1114 // 1) Strip the path -> c.d
1115 // 2) Inject prefix p -> pc.d
1116 // 3) Inject infix i -> pci.d
1117 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001118 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001119 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001120 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001121 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001122 size_t last_dex_slash = in.rfind('/');
1123 if (last_dex_slash != std::string::npos) {
1124 in = in.substr(last_dex_slash + 1);
1125 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001126 if (!prefix.empty()) {
1127 in = prefix + in;
1128 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001129 if (!infix.empty()) {
1130 // Inject infix.
1131 size_t last_dot = in.rfind('.');
1132 if (last_dot != std::string::npos) {
1133 in.insert(last_dot, infix);
1134 }
1135 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001136 if (android::base::EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001137 in = in.substr(0, in.length() - strlen(".jar")) +
1138 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001139 }
1140 return in;
1141 }
1142
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001143 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001144 std::ostringstream oss;
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07001145 if (!avoid_storing_invocation_) {
1146 for (int i = 0; i < argc; ++i) {
1147 if (i > 0) {
1148 oss << ' ';
1149 }
1150 oss << argv[i];
Roland Levillain9ec5e222015-08-17 20:18:41 +01001151 }
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07001152 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1153 oss.str(""); // Reset.
Roland Levillain9ec5e222015-08-17 20:18:41 +01001154 }
Roland Levillain9ec5e222015-08-17 20:18:41 +01001155 oss << kRuntimeISA;
1156 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1157 key_value_store_->Put(
1158 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001159 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001160 key_value_store_->Put(
1161 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001162 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Srbecky5d950762016-03-07 20:47:29 +00001163 key_value_store_->Put(
1164 OatHeader::kNativeDebuggableKey,
David Srbecky346dc992016-03-13 22:00:07 +00001165 compiler_options_->GetNativeDebuggable() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe29d38e72016-03-23 15:31:51 +00001166 key_value_store_->Put(OatHeader::kCompilerFilter,
1167 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
Andreas Gampef8cd8902017-01-18 16:05:01 -08001168 key_value_store_->Put(OatHeader::kConcurrentCopying,
1169 kUseReadBarrier ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001170 }
1171
1172 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1173 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1174 // returns, arguments have been successfully parsed.
1175 void ParseArgs(int argc, char** argv) {
1176 original_argc = argc;
1177 original_argv = argv;
1178
Andreas Gampe51d80cc2017-06-21 21:05:13 -07001179 InitLogging(argv, Runtime::Abort);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001180
1181 // Skip over argv[0].
1182 argv++;
1183 argc--;
1184
1185 if (argc == 0) {
1186 Usage("No arguments specified");
1187 }
1188
1189 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001190 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001191
1192 for (int i = 0; i < argc; i++) {
1193 const StringPiece option(argv[i]);
1194 const bool log_options = false;
1195 if (log_options) {
1196 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1197 }
1198 if (option.starts_with("--dex-file=")) {
1199 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1200 } else if (option.starts_with("--dex-location=")) {
1201 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1202 } else if (option.starts_with("--zip-fd=")) {
1203 ParseZipFd(option);
1204 } else if (option.starts_with("--zip-location=")) {
1205 zip_location_ = option.substr(strlen("--zip-location=")).data();
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001206 } else if (option.starts_with("--input-vdex-fd=")) {
1207 ParseInputVdexFd(option);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001208 } else if (option.starts_with("--input-vdex=")) {
1209 input_vdex_ = option.substr(strlen("--input-vdex=")).data();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01001210 } else if (option.starts_with("--output-vdex=")) {
1211 output_vdex_ = option.substr(strlen("--output-vdex=")).data();
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001212 } else if (option.starts_with("--output-vdex-fd=")) {
1213 ParseOutputVdexFd(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001214 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001215 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001216 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001217 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001218 } else if (option.starts_with("--oat-fd=")) {
1219 ParseOatFd(option);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001220 } else if (option.starts_with("--oat-location=")) {
1221 oat_location_ = option.substr(strlen("--oat-location=")).data();
Roland Levillain9ec5e222015-08-17 20:18:41 +01001222 } else if (option == "--watch-dog") {
1223 parser_options->watch_dog_enabled = true;
1224 } else if (option == "--no-watch-dog") {
1225 parser_options->watch_dog_enabled = false;
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001226 } else if (option.starts_with("--watchdog-timeout=")) {
1227 ParseIntOption(option,
1228 "--watchdog-timeout",
1229 &parser_options->watch_dog_timeout_in_ms,
1230 Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001231 } else if (option.starts_with("-j")) {
1232 ParseJ(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001233 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001235 } else if (option.starts_with("--image-classes=")) {
1236 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1237 } else if (option.starts_with("--image-classes-zip=")) {
1238 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001239 } else if (option.starts_with("--image-format=")) {
1240 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001241 } else if (option.starts_with("--compiled-classes=")) {
1242 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1243 } else if (option.starts_with("--compiled-classes-zip=")) {
1244 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1245 } else if (option.starts_with("--compiled-methods=")) {
1246 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1247 } else if (option.starts_with("--compiled-methods-zip=")) {
1248 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07001249 } else if (option.starts_with("--run-passes=")) {
1250 passes_to_run_filename_ = option.substr(strlen("--run-passes=")).data();
Roland Levillain9ec5e222015-08-17 20:18:41 +01001251 } else if (option.starts_with("--base=")) {
1252 ParseBase(option);
1253 } else if (option.starts_with("--boot-image=")) {
1254 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1255 } else if (option.starts_with("--android-root=")) {
1256 android_root_ = option.substr(strlen("--android-root=")).data();
1257 } else if (option.starts_with("--instruction-set=")) {
1258 ParseInstructionSet(option);
1259 } else if (option.starts_with("--instruction-set-variant=")) {
1260 ParseInstructionSetVariant(option, parser_options.get());
1261 } else if (option.starts_with("--instruction-set-features=")) {
1262 ParseInstructionSetFeatures(option, parser_options.get());
1263 } else if (option.starts_with("--compiler-backend=")) {
1264 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001265 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001266 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001267 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001268 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001269 } else if (option == "--host") {
1270 is_host_ = true;
1271 } else if (option == "--runtime-arg") {
1272 if (++i >= argc) {
1273 Usage("Missing required argument for --runtime-arg");
1274 }
1275 if (log_options) {
1276 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1277 }
1278 runtime_args_.push_back(argv[i]);
1279 } else if (option == "--dump-timing") {
1280 dump_timing_ = true;
1281 } else if (option == "--dump-passes") {
1282 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001283 } else if (option == "--dump-stats") {
1284 dump_stats_ = true;
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07001285 } else if (option == "--avoid-storing-invocation") {
1286 avoid_storing_invocation_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001287 } else if (option.starts_with("--swap-file=")) {
1288 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1289 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001290 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
Andreas Gampee1459ae2016-06-29 09:36:30 -07001291 } else if (option.starts_with("--swap-dex-size-threshold=")) {
1292 ParseUintOption(option,
1293 "--swap-dex-size-threshold",
1294 &min_dex_file_cumulative_size_for_swap_,
1295 Usage);
1296 } else if (option.starts_with("--swap-dex-count-threshold=")) {
1297 ParseUintOption(option,
1298 "--swap-dex-count-threshold",
1299 &min_dex_files_for_swap_,
1300 Usage);
Andreas Gampe67f02822016-06-24 21:05:23 -07001301 } else if (option.starts_with("--very-large-app-threshold=")) {
1302 ParseUintOption(option,
1303 "--very-large-app-threshold",
1304 &very_large_threshold_,
1305 Usage);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001306 } else if (option.starts_with("--app-image-file=")) {
1307 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1308 } else if (option.starts_with("--app-image-fd=")) {
1309 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001310 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001311 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001312 } else if (option.starts_with("--no-inline-from=")) {
1313 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001314 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001315 if (!SupportsDeterministicCompilation()) {
Roland Levillainb81e9e92017-04-20 17:35:32 +01001316 Usage("Option --force-determinism requires read barriers or a CMS/MS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001317 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001318 force_determinism_ = true;
Jeff Hao16d48432017-04-05 17:05:46 -07001319 } else if (option.starts_with("--classpath-dir=")) {
1320 classpath_dir_ = option.substr(strlen("--classpath-dir=")).data();
Calin Juravle1ce70852017-06-28 10:59:03 -07001321 } else if (option.starts_with("--class-loader-context=")) {
1322 class_loader_context_ = ClassLoaderContext::Create(
1323 option.substr(strlen("--class-loader-context=")).data());
Calin Juravle19915892017-08-03 17:10:36 +00001324 if (class_loader_context_ == nullptr) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001325 Usage("Option --class-loader-context has an incorrect format: %s", option.data());
1326 }
Jeff Haoc23b0c02017-07-27 18:19:38 -07001327 } else if (option.starts_with("--dirty-image-objects=")) {
1328 dirty_image_objects_filename_ = option.substr(strlen("--dirty-image-objects=")).data();
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001329 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001330 Usage("Unknown argument %s", option.data());
1331 }
1332 }
1333
Jeff Hao436183f2016-01-12 16:36:50 -08001334 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001335
1336 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001337 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001338 }
1339
Jeff Haodcdc85b2015-12-04 14:06:18 -08001340 // Check whether the oat output files are writable, and open them for later. Also open a swap
1341 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001342 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001343 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1344 PruneNonExistentDexFiles();
1345
Jeff Hao436183f2016-01-12 16:36:50 -08001346 // Expand oat and image filenames for multi image.
1347 if (IsBootImage() && multi_image_) {
1348 ExpandOatAndImageFilenames();
1349 }
1350
David Brazdil7b49e6c2016-09-01 11:06:18 +01001351 // OAT and VDEX file handling
David Brazdil7b49e6c2016-09-01 11:06:18 +01001352 if (oat_fd_ == -1) {
1353 DCHECK(!oat_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001354 for (const char* oat_filename : oat_filenames_) {
1355 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1356 if (oat_file.get() == nullptr) {
1357 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1358 return false;
1359 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001360 if (fchmod(oat_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001361 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1362 oat_file->Erase();
1363 return false;
1364 }
1365 oat_files_.push_back(std::move(oat_file));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001366 DCHECK_EQ(input_vdex_fd_, -1);
1367 if (!input_vdex_.empty()) {
1368 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001369 input_vdex_file_ = VdexFile::Open(input_vdex_,
1370 /* writable */ false,
1371 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001372 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001373 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001374 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001375
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001376 DCHECK_EQ(output_vdex_fd_, -1);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01001377 std::string vdex_filename = output_vdex_.empty()
1378 ? ReplaceFileExtension(oat_filename, "vdex")
1379 : output_vdex_;
1380 if (vdex_filename == input_vdex_ && output_vdex_.empty()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001381 update_input_vdex_ = true;
1382 std::unique_ptr<File> vdex_file(OS::OpenFileReadWrite(vdex_filename.c_str()));
1383 vdex_files_.push_back(std::move(vdex_file));
1384 } else {
1385 std::unique_ptr<File> vdex_file(OS::CreateEmptyFile(vdex_filename.c_str()));
1386 if (vdex_file.get() == nullptr) {
1387 PLOG(ERROR) << "Failed to open vdex file: " << vdex_filename;
1388 return false;
1389 }
1390 if (fchmod(vdex_file->Fd(), 0644) != 0) {
1391 PLOG(ERROR) << "Failed to make vdex file world readable: " << vdex_filename;
1392 vdex_file->Erase();
1393 return false;
1394 }
1395 vdex_files_.push_back(std::move(vdex_file));
David Brazdil7b49e6c2016-09-01 11:06:18 +01001396 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001397 }
1398 } else {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001399 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, /* check_usage */ true));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 if (oat_file.get() == nullptr) {
1401 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1402 return false;
1403 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001404 oat_file->DisableAutoClose();
1405 if (oat_file->SetLength(0) != 0) {
1406 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1407 }
1408 oat_files_.push_back(std::move(oat_file));
1409
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001410 if (input_vdex_fd_ != -1) {
1411 struct stat s;
1412 int rc = TEMP_FAILURE_RETRY(fstat(input_vdex_fd_, &s));
1413 if (rc == -1) {
1414 PLOG(WARNING) << "Failed getting length of vdex file";
1415 } else {
1416 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001417 input_vdex_file_ = VdexFile::Open(input_vdex_fd_,
1418 s.st_size,
1419 "vdex",
1420 /* writable */ false,
1421 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001422 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001423 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001424 // If there's any problem with the passed vdex, just warn and proceed
1425 // without it.
1426 if (input_vdex_file_ == nullptr) {
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001427 PLOG(WARNING) << "Failed opening vdex file: " << error_msg;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001428 }
1429 }
1430 }
1431
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001432 DCHECK_NE(output_vdex_fd_, -1);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001433 std::string vdex_location = ReplaceFileExtension(oat_location_, "vdex");
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001434 std::unique_ptr<File> vdex_file(new File(output_vdex_fd_, vdex_location, /* check_usage */ true));
David Brazdil7b49e6c2016-09-01 11:06:18 +01001435 if (vdex_file.get() == nullptr) {
1436 PLOG(ERROR) << "Failed to create vdex file: " << vdex_location;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001437 return false;
1438 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001439 vdex_file->DisableAutoClose();
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001440 if (input_vdex_file_ != nullptr && output_vdex_fd_ == input_vdex_fd_) {
1441 update_input_vdex_ = true;
1442 } else {
1443 if (vdex_file->SetLength(0) != 0) {
1444 PLOG(ERROR) << "Truncating vdex file " << vdex_location << " failed.";
1445 return false;
1446 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001447 }
1448 vdex_files_.push_back(std::move(vdex_file));
1449
Jeff Haodcdc85b2015-12-04 14:06:18 -08001450 oat_filenames_.push_back(oat_location_.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001451 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001452
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001453 // If we're updating in place a vdex file, be defensive and put an invalid vdex magic in case
1454 // dex2oat gets killed.
1455 // Note: we're only invalidating the magic data in the file, as dex2oat needs the rest of
1456 // the information to remain valid.
1457 if (update_input_vdex_) {
Andreas Gampe8bdda5a2017-06-08 15:30:36 -07001458 std::unique_ptr<BufferedOutputStream> vdex_out = std::make_unique<BufferedOutputStream>(
1459 std::make_unique<FileOutputStream>(vdex_files_.back().get()));
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001460 if (!vdex_out->WriteFully(&VdexFile::Header::kVdexInvalidMagic,
1461 arraysize(VdexFile::Header::kVdexInvalidMagic))) {
1462 PLOG(ERROR) << "Failed to invalidate vdex header. File: " << vdex_out->GetLocation();
1463 return false;
1464 }
1465
1466 if (!vdex_out->Flush()) {
1467 PLOG(ERROR) << "Failed to flush stream after invalidating header of vdex file."
1468 << " File: " << vdex_out->GetLocation();
1469 return false;
1470 }
1471 }
1472
David Brazdil7b49e6c2016-09-01 11:06:18 +01001473 // Swap file handling
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001474 //
1475 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1476 // that we can use for swap.
1477 //
1478 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1479 // will immediately unlink to satisfy the swap fd assumption.
1480 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1481 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1482 if (swap_file.get() == nullptr) {
1483 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1484 return false;
1485 }
1486 swap_fd_ = swap_file->Fd();
1487 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1488 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1489 // released immediately.
1490 unlink(swap_file_name_.c_str());
1491 }
Jeff Hao436183f2016-01-12 16:36:50 -08001492
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001493 return true;
1494 }
1495
David Brazdil7b49e6c2016-09-01 11:06:18 +01001496 void EraseOutputFiles() {
1497 for (auto& files : { &vdex_files_, &oat_files_ }) {
1498 for (size_t i = 0; i < files->size(); ++i) {
1499 if ((*files)[i].get() != nullptr) {
1500 (*files)[i]->Erase();
1501 (*files)[i].reset();
1502 }
1503 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001504 }
Andreas Gampea650e702014-12-03 14:28:02 -08001505 }
1506
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001507 void LoadClassProfileDescriptors() {
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -07001508 if (profile_compilation_info_ != nullptr && IsImage()) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001509 Runtime* runtime = Runtime::Current();
1510 CHECK(runtime != nullptr);
Mathieu Chartier0b490842016-05-25 15:05:59 -07001511 // Filter out class path classes since we don't want to include these in the image.
Mathieu Chartier4f342b02017-07-21 17:12:39 -07001512 image_classes_.reset(
1513 new std::unordered_set<std::string>(
1514 profile_compilation_info_->GetClassDescriptors(dex_files_)));
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001515 VLOG(compiler) << "Loaded " << image_classes_->size()
1516 << " image class descriptors from profile";
1517 if (VLOG_IS_ON(compiler)) {
1518 for (const std::string& s : *image_classes_) {
1519 LOG(INFO) << "Image class " << s;
1520 }
1521 }
1522 }
1523 }
1524
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001525 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1526 // boot class path.
Andreas Gampef7882972017-03-20 16:35:24 -07001527 dex2oat::ReturnCode Setup() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001528 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001529
Jeff Haoc23b0c02017-07-27 18:19:38 -07001530 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods() ||
1531 !PrepareDirtyObjects()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001532 return dex2oat::ReturnCode::kOther;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001534
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001535 // Verification results are null since we don't know if we will need them yet as the compler
1536 // filter may change.
Andreas Gampe4585f872015-03-27 23:45:15 -07001537 callbacks_.reset(new QuickCompilerCallbacks(
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001538 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001539 CompilerCallbacks::CallbackMode::kCompileBootImage :
1540 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001541
Vladimir Marko49b0f452015-12-10 13:49:19 +00001542 RuntimeArgumentMap runtime_options;
Mathieu Chartier46331a62017-07-21 09:49:10 -07001543 if (!PrepareRuntimeOptions(&runtime_options, callbacks_.get())) {
Andreas Gampef7882972017-03-20 16:35:24 -07001544 return dex2oat::ReturnCode::kOther;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001545 }
1546
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001547 CreateOatWriters();
1548 if (!AddDexFileSources()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001549 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001550 }
1551
1552 if (IsBootImage() && image_filenames_.size() > 1) {
1553 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1554 // We need this for the multi-image case.
Mathieu Chartier866d8742016-09-21 15:24:18 -07001555 key_value_store_->Put(OatHeader::kBootClassPathKey,
1556 gc::space::ImageSpace::GetMultiImageBootClassPath(dex_locations_,
1557 oat_filenames_,
1558 image_filenames_));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001559 }
1560
1561 if (!IsBootImage()) {
1562 // When compiling an app, create the runtime early to retrieve
1563 // the image location key needed for the oat header.
1564 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampef7882972017-03-20 16:35:24 -07001565 return dex2oat::ReturnCode::kCreateRuntime;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001566 }
1567
Andreas Gampe29d38e72016-03-23 15:31:51 +00001568 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001569 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1570 std::vector<gc::space::ImageSpace*> image_spaces =
1571 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Richard Uhlerbc26b722017-03-10 14:27:10 +00001572 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001573 image_file_location_oat_data_begin_ =
1574 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1575 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1576 // Store the boot image filename(s).
1577 std::vector<std::string> image_filenames;
1578 for (const gc::space::ImageSpace* image_space : image_spaces) {
1579 image_filenames.push_back(image_space->GetImageFilename());
1580 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001581 std::string image_file_location = android::base::Join(image_filenames, ':');
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001582 if (!image_file_location.empty()) {
1583 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1584 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001585 } else {
1586 image_file_location_oat_checksum_ = 0u;
1587 image_file_location_oat_data_begin_ = 0u;
1588 image_patch_delta_ = 0;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001589 }
1590
1591 // Open dex files for class path.
Calin Juravle19915892017-08-03 17:10:36 +00001592
Calin Juravle1ce70852017-06-28 10:59:03 -07001593 if (class_loader_context_ == nullptr) {
Calin Juravle19915892017-08-03 17:10:36 +00001594 // If no context was specified use the default one (which is an empty PathClassLoader).
1595 class_loader_context_ = std::unique_ptr<ClassLoaderContext>(ClassLoaderContext::Default());
Jeff Haof0192c82016-03-28 20:39:50 -07001596 }
Calin Juravle19915892017-08-03 17:10:36 +00001597
Calin Juravle1ce70852017-06-28 10:59:03 -07001598 DCHECK_EQ(oat_writers_.size(), 1u);
1599
1600 // Note: Ideally we would reject context where the source dex files are also
1601 // specified in the classpath (as it doesn't make sense). However this is currently
1602 // needed for non-prebuild tests and benchmarks which expects on the fly compilation.
1603 // Also, for secondary dex files we do not have control on the actual classpath.
1604 // Instead of aborting, remove all the source location from the context classpaths.
1605 if (class_loader_context_->RemoveLocationsFromClassPaths(
1606 oat_writers_[0]->GetSourceLocations())) {
1607 LOG(WARNING) << "The source files to be compiled are also in the classpath.";
1608 }
1609
1610 // We need to open the dex files before encoding the context in the oat file.
1611 // (because the encoding adds the dex checksum...)
1612 // TODO(calin): consider redesigning this so we don't have to open the dex files before
1613 // creating the actual class loader.
1614 if (!class_loader_context_->OpenDexFiles(runtime_->GetInstructionSet(), classpath_dir_)) {
1615 // Do not abort if we couldn't open files from the classpath. They might be
1616 // apks without dex files and right now are opening flow will fail them.
1617 LOG(WARNING) << "Failed to open classpath dex files";
1618 }
1619
1620 // Store the class loader context in the oat header.
1621 key_value_store_->Put(OatHeader::kClassPathKey,
1622 class_loader_context_->EncodeContextForOatFile(classpath_dir_));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001623 }
1624
1625 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001626 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001627 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1628 rodata_.reserve(oat_writers_.size());
1629 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1630 rodata_.push_back(elf_writers_[i]->StartRoData());
1631 // Unzip or copy dex files straight to the oat file.
1632 std::unique_ptr<MemMap> opened_dex_files_map;
1633 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001634 // No need to verify the dex file for:
Mathieu Chartier11b3df32017-02-21 13:41:54 -08001635 // 1) Dexlayout since it does the verification. It also may not pass the verification since
1636 // we don't update the dex checksum.
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001637 // 2) when we have a vdex file, which means it was already verified.
Mathieu Chartier11b3df32017-02-21 13:41:54 -08001638 const bool verify = !DoDexLayoutOptimizations() && (input_vdex_file_ == nullptr);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001639 if (!oat_writers_[i]->WriteAndOpenDexFiles(
1640 kIsVdexEnabled ? vdex_files_[i].get() : oat_files_[i].get(),
1641 rodata_.back(),
1642 instruction_set_,
1643 instruction_set_features_.get(),
1644 key_value_store_.get(),
Jeff Hao042e8982016-10-19 11:17:11 -07001645 verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001646 update_input_vdex_,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001647 &opened_dex_files_map,
1648 &opened_dex_files)) {
Andreas Gampef7882972017-03-20 16:35:24 -07001649 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001650 }
1651 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1652 if (opened_dex_files_map != nullptr) {
1653 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1654 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001655 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001656 opened_dex_files_.push_back(std::move(dex_file));
1657 }
1658 } else {
1659 DCHECK(opened_dex_files.empty());
1660 }
1661 }
1662 }
1663
1664 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
Andreas Gampe7386da42016-06-08 18:18:47 -07001665
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001666 // If we need to downgrade the compiler-filter for size reasons.
1667 if (!IsBootImage() && IsVeryLarge(dex_files_)) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001668 // If we need to downgrade the compiler-filter for size reasons, do that early before we read
1669 // it below for creating verification callbacks.
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001670 if (!CompilerFilter::IsAsGoodAs(kLargeAppFilter, compiler_options_->GetCompilerFilter())) {
1671 LOG(INFO) << "Very large app, downgrading to verify.";
1672 // Note: this change won't be reflected in the key-value store, as that had to be
1673 // finalized before loading the dex files. This setup is currently required
1674 // to get the size from the DexFile objects.
1675 // TODO: refactor. b/29790079
1676 compiler_options_->SetCompilerFilter(kLargeAppFilter);
1677 }
1678 }
1679
1680 if (CompilerFilter::IsAnyCompilationEnabled(compiler_options_->GetCompilerFilter())) {
1681 // Only modes with compilation require verification results, do this here instead of when we
1682 // create the compilation callbacks since the compilation mode may have been changed by the
1683 // very large app logic.
1684 // Avoiding setting the verification results saves RAM by not adding the dex files later in
1685 // the function.
1686 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1687 callbacks_->SetVerificationResults(verification_results_.get());
1688 }
1689
Andreas Gampe7386da42016-06-08 18:18:47 -07001690 // We had to postpone the swap decision till now, as this is the point when we actually
1691 // know about the dex files we're going to use.
1692
1693 // Make sure that we didn't create the driver, yet.
1694 CHECK(driver_ == nullptr);
1695 // If we use a swap file, ensure we are above the threshold to make it necessary.
1696 if (swap_fd_ != -1) {
1697 if (!UseSwap(IsBootImage(), dex_files_)) {
1698 close(swap_fd_);
1699 swap_fd_ = -1;
1700 VLOG(compiler) << "Decided to run without swap.";
1701 } else {
1702 LOG(INFO) << "Large app, accepted running with swap.";
1703 }
1704 }
1705 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001706 if (IsBootImage()) {
1707 // For boot image, pass opened dex files to the Runtime::Create().
1708 // Note: Runtime acquires ownership of these dex files.
1709 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001710 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampef7882972017-03-20 16:35:24 -07001711 return dex2oat::ReturnCode::kOther;
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001712 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001713 }
1714
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 // If we're doing the image, override the compiler filter to force full compilation. Must be
1716 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1717 // compilation of class initializers.
1718 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001719 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001720 WellKnownClasses::Init(self->GetJniEnv());
1721
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001722 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001723 constexpr bool kSaveDexInput = false;
1724 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001725 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001726 }
1727 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001728
1729 // Ensure opened dex files are writable for dex-to-dex transformations.
1730 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1731 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1732 PLOG(ERROR) << "Failed to make .dex files writeable.";
Andreas Gampef7882972017-03-20 16:35:24 -07001733 return dex2oat::ReturnCode::kOther;
Vladimir Marko919f5532016-01-20 19:13:01 +00001734 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001735 }
1736
Mathieu Chartier72041a02017-07-14 18:23:25 -07001737 // Verification results are only required for modes that have any compilation. Avoid
1738 // adding the dex files if possible to prevent allocating large arrays.
1739 if (verification_results_ != nullptr) {
1740 for (const auto& dex_file : dex_files_) {
1741 // Pre-register dex files so that we can access verification results without locks during
1742 // compilation and verification.
Mathieu Chartier0733dc82017-07-17 14:05:28 -07001743 verification_results_->AddDexFile(dex_file);
1744 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001745 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001746
Andreas Gampef7882972017-03-20 16:35:24 -07001747 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001748 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001749
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001750 // If we need to keep the oat file open for the image writer.
1751 bool ShouldKeepOatFileOpen() const {
1752 return IsImage() && oat_fd_ != kInvalidFd;
1753 }
1754
Mathieu Chartier72041a02017-07-14 18:23:25 -07001755 // Doesn't return the class loader since it's not meant to be used for image compilation.
1756 void CompileDexFilesIndividually() {
1757 CHECK(!IsImage()) << "Not supported with image";
1758 for (const DexFile* dex_file : dex_files_) {
1759 std::vector<const DexFile*> dex_files(1u, dex_file);
1760 VLOG(compiler) << "Compiling " << dex_file->GetLocation();
1761 jobject class_loader = CompileDexFiles(dex_files);
1762 CHECK(class_loader != nullptr);
1763 ScopedObjectAccess soa(Thread::Current());
1764 // Unload class loader to free RAM.
1765 jweak weak_class_loader = soa.Env()->vm->AddWeakGlobalRef(
1766 soa.Self(),
1767 soa.Decode<mirror::ClassLoader>(class_loader));
1768 soa.Env()->vm->DeleteGlobalRef(soa.Self(), class_loader);
1769 runtime_->GetHeap()->CollectGarbage(/*clear_soft_references*/ true);
1770 ObjPtr<mirror::ClassLoader> decoded_weak = soa.Decode<mirror::ClassLoader>(weak_class_loader);
1771 if (decoded_weak != nullptr) {
1772 LOG(FATAL) << "Failed to unload class loader, path from root set: "
1773 << runtime_->GetHeap()->GetVerification()->FirstPathFromRootSet(decoded_weak);
1774 }
1775 VLOG(compiler) << "Unloaded classloader";
1776 }
1777 }
1778
1779 bool ShouldCompileDexFilesIndividually() const {
Nicolas Geoffraya6fc7872017-08-14 11:29:22 +01001780 // Compile individually if we are:
1781 // 1. not building an image,
1782 // 2. not verifying a vdex file,
1783 // 3. using multidex,
1784 // 4. not doing any AOT compilation.
1785 // This means extract, no-vdex verify, and quicken, will use the individual compilation
1786 // mode (to reduce RAM used by the compiler).
Mathieu Chartier72041a02017-07-14 18:23:25 -07001787 return !IsImage() &&
Nicolas Geoffraya6fc7872017-08-14 11:29:22 +01001788 !update_input_vdex_ &&
Mathieu Chartier72041a02017-07-14 18:23:25 -07001789 dex_files_.size() > 1 &&
Mathieu Chartier6a2b67b2017-08-08 15:09:29 -07001790 !CompilerFilter::IsAotCompilationEnabled(compiler_options_->GetCompilerFilter());
Mathieu Chartier72041a02017-07-14 18:23:25 -07001791 }
1792
1793 // Set up and create the compiler driver and then invoke it to compile all the dex files.
1794 jobject Compile() {
1795 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1796
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001797 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1798 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001799
Vladimir Marko47496c22016-01-27 16:15:08 +00001800 // Find the dex files we should not inline from.
Vladimir Marko47496c22016-01-27 16:15:08 +00001801 std::vector<std::string> no_inline_filters;
1802 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001803
1804 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001805 const std::string core_oj = "core-oj";
1806 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1807 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001808 }
1809
Vladimir Marko47496c22016-01-27 16:15:08 +00001810 if (!no_inline_filters.empty()) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001811 std::vector<const DexFile*> class_path_files;
1812 if (!IsBootImage()) {
1813 // The class loader context is used only for apps.
1814 class_path_files = class_loader_context_->FlattenOpenedDexFiles();
1815 }
1816
Jeff Haodcdc85b2015-12-04 14:06:18 -08001817 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1818 &class_linker->GetBootClassPath(),
1819 &class_path_files,
1820 &dex_files_
1821 };
1822 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001824 for (const std::string& filter : no_inline_filters) {
1825 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
Calin Juravlea308a322017-07-18 16:51:51 -07001826 // allows tests to specify <test-dexfile>!classes2.dex if needed but if the
Vladimir Marko47496c22016-01-27 16:15:08 +00001827 // base location passes the StartsWith() test, so do all extra locations.
1828 std::string dex_location = dex_file->GetLocation();
1829 if (filter.find('/') == std::string::npos) {
1830 // The filter does not contain the path. Remove the path from dex_location as well.
1831 size_t last_slash = dex_file->GetLocation().rfind('/');
1832 if (last_slash != std::string::npos) {
1833 dex_location = dex_location.substr(last_slash + 1);
1834 }
1835 }
1836
Andreas Gampe9186ced2016-12-12 14:28:21 -08001837 if (android::base::StartsWith(dex_location, filter.c_str())) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001838 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1839 no_inline_from_dex_files_.push_back(dex_file);
1840 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001841 }
1842 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001843 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001844 }
1845 if (!no_inline_from_dex_files_.empty()) {
1846 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001847 }
1848 }
1849
Vladimir Marko307dac92015-10-20 11:20:09 +01001850 driver_.reset(new CompilerDriver(compiler_options_.get(),
1851 verification_results_.get(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001852 compiler_kind_,
1853 instruction_set_,
1854 instruction_set_features_.get(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001855 image_classes_.release(),
1856 compiled_classes_.release(),
Wojciech Staszkiewicz62534792016-08-09 14:30:55 -07001857 compiled_methods_.release(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001858 thread_count_,
1859 dump_stats_,
1860 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001861 compiler_phases_timings_.get(),
1862 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001863 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001864 driver_->SetDexFilesForOatFile(dex_files_);
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001865
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001866 const bool compile_individually = ShouldCompileDexFilesIndividually();
1867 if (compile_individually) {
1868 // Set the compiler driver in the callbacks so that we can avoid re-verification. This not
1869 // only helps performance but also prevents reverifying quickened bytecodes. Attempting
1870 // verify quickened bytecode causes verification failures.
1871 // Only set the compiler filter if we are doing separate compilation since there is a bit
1872 // of overhead when checking if a class was previously verified.
1873 callbacks_->SetDoesClassUnloading(true, driver_.get());
1874 }
1875
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001876 // Setup vdex for compilation.
1877 if (!DoEagerUnquickeningOfVdex() && input_vdex_file_ != nullptr) {
1878 callbacks_->SetVerifierDeps(
1879 new verifier::VerifierDeps(dex_files_, input_vdex_file_->GetVerifierDepsData()));
1880
1881 // TODO: we unquicken unconditionally, as we don't know
1882 // if the boot image has changed. How exactly we'll know is under
1883 // experimentation.
1884 TimingLogger::ScopedTiming time_unquicken("Unquicken", timings_);
1885 VdexFile::Unquicken(dex_files_, input_vdex_file_->GetQuickeningInfo());
Mathieu Chartier72041a02017-07-14 18:23:25 -07001886 } else {
1887 // Create the main VerifierDeps, here instead of in the compiler since we want to aggregate
1888 // the results for all the dex files, not just the results for the current dex file.
1889 callbacks_->SetVerifierDeps(new verifier::VerifierDeps(dex_files_));
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001890 }
Mathieu Chartier72041a02017-07-14 18:23:25 -07001891 // Invoke the compilation.
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001892 if (compile_individually) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001893 CompileDexFilesIndividually();
1894 // Return a null classloader since we already freed released it.
1895 return nullptr;
1896 }
1897 return CompileDexFiles(dex_files_);
1898 }
1899
1900 // Create the class loader, use it to compile, and return.
1901 jobject CompileDexFiles(const std::vector<const DexFile*>& dex_files) {
1902 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1903
1904 jobject class_loader = nullptr;
1905 if (!IsBootImage()) {
1906 class_loader = class_loader_context_->CreateClassLoader(dex_files_);
1907 }
1908
1909 // Register dex caches and key them to the class loader so that they only unload when the
1910 // class loader unloads.
1911 for (const auto& dex_file : dex_files) {
1912 ScopedObjectAccess soa(Thread::Current());
1913 // Registering the dex cache adds a strong root in the class loader that prevents the dex
1914 // cache from being unloaded early.
1915 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
1916 *dex_file,
1917 soa.Decode<mirror::ClassLoader>(class_loader));
1918 if (dex_cache == nullptr) {
1919 soa.Self()->AssertPendingException();
1920 LOG(FATAL) << "Failed to register dex file " << dex_file->GetLocation() << " "
1921 << soa.Self()->GetException()->Dump();
1922 }
1923 }
1924 driver_->CompileAll(class_loader, dex_files, timings_);
1925 return class_loader;
Vladimir Markof4da6752014-08-01 19:04:18 +01001926 }
1927
Jeff Hao436183f2016-01-12 16:36:50 -08001928 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 // ensure the references between the two are correct.
1930 //
1931 // Currently we have a memory layout that looks something like this:
1932 //
1933 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001934 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001935 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001936 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001937 // +--------------+
1938 // | alloc spaces |
1939 // +--------------+
1940 //
Jeff Hao436183f2016-01-12 16:36:50 -08001941 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001942 //
Jeff Hao436183f2016-01-12 16:36:50 -08001943 // 1. The images are expected to be loaded at an absolute address and
1944 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001945 //
Jeff Hao436183f2016-01-12 16:36:50 -08001946 // 2. There are absolute pointers from Methods in the images to their
1947 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948 //
Jeff Hao436183f2016-01-12 16:36:50 -08001949 // 3. There are absolute pointers from the code in the oat files to Methods
1950 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001951 //
Jeff Hao436183f2016-01-12 16:36:50 -08001952 // 4. There are absolute pointers from code in the oat files to other code
1953 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001954 //
1955 // To get this all correct, we go through several steps.
1956 //
Jeff Hao436183f2016-01-12 16:36:50 -08001957 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001958 // the oat data size and code size. During this stage, we also set
1959 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001960 //
Jeff Hao436183f2016-01-12 16:36:50 -08001961 // 2. We prepare offsets for the objects in the images and calculate
1962 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001963 //
Jeff Hao436183f2016-01-12 16:36:50 -08001964 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001965 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001966 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001967 // can prepare the ELF headers and we then know the ELF memory segment
1968 // layout and we can now resolve all references. The compiler provides
1969 // LinkerPatch information in each CompiledMethod and we resolve these,
1970 // using the layout information and image object locations provided by
1971 // image writer, as we're writing the method code.
1972 //
Jeff Hao436183f2016-01-12 16:36:50 -08001973 // 4. We create the image files. They need to know where the oat files
1974 // will be loaded after itself. Originally oat files were simply
1975 // memory mapped so we could predict where their contents were based
1976 // on the file size. Now that they are ELF files, we need to inspect
1977 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001978 // where the oat header is located within.
1979 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001980 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001981 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001982 // load the .so at the desired location at runtime by offsetting the
1983 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001984 // TODO: Do this in step 3. We already know the layout there.
1985 //
1986 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1987 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001988
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001989 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1990 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001991 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1992 // case (when the file will be explicitly erased).
David Brazdil7b49e6c2016-09-01 11:06:18 +01001993 bool WriteOutputFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001994 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1995
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001996 // Sync the data to the file, in case we did dex2dex transformations.
1997 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1998 if (!map->Sync()) {
1999 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
2000 return false;
2001 }
2002 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002003
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002004 if (IsImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002005 if (IsAppImage() && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002006 gc::Heap* const heap = Runtime::Current()->GetHeap();
2007 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002008 image_base_ = std::max(image_base_, RoundUp(
2009 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
2010 kPageSize));
2011 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002012 // The non moving space is right after the oat file. Put the preferred app image location
2013 // right after the non moving space so that we ideally get a continuous immune region for
2014 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002015 // Use the default non moving space capacity since dex2oat does not have a separate non-
2016 // moving space. This means the runtime's non moving space space size will be as large
2017 // as the growth limit for dex2oat, but smaller in the zygote.
2018 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002019 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002020 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
2021 }
2022
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002023 image_writer_.reset(new ImageWriter(*driver_,
2024 image_base_,
2025 compiler_options_->GetCompilePic(),
2026 IsAppImage(),
2027 image_storage_mode_,
2028 oat_filenames_,
Jeff Haoc23b0c02017-07-27 18:19:38 -07002029 dex_file_oat_index_map_,
2030 dirty_image_objects_.get()));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002031
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002032 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002033 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
2034 if (!image_writer_->PrepareImageAddressSpace()) {
2035 LOG(ERROR) << "Failed to prepare image address space.";
2036 return false;
2037 }
2038 }
2039
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002040 // Initialize the writers with the compiler driver, image writer, and their
2041 // dex files. The writers were created without those being there yet.
2042 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2043 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
2044 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
2045 oat_writer->Initialize(driver_.get(), image_writer_.get(), dex_files);
2046 }
2047
David Brazdil5d5a36b2016-09-14 15:34:10 +01002048 {
2049 TimingLogger::ScopedTiming t2("dex2oat Write VDEX", timings_);
2050 DCHECK(IsBootImage() || oat_files_.size() == 1u);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002051 verifier::VerifierDeps* verifier_deps = callbacks_->GetVerifierDeps();
David Brazdil5d5a36b2016-09-14 15:34:10 +01002052 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2053 File* vdex_file = vdex_files_[i].get();
Andreas Gampe8bdda5a2017-06-08 15:30:36 -07002054 std::unique_ptr<BufferedOutputStream> vdex_out =
2055 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
David Brazdil5d5a36b2016-09-14 15:34:10 +01002056
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002057 if (!oat_writers_[i]->WriteVerifierDeps(vdex_out.get(), verifier_deps)) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002058 LOG(ERROR) << "Failed to write verifier dependencies into VDEX " << vdex_file->GetPath();
2059 return false;
2060 }
2061
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002062 if (!oat_writers_[i]->WriteQuickeningInfo(vdex_out.get())) {
2063 LOG(ERROR) << "Failed to write quickening info into VDEX " << vdex_file->GetPath();
2064 return false;
2065 }
2066
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002067 // VDEX finalized, seek back to the beginning and write checksums and the header.
2068 if (!oat_writers_[i]->WriteChecksumsAndVdexHeader(vdex_out.get())) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002069 LOG(ERROR) << "Failed to write vdex header into VDEX " << vdex_file->GetPath();
2070 return false;
2071 }
2072 }
2073 }
2074
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002075 {
2076 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002077 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002078 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00002079 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
2080 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
2081
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002082 oat_writer->PrepareLayout(&patcher);
Vladimir Marko944da602016-02-19 12:27:55 +00002083
2084 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
David Brazdil7b49e6c2016-09-01 11:06:18 +01002085 size_t text_size = oat_writer->GetOatSize() - rodata_size;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002086 elf_writer->PrepareDynamicSection(rodata_size,
2087 text_size,
2088 oat_writer->GetBssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002089 oat_writer->GetBssMethodsOffset(),
Vladimir Markoaad75c62016-10-03 08:46:48 +00002090 oat_writer->GetBssRootsOffset());
Vladimir Marko944da602016-02-19 12:27:55 +00002091
2092 if (IsImage()) {
2093 // Update oat layout.
2094 DCHECK(image_writer_ != nullptr);
2095 DCHECK_LT(i, oat_filenames_.size());
2096 image_writer_->UpdateOatFileLayout(i,
2097 elf_writer->GetLoadedSize(),
2098 oat_writer->GetOatDataOffset(),
David Brazdil7b49e6c2016-09-01 11:06:18 +01002099 oat_writer->GetOatSize());
Vladimir Marko944da602016-02-19 12:27:55 +00002100 }
Richard Uhlerbc26b722017-03-10 14:27:10 +00002101
2102 if (IsBootImage()) {
2103 // Have the image_file_location_oat_checksum_ for boot oat files
2104 // depend on the contents of all the boot oat files. This way only
2105 // the primary image checksum needs to be checked to determine
2106 // whether any of the images are out of date.
2107 image_file_location_oat_checksum_ ^= oat_writer->GetOatHeader().GetChecksum();
2108 }
Vladimir Marko944da602016-02-19 12:27:55 +00002109 }
2110
2111 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002112 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002113 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
2114 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00002115
David Srbecky09c2a6b2016-03-11 17:11:44 +00002116 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader()));
2117
David Srbecky0c4572e2016-01-22 19:19:25 +00002118 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00002119 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
2120 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00002121
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002122 OutputStream*& rodata = rodata_[i];
2123 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124 if (!oat_writer->WriteRodata(rodata)) {
2125 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
2126 return false;
2127 }
2128 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002129 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00002130
Jeff Haodcdc85b2015-12-04 14:06:18 -08002131 OutputStream* text = elf_writer->StartText();
2132 if (!oat_writer->WriteCode(text)) {
2133 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
2134 return false;
2135 }
2136 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00002137
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002138 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
2139 image_file_location_oat_checksum_,
2140 image_file_location_oat_data_begin_,
2141 image_patch_delta_)) {
2142 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
2143 return false;
2144 }
2145
Vladimir Marko944da602016-02-19 12:27:55 +00002146 if (IsImage()) {
2147 // Update oat header information.
2148 DCHECK(image_writer_ != nullptr);
2149 DCHECK_LT(i, oat_filenames_.size());
2150 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
2151 }
2152
Jeff Haodcdc85b2015-12-04 14:06:18 -08002153 elf_writer->WriteDynamicSection();
2154 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
Vladimir Marko10c13562015-11-25 14:33:36 +00002155
Jeff Haodcdc85b2015-12-04 14:06:18 -08002156 if (!elf_writer->End()) {
2157 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
2158 return false;
2159 }
2160
David Brazdil7b49e6c2016-09-01 11:06:18 +01002161 if (!FlushOutputFile(&vdex_files_[i]) || !FlushOutputFile(&oat_files_[i])) {
2162 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002163 }
2164
Jeff Haodcdc85b2015-12-04 14:06:18 -08002165 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002166
2167 oat_writer.reset();
2168 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002169 }
2170 }
2171
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002172 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002173 }
2174
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002175 // If we are compiling an image, invoke the image creation routine. Else just skip.
2176 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002177 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002178 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
2179 if (!CreateImageFile()) {
2180 return false;
2181 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002182 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07002183 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002184 return true;
2185 }
2186
Jeff Haodcdc85b2015-12-04 14:06:18 -08002187 // Create a copy from stripped to unstripped.
2188 bool CopyStrippedToUnstripped() {
2189 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
2190 // If we don't want to strip in place, copy from stripped location to unstripped location.
2191 // We need to strip after image creation because FixupElf needs to use .strtab.
2192 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
2193 // If the oat file is still open, flush it.
2194 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002195 if (!FlushCloseOutputFile(&oat_files_[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002196 return false;
2197 }
2198 }
2199
2200 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
2201 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
2202 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
Vladimir Markob55cc6d2016-10-17 15:25:10 +01002203 int64_t in_length = in->GetLength();
2204 if (in_length < 0) {
2205 PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
2206 return false;
2207 }
2208 if (!out->Copy(in.get(), 0, in_length)) {
2209 PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
2210 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002211 }
2212 if (out->FlushCloseOrErase() != 0) {
2213 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
2214 return false;
2215 }
2216 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
2217 }
2218 }
2219 return true;
2220 }
2221
David Brazdil7b49e6c2016-09-01 11:06:18 +01002222 bool FlushOutputFile(std::unique_ptr<File>* file) {
2223 if (file->get() != nullptr) {
2224 if (file->get()->Flush() != 0) {
2225 PLOG(ERROR) << "Failed to flush output file: " << file->get()->GetPath();
2226 return false;
2227 }
2228 }
2229 return true;
2230 }
2231
2232 bool FlushCloseOutputFile(std::unique_ptr<File>* file) {
2233 if (file->get() != nullptr) {
2234 std::unique_ptr<File> tmp(file->release());
2235 if (tmp->FlushCloseOrErase() != 0) {
2236 PLOG(ERROR) << "Failed to flush and close output file: " << tmp->GetPath();
2237 return false;
2238 }
2239 }
2240 return true;
2241 }
2242
2243 bool FlushOutputFiles() {
2244 TimingLogger::ScopedTiming t2("dex2oat Flush Output Files", timings_);
2245 for (auto& files : { &vdex_files_, &oat_files_ }) {
2246 for (size_t i = 0; i < files->size(); ++i) {
2247 if (!FlushOutputFile(&(*files)[i])) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002248 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002249 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002250 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00002251 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08002252 return true;
2253 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002254
David Brazdil7b49e6c2016-09-01 11:06:18 +01002255 bool FlushCloseOutputFiles() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002256 bool result = true;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002257 for (auto& files : { &vdex_files_, &oat_files_ }) {
2258 for (size_t i = 0; i < files->size(); ++i) {
2259 result &= FlushCloseOutputFile(&(*files)[i]);
2260 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002261 }
2262 return result;
2263 }
2264
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265 void DumpTiming() {
2266 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
2267 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
2268 }
2269 if (dump_passes_) {
2270 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
2271 }
2272 }
2273
Andreas Gampe10e477d2014-11-19 12:57:42 -08002274 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002275 return IsAppImage() || IsBootImage();
2276 }
2277
2278 bool IsAppImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002279 return compiler_options_->IsAppImage();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002280 }
2281
2282 bool IsBootImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002283 return compiler_options_->IsBootImage();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002284 }
2285
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002286 bool IsHost() const {
2287 return is_host_;
2288 }
2289
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002290 bool UseProfile() const {
Mathieu Chartierd0af56c2017-02-17 12:56:25 -08002291 return profile_file_fd_ != -1 || !profile_file_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02002292 }
2293
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002294 bool DoProfileGuidedOptimizations() const {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002295 return UseProfile();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002296 }
2297
2298 bool DoDexLayoutOptimizations() const {
2299 return DoProfileGuidedOptimizations();
2300 }
2301
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01002302 bool DoEagerUnquickeningOfVdex() const {
2303 // DexLayout can invalidate the vdex metadata, so we need to unquicken
2304 // the vdex file eagerly, before passing it to dexlayout.
2305 return DoDexLayoutOptimizations();
2306 }
2307
Calin Juravle2e2db782016-02-23 12:00:03 +00002308 bool LoadProfile() {
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002309 DCHECK(UseProfile());
Calin Juravlee6f87cc2017-05-24 17:41:05 -07002310 // TODO(calin): We should be using the runtime arena pool (instead of the
2311 // default profile arena). However the setup logic is messy and needs
2312 // cleaning up before that (e.g. the oat writers are created before the
2313 // runtime).
Calin Juravle2e2db782016-02-23 12:00:03 +00002314 profile_compilation_info_.reset(new ProfileCompilationInfo());
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002315 ScopedFlock profile_file;
Calin Juravle2e2db782016-02-23 12:00:03 +00002316 std::string error;
2317 if (profile_file_fd_ != -1) {
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002318 profile_file = LockedFile::DupOf(profile_file_fd_, "profile",
2319 true /* read_only_mode */, &error);
Andreas Gampe29d38e72016-03-23 15:31:51 +00002320 } else if (profile_file_ != "") {
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002321 profile_file = LockedFile::Open(profile_file_.c_str(), O_RDONLY, true, &error);
Calin Juravle998c2162015-12-21 15:39:33 +02002322 }
Calin Juravle877fd962016-01-05 14:29:29 +00002323
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002324 // Return early if we're unable to obtain a lock on the profile.
2325 if (profile_file.get() == nullptr) {
2326 LOG(ERROR) << "Cannot lock profiles: " << error;
2327 return false;
2328 }
2329
2330 if (!profile_compilation_info_->Load(profile_file->Fd())) {
Calin Juravle2e2db782016-02-23 12:00:03 +00002331 profile_compilation_info_.reset(nullptr);
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002332 return false;
Calin Juravle2e2db782016-02-23 12:00:03 +00002333 }
Calin Juravle877fd962016-01-05 14:29:29 +00002334
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002335 return true;
Calin Juravle998c2162015-12-21 15:39:33 +02002336 }
2337
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002338 private:
Andreas Gampee1459ae2016-06-29 09:36:30 -07002339 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) {
2340 if (is_image) {
2341 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
2342 return false;
2343 }
2344 if (dex_files.size() < min_dex_files_for_swap_) {
2345 // If there are less dex files than the threshold, assume it's gonna be fine.
2346 return false;
2347 }
2348 size_t dex_files_size = 0;
2349 for (const auto* dex_file : dex_files) {
2350 dex_files_size += dex_file->GetHeader().file_size_;
2351 }
2352 return dex_files_size >= min_dex_file_cumulative_size_for_swap_;
2353 }
2354
Andreas Gampe67f02822016-06-24 21:05:23 -07002355 bool IsVeryLarge(std::vector<const DexFile*>& dex_files) {
2356 size_t dex_files_size = 0;
2357 for (const auto* dex_file : dex_files) {
2358 dex_files_size += dex_file->GetHeader().file_size_;
2359 }
2360 return dex_files_size >= very_large_threshold_;
2361 }
2362
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002363 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
2364 // This function is used only for apps and for an app we have exactly one oat file.
2365 DCHECK(!IsBootImage());
2366 DCHECK_EQ(oat_writers_.size(), 1u);
2367 std::vector<std::string> dex_files_canonical_locations;
Calin Juravle1ce70852017-06-28 10:59:03 -07002368 for (const std::string& location : oat_writers_[0]->GetSourceLocations()) {
2369 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002370 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00002371
Vladimir Marko919f5532016-01-20 19:13:01 +00002372 std::vector<std::string> parsed;
2373 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002374 auto kept_it = std::remove_if(parsed.begin(),
2375 parsed.end(),
2376 [dex_files_canonical_locations](const std::string& location) {
2377 return ContainsElement(dex_files_canonical_locations,
2378 DexFile::GetDexCanonicalLocation(location.c_str()));
2379 });
2380 parsed.erase(kept_it, parsed.end());
2381 return parsed;
2382 }
2383
Vladimir Marko49b0f452015-12-10 13:49:19 +00002384 bool PrepareImageClasses() {
2385 // If --image-classes was specified, calculate the full list of classes to include in the image.
2386 if (image_classes_filename_ != nullptr) {
2387 image_classes_ =
2388 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
2389 if (image_classes_ == nullptr) {
2390 return false;
2391 }
2392 } else if (IsBootImage()) {
2393 image_classes_.reset(new std::unordered_set<std::string>);
2394 }
2395 return true;
2396 }
2397
2398 bool PrepareCompiledClasses() {
2399 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2400 // image.
2401 if (compiled_classes_filename_ != nullptr) {
2402 compiled_classes_ =
2403 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2404 if (compiled_classes_ == nullptr) {
2405 return false;
2406 }
2407 } else {
2408 compiled_classes_.reset(nullptr); // By default compile everything.
2409 }
2410 return true;
2411 }
2412
2413 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2414 const char* classes_filename,
2415 const char* tag) {
2416 std::unique_ptr<std::unordered_set<std::string>> classes;
2417 std::string error_msg;
2418 if (zip_filename != nullptr) {
2419 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2420 } else {
2421 classes.reset(ReadImageClassesFromFile(classes_filename));
2422 }
2423 if (classes == nullptr) {
2424 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2425 << classes_filename << "': " << error_msg;
2426 }
2427 return classes;
2428 }
2429
2430 bool PrepareCompiledMethods() {
2431 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2432 if (compiled_methods_filename_ != nullptr) {
2433 std::string error_msg;
2434 if (compiled_methods_zip_filename_ != nullptr) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002435 compiled_methods_.reset(ReadCommentedInputFromZip<std::unordered_set<std::string>>(
2436 compiled_methods_zip_filename_,
2437 compiled_methods_filename_,
2438 nullptr, // No post-processing.
2439 &error_msg));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002440 } else {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002441 compiled_methods_.reset(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
2442 compiled_methods_filename_,
2443 nullptr)); // No post-processing.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002444 }
2445 if (compiled_methods_.get() == nullptr) {
2446 LOG(ERROR) << "Failed to create list of compiled methods from '"
2447 << compiled_methods_filename_ << "': " << error_msg;
2448 return false;
2449 }
2450 } else {
2451 compiled_methods_.reset(nullptr); // By default compile everything.
2452 }
2453 return true;
2454 }
2455
Jeff Haoc23b0c02017-07-27 18:19:38 -07002456 bool PrepareDirtyObjects() {
2457 if (dirty_image_objects_filename_ != nullptr) {
2458 dirty_image_objects_.reset(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
2459 dirty_image_objects_filename_,
2460 nullptr));
2461 if (dirty_image_objects_ == nullptr) {
2462 LOG(ERROR) << "Failed to create list of dirty objects from '"
2463 << dirty_image_objects_filename_ << "'";
2464 return false;
2465 }
2466 } else {
2467 dirty_image_objects_.reset(nullptr);
2468 }
2469 return true;
2470 }
2471
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002472 void PruneNonExistentDexFiles() {
2473 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2474 size_t kept = 0u;
2475 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2476 if (!OS::FileExists(dex_filenames_[i])) {
2477 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2478 } else {
2479 dex_filenames_[kept] = dex_filenames_[i];
2480 dex_locations_[kept] = dex_locations_[i];
2481 ++kept;
2482 }
2483 }
2484 dex_filenames_.resize(kept);
2485 dex_locations_.resize(kept);
2486 }
2487
2488 bool AddDexFileSources() {
2489 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002490 if (input_vdex_file_ != nullptr) {
2491 DCHECK_EQ(oat_writers_.size(), 1u);
2492 const std::string& name = zip_location_.empty() ? dex_locations_[0] : zip_location_;
2493 DCHECK(!name.empty());
2494 if (!oat_writers_[0]->AddVdexDexFilesSource(*input_vdex_file_.get(), name.c_str())) {
2495 return false;
2496 }
2497 } else if (zip_fd_ != -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002498 DCHECK_EQ(oat_writers_.size(), 1u);
Andreas Gampe43e10b02016-07-15 17:17:34 -07002499 if (!oat_writers_[0]->AddZippedDexFilesSource(File(zip_fd_, /* check_usage */ false),
2500 zip_location_.c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002501 return false;
2502 }
2503 } else if (oat_writers_.size() > 1u) {
2504 // Multi-image.
2505 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2506 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2507 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2508 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2509 return false;
2510 }
2511 }
2512 } else {
2513 DCHECK_EQ(oat_writers_.size(), 1u);
2514 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2515 DCHECK_NE(dex_filenames_.size(), 0u);
2516 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2517 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2518 return false;
2519 }
2520 }
2521 }
2522 return true;
2523 }
2524
2525 void CreateOatWriters() {
2526 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2527 elf_writers_.reserve(oat_files_.size());
2528 oat_writers_.reserve(oat_files_.size());
2529 for (const std::unique_ptr<File>& oat_file : oat_files_) {
David Srbecky5d811202016-03-08 13:21:22 +00002530 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2531 instruction_set_features_.get(),
2532 compiler_options_.get(),
2533 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002534 elf_writers_.back()->Start();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002535 const bool do_dexlayout = DoDexLayoutOptimizations();
Jeff Hao608f2ce2016-10-19 11:17:11 -07002536 oat_writers_.emplace_back(new OatWriter(
2537 IsBootImage(), timings_, do_dexlayout ? profile_compilation_info_.get() : nullptr));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002538 }
2539 }
2540
Vladimir Marko49b0f452015-12-10 13:49:19 +00002541 void SaveDexInput() {
2542 for (size_t i = 0; i < dex_files_.size(); ++i) {
2543 const DexFile* dex_file = dex_files_[i];
2544 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2545 getpid(), i));
2546 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2547 if (tmp_file.get() == nullptr) {
2548 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2549 << ". Try: adb shell chmod 777 /data/local/tmp";
2550 continue;
2551 }
2552 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2553 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2554 UNUSED(tmp_file->Flush());
2555 UNUSED(tmp_file->Close());
2556 LOG(INFO) << "Wrote input to " << tmp_file_name;
2557 }
2558 }
2559
Mathieu Chartier46331a62017-07-21 09:49:10 -07002560 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options,
2561 QuickCompilerCallbacks* callbacks) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002562 RuntimeOptions raw_options;
2563 if (boot_image_filename_.empty()) {
2564 std::string boot_class_path = "-Xbootclasspath:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002565 boot_class_path += android::base::Join(dex_filenames_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002566 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2567 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002568 boot_class_path_locations += android::base::Join(dex_locations_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002569 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2570 } else {
2571 std::string boot_image_option = "-Ximage:";
2572 boot_image_option += boot_image_filename_;
2573 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2574 }
2575 for (size_t i = 0; i < runtime_args_.size(); i++) {
2576 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2577 }
2578
Mathieu Chartier46331a62017-07-21 09:49:10 -07002579 raw_options.push_back(std::make_pair("compilercallbacks", callbacks));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002580 raw_options.push_back(
2581 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2582
2583 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2584 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2585 // have been stripped in preopting, anyways).
2586 if (!IsBootImage()) {
2587 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2588 }
Andreas Gampec8e35202017-04-28 15:47:12 -07002589 // Never allow implicit image compilation.
2590 raw_options.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002591 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2592 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2593 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002594 // Disable Hspace compaction to save heap size virtual space.
2595 // Only need disable Hspace for OOM becasue background collector is equal to
2596 // foreground collector by default for dex2oat.
2597 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002598
Andreas Gampeace0dc12016-01-20 13:33:13 -08002599 if (compiler_options_->IsForceDeterminism()) {
Roland Levillainb81e9e92017-04-20 17:35:32 +01002600 // If we're asked to be deterministic, ensure non-concurrent GC for determinism.
2601 //
2602 // Note that with read barriers, this option is ignored, because Runtime::Init
2603 // overrides the foreground GC to be gc::kCollectorTypeCC when instantiating
2604 // gc::Heap. This is fine, as concurrent GC requests are not honored in dex2oat,
2605 // which uses an unstarted runtime.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002606 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
Roland Levillainb81e9e92017-04-20 17:35:32 +01002607
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002608 // The default LOS implementation (map) is not deterministic. So disable it.
2609 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=disabled", nullptr));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002610
2611 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2612 // compaction (done above) and ensure that neither foreground nor background collectors
2613 // are concurrent.
Roland Levillainb81e9e92017-04-20 17:35:32 +01002614 //
2615 // Likewise, this option is ignored with read barriers because Runtime::Init
2616 // overrides the background GC to be gc::kCollectorTypeCCBackground, but that's
2617 // fine too, for the same reason (see above).
Andreas Gampeace0dc12016-01-20 13:33:13 -08002618 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2619
2620 // To make identity hashcode deterministic, set a known seed.
2621 mirror::Object::SetHashCodeSeed(987654321U);
2622 }
2623
Vladimir Marko49b0f452015-12-10 13:49:19 +00002624 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2625 LOG(ERROR) << "Failed to parse runtime options";
2626 return false;
2627 }
2628 return true;
2629 }
2630
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002631 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002632 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2633 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002634 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002635 LOG(ERROR) << "Failed to create runtime";
2636 return false;
2637 }
Andreas Gampe49c144d2016-11-14 10:11:16 -08002638
2639 // Runtime::Init will rename this thread to be "main". Prefer "dex2oat" so that "top" and
2640 // "ps -a" don't change to non-descript "main."
2641 SetThreadName(kIsDebugBuild ? "dex2oatd" : "dex2oat");
2642
Vladimir Marko307dac92015-10-20 11:20:09 +01002643 runtime_.reset(Runtime::Current());
2644 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002645 for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2646 CalleeSaveType type = CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002647 if (!runtime_->HasCalleeSaveMethod(type)) {
2648 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002649 }
2650 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002651
2652 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2653 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002654 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002655
Vladimir Marko307dac92015-10-20 11:20:09 +01002656 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002657
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002658 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2659 // Runtime::Start, give it away now so that we don't starve GC.
2660 Thread* self = Thread::Current();
2661 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002662
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002663 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002664 }
2665
Jeff Haodcdc85b2015-12-04 14:06:18 -08002666 // 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 -08002667 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002668 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002669 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002670 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002671 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002672 image_filenames_.push_back(app_image_file_name_.c_str());
2673 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002674 if (!image_writer_->Write(app_image_fd_,
2675 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002676 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002677 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002678 return false;
2679 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002680
Jeff Haodcdc85b2015-12-04 14:06:18 -08002681 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002682 dchecked_vector<uintptr_t> oat_data_begins;
2683 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2684 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002685 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002686 // Destroy ImageWriter before doing FixupElf.
2687 image_writer_.reset();
2688
Vladimir Marko944da602016-02-19 12:27:55 +00002689 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2690 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002691 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2692 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2693 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2694 if (oat_file.get() == nullptr) {
2695 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2696 return false;
2697 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002698
Vladimir Marko944da602016-02-19 12:27:55 +00002699 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002700 oat_file->Erase();
2701 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2702 return false;
2703 }
2704
2705 if (oat_file->FlushCloseOrErase()) {
2706 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2707 return false;
2708 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002709 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002710 }
2711
2712 return true;
2713 }
2714
2715 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002716 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2717 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002718 std::function<std::string(const char*)> process = DotToDescriptor;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002719 return ReadCommentedInputFromFile<std::unordered_set<std::string>>(image_classes_filename,
2720 &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002721 }
2722
2723 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002724 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002725 const char* zip_filename,
2726 const char* image_classes_filename,
2727 std::string* error_msg) {
2728 std::function<std::string(const char*)> process = DotToDescriptor;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002729 return ReadCommentedInputFromZip<std::unordered_set<std::string>>(zip_filename,
2730 image_classes_filename,
2731 &process,
2732 error_msg);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002733 }
2734
2735 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2736 // the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002737 template <typename T>
2738 static T* ReadCommentedInputFromFile(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002739 const char* input_filename, std::function<std::string(const char*)>* process) {
2740 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2741 if (input_file.get() == nullptr) {
2742 LOG(ERROR) << "Failed to open input file " << input_filename;
2743 return nullptr;
2744 }
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002745 std::unique_ptr<T> result(
2746 ReadCommentedInputStream<T>(*input_file, process));
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002747 input_file->close();
2748 return result.release();
2749 }
2750
2751 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2752 // Post-process each line with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002753 template <typename T>
2754 static T* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002755 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002756 const char* input_filename,
2757 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002758 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002759 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2760 if (zip_archive.get() == nullptr) {
2761 return nullptr;
2762 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002763 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002764 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002765 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002766 zip_filename, error_msg->c_str());
2767 return nullptr;
2768 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002769 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2770 input_filename,
2771 error_msg));
2772 if (input_file.get() == nullptr) {
2773 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002774 zip_filename, error_msg->c_str());
2775 return nullptr;
2776 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002777 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2778 input_file->Size());
2779 std::istringstream input_stream(input_string);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002780 return ReadCommentedInputStream<T>(input_stream, process);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002781 }
2782
2783 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2784 // with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002785 template <typename T>
2786 static T* ReadCommentedInputStream(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002787 std::istream& in_stream,
2788 std::function<std::string(const char*)>* process) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002789 std::unique_ptr<T> output(new T());
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002790 while (in_stream.good()) {
2791 std::string dot;
2792 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08002793 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002794 continue;
2795 }
2796 if (process != nullptr) {
2797 std::string descriptor((*process)(dot.c_str()));
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002798 output->insert(output->end(), descriptor);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002799 } else {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002800 output->insert(output->end(), dot);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002801 }
2802 }
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002803 return output.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002804 }
2805
Mathieu Chartier49285c52014-12-02 15:43:48 -08002806 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002807 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2808 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002809 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampec560fc02014-07-16 09:57:39 -07002810 LOG(INFO) << "dex2oat took "
2811 << PrettyDuration(NanoTime() - start_ns_)
Andreas Gampecc967752016-12-12 13:49:00 -08002812 << " (" << PrettyDuration(ProcessCpuNanoTime() - start_cputime_ns_) << " cpu)"
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002813 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002814 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002815 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2816 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002817 }
2818
Jeff Haodcdc85b2015-12-04 14:06:18 -08002819 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2820 std::string res(image_filename);
2821 size_t last_slash = res.rfind('/');
2822 if (last_slash == std::string::npos || last_slash == 0) {
2823 return res;
2824 }
2825 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2826 if (penultimate_slash == std::string::npos) {
2827 return res;
2828 }
2829 // Check that the string in-between is the expected one.
2830 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2831 GetInstructionSetString(isa)) {
2832 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2833 return res;
2834 }
2835 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2836 }
2837
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002838 std::unique_ptr<CompilerOptions> compiler_options_;
2839 Compiler::Kind compiler_kind_;
2840
2841 InstructionSet instruction_set_;
2842 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2843
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002844 uint32_t image_file_location_oat_checksum_;
2845 uintptr_t image_file_location_oat_data_begin_;
2846 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002847 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2848
Vladimir Marko307dac92015-10-20 11:20:09 +01002849 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002850
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002851 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2852
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002853 std::unique_ptr<Runtime> runtime_;
2854
Calin Juravle1ce70852017-06-28 10:59:03 -07002855 // The spec describing how the class loader should be setup for compilation.
2856 std::unique_ptr<ClassLoaderContext> class_loader_context_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002857
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002858 size_t thread_count_;
2859 uint64_t start_ns_;
Andreas Gampec560fc02014-07-16 09:57:39 -07002860 uint64_t start_cputime_ns_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002861 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002862 std::vector<std::unique_ptr<File>> oat_files_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002863 std::vector<std::unique_ptr<File>> vdex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002864 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002865 std::vector<const char*> oat_filenames_;
2866 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002867 int oat_fd_;
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00002868 int input_vdex_fd_;
2869 int output_vdex_fd_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002870 std::string input_vdex_;
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01002871 std::string output_vdex_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002872 std::unique_ptr<VdexFile> input_vdex_file_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002873 std::vector<const char*> dex_filenames_;
2874 std::vector<const char*> dex_locations_;
2875 int zip_fd_;
2876 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002877 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002878 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002879 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002880 uintptr_t image_base_;
2881 const char* image_classes_zip_filename_;
2882 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002883 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002884 const char* compiled_classes_zip_filename_;
2885 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002886 const char* compiled_methods_zip_filename_;
2887 const char* compiled_methods_filename_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002888 const char* passes_to_run_filename_;
Jeff Haoc23b0c02017-07-27 18:19:38 -07002889 const char* dirty_image_objects_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002890 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2891 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002892 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Jeff Haoc23b0c02017-07-27 18:19:38 -07002893 std::unique_ptr<std::unordered_set<std::string>> dirty_image_objects_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002894 std::unique_ptr<std::vector<std::string>> passes_to_run_;
Jeff Hao436183f2016-01-12 16:36:50 -08002895 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002896 bool is_host_;
2897 std::string android_root_;
Mathieu Chartier0b490842016-05-25 15:05:59 -07002898 // Dex files we are compiling, does not include the class path dex files.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002899 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002900 std::string no_inline_from_string_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002901
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002902 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2903 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2904 std::vector<OutputStream*> rodata_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002905 std::vector<std::unique_ptr<OutputStream>> vdex_out_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002906 std::unique_ptr<ImageWriter> image_writer_;
2907 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002908
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002909 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2910 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2911
Calin Juravle1ce70852017-06-28 10:59:03 -07002912 // Note that this might contain pointers owned by class_loader_context_.
Vladimir Marko47496c22016-01-27 16:15:08 +00002913 std::vector<const DexFile*> no_inline_from_dex_files_;
2914
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002915 bool dump_stats_;
2916 bool dump_passes_;
2917 bool dump_timing_;
2918 bool dump_slow_timing_;
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07002919 bool avoid_storing_invocation_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002920 std::string swap_file_name_;
2921 int swap_fd_;
Andreas Gampee1459ae2016-06-29 09:36:30 -07002922 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap;
2923 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap;
Andreas Gampe67f02822016-06-24 21:05:23 -07002924 size_t very_large_threshold_ = std::numeric_limits<size_t>::max();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002925 std::string app_image_file_name_;
2926 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002927 std::string profile_file_;
2928 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002929 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002930 TimingLogger* timings_;
2931 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002932 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002933 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002934
2935 // Backing storage.
2936 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002937
Andreas Gampeace0dc12016-01-20 13:33:13 -08002938 // See CompilerOptions.force_determinism_.
2939 bool force_determinism_;
2940
Jeff Hao16d48432017-04-05 17:05:46 -07002941 // Directory of relative classpaths.
2942 std::string classpath_dir_;
2943
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002944 // Whether the given input vdex is also the output.
2945 bool update_input_vdex_ = false;
2946
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002947 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2948};
2949
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002950static void b13564922() {
2951#if defined(__linux__) && defined(__arm__)
2952 int major, minor;
2953 struct utsname uts;
2954 if (uname(&uts) != -1 &&
2955 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2956 ((major < 3) || ((major == 3) && (minor < 4)))) {
2957 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2958 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2959 int old_personality = personality(0xffffffff);
2960 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2961 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2962 if (new_personality == -1) {
2963 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2964 }
2965 }
2966 }
2967#endif
2968}
2969
Mathieu Chartier72041a02017-07-14 18:23:25 -07002970class ScopedGlobalRef {
2971 public:
2972 explicit ScopedGlobalRef(jobject obj) : obj_(obj) {}
2973 ~ScopedGlobalRef() {
2974 if (obj_ != nullptr) {
2975 ScopedObjectAccess soa(Thread::Current());
2976 soa.Env()->vm->DeleteGlobalRef(soa.Self(), obj_);
2977 }
2978 }
2979
2980 private:
2981 jobject obj_;
2982};
2983
Andreas Gampe7b565912017-03-20 15:48:52 -07002984static dex2oat::ReturnCode CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002985 dex2oat.LoadClassProfileDescriptors();
Mathieu Chartier9e050df2017-08-09 10:05:47 -07002986 // Keep the class loader that was used for compilation live for the rest of the compilation
2987 // process.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002988 ScopedGlobalRef class_loader(dex2oat.Compile());
Andreas Gampe10e477d2014-11-19 12:57:42 -08002989
David Brazdil7b49e6c2016-09-01 11:06:18 +01002990 if (!dex2oat.WriteOutputFiles()) {
2991 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07002992 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002993 }
2994
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002995 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2996 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2997 // image writer will require this fd to generate the image.
2998 if (dex2oat.ShouldKeepOatFileOpen()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002999 if (!dex2oat.FlushOutputFiles()) {
3000 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003001 return dex2oat::ReturnCode::kOther;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003002 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003003 } else if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003004 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003005 }
3006
Jeff Haodcdc85b2015-12-04 14:06:18 -08003007 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08003008 if (!dex2oat.HandleImage()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003009 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003010 }
3011
3012 // When given --host, finish early without stripping.
3013 if (dex2oat.IsHost()) {
Mathieu Chartier00bf2602017-03-02 10:14:08 -08003014 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003015 return dex2oat::ReturnCode::kOther;
Mathieu Chartier00bf2602017-03-02 10:14:08 -08003016 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08003017 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003018 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003019 }
3020
Jeff Haodcdc85b2015-12-04 14:06:18 -08003021 // Copy stripped to unstripped location, if necessary.
3022 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003023 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003024 }
3025
Jeff Haodcdc85b2015-12-04 14:06:18 -08003026 // FlushClose again, as stripping might have re-opened the oat files.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003027 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003028 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003029 }
3030
3031 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003032 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003033}
3034
Andreas Gampe7b565912017-03-20 15:48:52 -07003035static dex2oat::ReturnCode CompileApp(Dex2Oat& dex2oat) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003036 // Keep the class loader that was used for compilation live for the rest of the compilation
3037 // process.
Mathieu Chartier72041a02017-07-14 18:23:25 -07003038 ScopedGlobalRef class_loader(dex2oat.Compile());
Andreas Gampe10e477d2014-11-19 12:57:42 -08003039
David Brazdil7b49e6c2016-09-01 11:06:18 +01003040 if (!dex2oat.WriteOutputFiles()) {
3041 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003042 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003043 }
3044
Jeff Haodcdc85b2015-12-04 14:06:18 -08003045 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08003046 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08003047
3048 // When given --host, finish early without stripping.
3049 if (dex2oat.IsHost()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003050 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003051 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003052 }
3053
3054 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003055 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003056 }
3057
Jeff Haodcdc85b2015-12-04 14:06:18 -08003058 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
3059 // stripped versions. If this is given, we expect to be able to open writable files by name.
3060 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003061 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003062 }
3063
Jeff Haodcdc85b2015-12-04 14:06:18 -08003064 // Flush and close the files.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003065 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003066 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003067 }
3068
3069 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003070 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003071}
3072
Andreas Gampe7b565912017-03-20 15:48:52 -07003073static dex2oat::ReturnCode Dex2oat(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003074 b13564922();
3075
3076 TimingLogger timings("compiler", false, false);
3077
Roland Levillain5c7e2602016-02-23 18:08:53 +00003078 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
3079 // might produce a stack frame too large for this function or for
3080 // functions inlining it (such as main), that would not fit the
3081 // requirements of the `-Wframe-larger-than` option.
Andreas Gampe8bdda5a2017-06-08 15:30:36 -07003082 std::unique_ptr<Dex2Oat> dex2oat = std::make_unique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003083
3084 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00003085 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003086
Calin Juravleb077e152016-02-18 18:47:37 +00003087 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02003088 // This operation involves I/O.
Mathieu Chartier11b3df32017-02-21 13:41:54 -08003089 if (dex2oat->UseProfile()) {
Calin Juravleb077e152016-02-18 18:47:37 +00003090 if (!dex2oat->LoadProfile()) {
3091 LOG(ERROR) << "Failed to process profile file";
Andreas Gampe7b565912017-03-20 15:48:52 -07003092 return dex2oat::ReturnCode::kOther;
Calin Juravle998c2162015-12-21 15:39:33 +02003093 }
3094 }
3095
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00003096 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap, and vdex.
3097
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003098 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00003099 if (!dex2oat->OpenFile()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003100 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003101 }
3102
Andreas Gampe046c7062015-05-18 23:22:54 -07003103 // Print the complete line when any of the following is true:
3104 // 1) Debug build
3105 // 2) Compiling an image
3106 // 3) Compiling with --host
3107 // 4) Compiling on the host (not a target build)
3108 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00003109 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07003110 LOG(INFO) << CommandLine();
3111 } else {
3112 LOG(INFO) << StrippedCommandLine();
3113 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003114
Andreas Gampef7882972017-03-20 16:35:24 -07003115 dex2oat::ReturnCode setup_code = dex2oat->Setup();
3116 if (setup_code != dex2oat::ReturnCode::kNoFailure) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003117 dex2oat->EraseOutputFiles();
Andreas Gampef7882972017-03-20 16:35:24 -07003118 return setup_code;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003119 }
3120
Wojciech Staszkiewicz529827d2016-09-15 10:30:30 -07003121 // Helps debugging on device. Can be used to determine which dalvikvm instance invoked a dex2oat
3122 // instance. Used by tools/bisection_search/bisection_search.py.
Wojciech Staszkiewicz0a4c75f2016-09-13 12:06:36 -07003123 VLOG(compiler) << "Running dex2oat (parent PID = " << getppid() << ")";
3124
Andreas Gampe7b565912017-03-20 15:48:52 -07003125 dex2oat::ReturnCode result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00003126 if (dex2oat->IsImage()) {
3127 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08003128 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00003129 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003130 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003131
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003132 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003133}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003134} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07003135
3136int main(int argc, char** argv) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003137 int result = static_cast<int>(art::Dex2oat(argc, argv));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003138 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
3139 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
3140 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07003141 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampee286b642017-04-13 12:20:42 -07003142 _exit(result);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003143 }
3144 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07003145}