blob: 6b65aca943c142254c22662251970ced56fec178 [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
Andreas Gampe097f34c2017-08-23 08:57:51 -070023#include <forward_list>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <fstream>
25#include <iostream>
Andreas Gampe67f02822016-06-24 21:05:23 -070026#include <limits>
Brian Carlstrom7940e442013-07-12 13:46:57 -070027#include <sstream>
28#include <string>
Andreas Gampe097f34c2017-08-23 08:57:51 -070029#include <type_traits>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070030#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include <vector>
32
Vladimir Markof94b7812014-06-05 15:48:04 +010033#if defined(__linux__) && defined(__arm__)
34#include <sys/personality.h>
35#include <sys/utsname.h>
36#endif
37
Andreas Gampe46ee31b2016-12-14 10:11:49 -080038#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080039#include "android-base/strings.h"
40
Ian Rogersd582fa42014-11-05 23:46:43 -080041#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080042#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000043#include "art_method-inl.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070044#include "base/callee_save_type.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070045#include "base/dumpable.h"
David Sehr891a50e2017-10-27 17:01:07 -070046#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080047#include "base/leb128.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080048#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080049#include "base/mutex.h"
50#include "base/os.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000051#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "base/stl_util.h"
53#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010054#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "base/timing_logger.h"
56#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080057#include "base/utils.h"
David Sehr79e26072018-04-06 17:58:50 -070058#include "base/zip_archive.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "class_linker.h"
Calin Juravle1ce70852017-06-28 10:59:03 -070060#include "class_loader_context.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070061#include "cmdline_parser.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000062#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000063#include "compiler_callbacks.h"
David Srbecky09c2a6b2016-03-11 17:11:44 +000064#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000065#include "debug/method_debug_info.h"
Mathieu Chartier2c4b0842017-12-13 11:49:51 -080066#include "dexlayout.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080067#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080068#include "dex/dex_file-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000069#include "dex/quick_compiler_callbacks.h"
70#include "dex/verification_results.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070071#include "dex2oat_options.h"
Andreas Gampe7b565912017-03-20 15:48:52 -070072#include "dex2oat_return_codes.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080074#include "driver/compiler_options.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070075#include "driver/compiler_options_map-inl.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080076#include "elf_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "gc/space/image_space.h"
78#include "gc/space/space-inl.h"
Mathieu Chartier72041a02017-07-14 18:23:25 -070079#include "gc/verification.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070080#include "interpreter/unstarted_runtime.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010081#include "jni/java_vm_ext.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010082#include "linker/buffered_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000083#include "linker/elf_writer.h"
84#include "linker/elf_writer_quick.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010085#include "linker/file_output_stream.h"
Vladimir Marko74527972016-11-29 15:57:32 +000086#include "linker/image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000087#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko74527972016-11-29 15:57:32 +000088#include "linker/oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070089#include "mirror/class-inl.h"
90#include "mirror/class_loader.h"
91#include "mirror/object-inl.h"
92#include "mirror/object_array-inl.h"
Andreas Gampe2ff3b972017-06-05 18:14:53 -070093#include "oat_file.h"
Jeff Haob11ffb72016-04-07 15:40:54 -070094#include "oat_file_assistant.h"
David Sehr82d046e2018-04-23 08:14:19 -070095#include "profile/profile_compilation_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070096#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000097#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070098#include "scoped_thread_state_change-inl.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000099#include "vdex_file.h"
David Brazdilca3c8c32016-09-06 14:04:48 +0100100#include "verifier/verifier_deps.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101#include "well_known_classes.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102
103namespace art {
104
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800105using android::base::StringAppendV;
106using android::base::StringPrintf;
107
Andreas Gampee1459ae2016-06-29 09:36:30 -0700108static constexpr size_t kDefaultMinDexFilesForSwap = 2;
109static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB;
110
Mathieu Chartier010126f2017-07-15 15:44:18 -0700111// Compiler filter override for very large apps.
112static constexpr CompilerFilter::Filter kLargeAppFilter = CompilerFilter::kVerify;
113
Brian Carlstrom6449c622014-02-10 23:48:36 -0800114static int original_argc;
115static char** original_argv;
116
117static std::string CommandLine() {
118 std::vector<std::string> command;
119 for (int i = 0; i < original_argc; ++i) {
120 command.push_back(original_argv[i]);
121 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800122 return android::base::Join(command, ' ');
Brian Carlstrom6449c622014-02-10 23:48:36 -0800123}
124
Andreas Gampe046c7062015-05-18 23:22:54 -0700125// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
126// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
127// locations are all staged).
128static std::string StrippedCommandLine() {
129 std::vector<std::string> command;
130
Calin Juravle07c6d722017-06-07 17:06:12 +0000131 // Do a pre-pass to look for zip-fd and the compiler filter.
Andreas Gampe046c7062015-05-18 23:22:54 -0700132 bool saw_zip_fd = false;
Calin Juravle07c6d722017-06-07 17:06:12 +0000133 bool saw_compiler_filter = false;
Andreas Gampe046c7062015-05-18 23:22:54 -0700134 for (int i = 0; i < original_argc; ++i) {
Andreas Gampe9186ced2016-12-12 14:28:21 -0800135 if (android::base::StartsWith(original_argv[i], "--zip-fd=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700136 saw_zip_fd = true;
Andreas Gampe046c7062015-05-18 23:22:54 -0700137 }
Calin Juravle07c6d722017-06-07 17:06:12 +0000138 if (android::base::StartsWith(original_argv[i], "--compiler-filter=")) {
139 saw_compiler_filter = true;
Calin Juravle07c6d722017-06-07 17:06:12 +0000140 }
Andreas Gampe046c7062015-05-18 23:22:54 -0700141 }
142
143 // Now filter out things.
144 for (int i = 0; i < original_argc; ++i) {
145 // All runtime-arg parameters are dropped.
146 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
147 i++; // Drop the next part, too.
148 continue;
149 }
150
151 // Any instruction-setXXX is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800152 if (android::base::StartsWith(original_argv[i], "--instruction-set")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700153 continue;
154 }
155
156 // The boot image is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800157 if (android::base::StartsWith(original_argv[i], "--boot-image=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700158 continue;
159 }
160
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800161 // The image format is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800162 if (android::base::StartsWith(original_argv[i], "--image-format=")) {
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800163 continue;
164 }
165
Andreas Gampe046c7062015-05-18 23:22:54 -0700166 // This should leave any dex-file and oat-file options, describing what we compiled.
167
168 // However, we prefer to drop this when we saw --zip-fd.
169 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700170 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe9186ced2016-12-12 14:28:21 -0800171 if (android::base::StartsWith(original_argv[i], "--zip-") ||
172 android::base::StartsWith(original_argv[i], "--dex-") ||
173 android::base::StartsWith(original_argv[i], "--oat-") ||
174 android::base::StartsWith(original_argv[i], "--swap-") ||
175 android::base::StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700176 continue;
177 }
178 }
179
180 command.push_back(original_argv[i]);
181 }
182
Calin Juravle07c6d722017-06-07 17:06:12 +0000183 if (!saw_compiler_filter) {
184 command.push_back("--compiler-filter=" +
185 CompilerFilter::NameOfFilter(CompilerFilter::kDefaultCompilerFilter));
186 }
187
Andreas Gampe046c7062015-05-18 23:22:54 -0700188 // Construct the final output.
189 if (command.size() <= 1U) {
190 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
191 return "Starting dex2oat.";
192 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800193 return android::base::Join(command, ' ');
Andreas Gampe046c7062015-05-18 23:22:54 -0700194}
195
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196static void UsageErrorV(const char* fmt, va_list ap) {
197 std::string error;
198 StringAppendV(&error, fmt, ap);
199 LOG(ERROR) << error;
200}
201
202static void UsageError(const char* fmt, ...) {
203 va_list ap;
204 va_start(ap, fmt);
205 UsageErrorV(fmt, ap);
206 va_end(ap);
207}
208
Andreas Gampe794ad762015-02-23 08:12:24 -0800209NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 va_list ap;
211 va_start(ap, fmt);
212 UsageErrorV(fmt, ap);
213 va_end(ap);
214
Brian Carlstrom6449c622014-02-10 23:48:36 -0800215 UsageError("Command: %s", CommandLine().c_str());
216
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError("Usage: dex2oat [options]...");
218 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100219 UsageError(" -j<number>: specifies the number of threads used for compilation.");
220 UsageError(" Default is the number of detected hardware threads available on the");
221 UsageError(" host system.");
222 UsageError(" Example: -j12");
223 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700224 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" Example: --dex-file=/system/framework/core.jar");
226 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700227 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
228 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
229 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
230 UsageError(" --dex-location=/system/framework/core.jar");
231 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
233 UsageError(" containing a classes.dex file to compile.");
234 UsageError(" Example: --zip-fd=5");
235 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700236 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
237 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
239 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 UsageError(" Example: --oat-file=/system/framework/boot.oat");
242 UsageError("");
243 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900244 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245 UsageError("");
Shubham Ajmera66205322017-10-06 11:18:51 -0700246 UsageError(" --input-vdex-fd=<number>: specifies the vdex input source via a file descriptor.");
247 UsageError(" Example: --input-vdex-fd=6");
248 UsageError("");
249 UsageError(" --output-vdex-fd=<number>: specifies the vdex output destination via a file");
250 UsageError(" descriptor.");
251 UsageError(" Example: --output-vdex-fd=6");
252 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
254 UsageError(" to the file descriptor specified by --oat-fd.");
255 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
256 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800257 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700258 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
259 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800260 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 UsageError(" Example: --image=/system/framework/boot.art");
262 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800263 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800264 UsageError(" Which format to store the image.");
265 UsageError(" Example: --image-format=lz4");
266 UsageError(" Default: uncompressed");
267 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
269 UsageError(" Example: --image=frameworks/base/preloaded-classes");
270 UsageError("");
271 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
272 UsageError(" Example: --base=0x50000000");
273 UsageError("");
274 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000275 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000277 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000278 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 UsageError("");
280 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
281 UsageError(" Example: --android-root=out/host/linux-x86");
282 UsageError(" Default: $ANDROID_ROOT");
283 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800284 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700285 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700286 UsageError(" Example: --instruction-set=x86");
287 UsageError(" Default: arm");
288 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700289 UsageError(" --instruction-set-features=...,: Specify instruction set features");
290 UsageError(" Example: --instruction-set-features=div");
291 UsageError(" Default: default");
292 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700293 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
294 UsageError(" Default: disabled");
295 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800296 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800298 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100299 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100301 UsageError(" --compiler-filter="
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100302 "(assume-verified"
303 "|extract"
304 "|verify"
305 "|quicken"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000306 "|space-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100307 "|space"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000308 "|speed-profile"
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100309 "|speed"
Andreas Gampe29d38e72016-03-23 15:31:51 +0000310 "|everything-profile"
311 "|everything):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700312 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800313 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800314 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800315 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800316 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
317 UsageError(" method for compiler filter tuning.");
318 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
319 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
320 UsageError("");
321 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
322 UsageError(" method for compiler filter tuning.");
323 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
324 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
325 UsageError("");
326 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
327 UsageError(" method for compiler filter tuning.");
328 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
329 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
330 UsageError("");
331 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
332 UsageError(" method for compiler filter tuning.");
333 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
334 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
335 UsageError("");
336 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
337 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Mathieu Chartier1cc7e8b2016-03-16 14:29:17 -0700338 UsageError(" and the filter is not interpret-only or verify-none or verify-at-runtime, ");
339 UsageError(" overrides the filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800340 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
341 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
342 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100343 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
344 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100345 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
346 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100347 UsageError(" Example: --inline-max-code-units=%d",
348 CompilerOptions::kDefaultInlineMaxCodeUnits);
349 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
350 UsageError("");
Nicolas Geoffraye82b60f2017-12-10 21:50:10 +0000351 UsageError(" --dump-timings: display a breakdown of where time was spent");
Ian Rogers46398602013-08-20 07:50:36 -0700352 UsageError("");
Vladimir Marko2da52b02018-05-08 16:31:34 +0100353 UsageError(" --dump-pass-timings: display a breakdown of time spent in optimization");
354 UsageError(" passes for each compiled method.");
355 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100356 UsageError(" -g");
357 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
358 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky346dc992016-03-13 22:00:07 +0000359 UsageError(" If used without --debuggable, it will be best-effort only.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000360 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700361 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100362 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100363 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000364 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
365 UsageError(" debug information necessary to print backtraces. (disabled by default)");
366 UsageError("");
David Srbecky346dc992016-03-13 22:00:07 +0000367 UsageError(" --no-generate-mini-debug-info: Do not generate backtrace info.");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000368 UsageError("");
Alexey Alexandrovab40c112016-09-19 09:33:49 -0700369 UsageError(" --generate-build-id: Generate GNU-compatible linker build ID ELF section with");
370 UsageError(" SHA-1 of the file content (and thus stable across identical builds)");
371 UsageError("");
372 UsageError(" --no-generate-build-id: Do not generate the build ID ELF section.");
373 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000374 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000375 UsageError("");
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700376 UsageError(" --avoid-storing-invocation: Avoid storing the invocation args in the key value");
377 UsageError(" store. Used to test determinism with different args.");
378 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
380 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
381 UsageError(" Use a separate --runtime-arg switch for each argument.");
382 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700383 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000384 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000386 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
387 UsageError(" Cannot be used together with --profile-file.");
388 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100389 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800390 UsageError(" Example: --swap-file=/data/tmp/swap.001");
391 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100392 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800393 UsageError(" Example: --swap-fd=10");
394 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100395 UsageError(" --swap-dex-size-threshold=<size>: specifies the minimum total dex file size in");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700396 UsageError(" bytes to allow the use of swap.");
397 UsageError(" Example: --swap-dex-size-threshold=1000000");
398 UsageError(" Default: %zu", kDefaultMinDexFileCumulativeSizeForSwap);
399 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100400 UsageError(" --swap-dex-count-threshold=<count>: specifies the minimum number of dex files to");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700401 UsageError(" allow the use of swap.");
402 UsageError(" Example: --swap-dex-count-threshold=10");
403 UsageError(" Default: %zu", kDefaultMinDexFilesForSwap);
404 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100405 UsageError(" --very-large-app-threshold=<size>: specifies the minimum total dex file size in");
Mathieu Chartier010126f2017-07-15 15:44:18 -0700406 UsageError(" bytes to consider the input \"very large\" and reduce compilation done.");
Andreas Gampe67f02822016-06-24 21:05:23 -0700407 UsageError(" Example: --very-large-app-threshold=100000000");
408 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700409 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
Mathieu Chartierf85b3db2018-04-02 18:16:21 -0700410 UsageError(" The image is non-empty only if a profile is passed in.");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700411 UsageError(" Example: --app-image-fd=10");
412 UsageError("");
413 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
414 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
415 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800416 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
417 "input dex file.");
418 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000419 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000420 UsageError("");
Roland Levillainf5bea5e2017-05-02 12:46:07 +0100421 UsageError(" --dump-cfg=<cfg-file>: dump control-flow graphs (CFGs) to specified file.");
422 UsageError(" Example: --dump-cfg=output.cfg");
423 UsageError("");
424 UsageError(" --dump-cfg-append: when dumping CFGs to an existing file, append new CFG data to");
425 UsageError(" existing data (instead of overwriting existing data with new data, which is");
426 UsageError(" the default behavior). This option is only meaningful when used with");
427 UsageError(" --dump-cfg.");
428 UsageError("");
Jeff Hao16d48432017-04-05 17:05:46 -0700429 UsageError(" --classpath-dir=<directory-path>: directory used to resolve relative class paths.");
430 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700431 UsageError(" --class-loader-context=<string spec>: a string specifying the intended");
432 UsageError(" runtime loading context for the compiled dex files.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700433 UsageError("");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700434 UsageError(" --stored-class-loader-context=<string spec>: a string specifying the intended");
435 UsageError(" runtime loading context that is stored in the oat file. Overrides");
436 UsageError(" --class-loader-context. Note that this ignores the classpath_dir arg.");
437 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700438 UsageError(" It describes how the class loader chain should be built in order to ensure");
439 UsageError(" classes are resolved during dex2aot as they would be resolved at runtime.");
440 UsageError(" This spec will be encoded in the oat file. If at runtime the dex file is");
441 UsageError(" loaded in a different context, the oat file will be rejected.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700442 UsageError("");
Calin Juravle1ce70852017-06-28 10:59:03 -0700443 UsageError(" The chain is interpreted in the natural 'parent order', meaning that class");
444 UsageError(" loader 'i+1' will be the parent of class loader 'i'.");
Calin Juravlec79470d2017-07-12 17:37:42 -0700445 UsageError(" The compilation sources will be appended to the classpath of the first class");
446 UsageError(" loader.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700447 UsageError("");
Calin Juravlec79470d2017-07-12 17:37:42 -0700448 UsageError(" E.g. if the context is 'PCL[lib1.dex];DLC[lib2.dex]' and ");
449 UsageError(" --dex-file=src.dex then dex2oat will setup a PathClassLoader with classpath ");
450 UsageError(" 'lib1.dex:src.dex' and set its parent to a DelegateLastClassLoader with ");
451 UsageError(" classpath 'lib2.dex'.");
Calin Juravle1ce70852017-06-28 10:59:03 -0700452 UsageError(" ");
453 UsageError(" Note that the compiler will be tolerant if the source dex files specified");
454 UsageError(" with --dex-file are found in the classpath. The source dex files will be");
455 UsageError(" removed from any class loader's classpath possibly resulting in empty");
456 UsageError(" class loaders.");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700457 UsageError("");
Calin Juravlec79470d2017-07-12 17:37:42 -0700458 UsageError(" Example: --class-loader-context=PCL[lib1.dex:lib2.dex];DLC[lib3.dex]");
Calin Juravle1ce70852017-06-28 10:59:03 -0700459 UsageError("");
Jeff Haoc23b0c02017-07-27 18:19:38 -0700460 UsageError(" --dirty-image-objects=<directory-path>: list of known dirty objects in the image.");
461 UsageError(" The image writer will group them together.");
462 UsageError("");
Mathieu Chartiereafe2a52017-10-19 15:29:42 -0700463 UsageError(" --compact-dex-level=none|fast: None avoids generating compact dex, fast");
Mathieu Chartierddf39552018-04-03 10:22:27 -0700464 UsageError(" generates compact dex with low compile time. If speed-profile is specified as");
465 UsageError(" the compiler filter and the profile is not empty, the default compact dex");
466 UsageError(" level is always used.");
Mathieu Chartiereafe2a52017-10-19 15:29:42 -0700467 UsageError("");
Andreas Gampee20ff6f2017-11-07 15:00:35 -0800468 UsageError(" --deduplicate-code=true|false: enable|disable code deduplication. Deduplicated");
469 UsageError(" code will have an arbitrary symbol tagged with [DEDUPED].");
Andreas Gampecac31ad2017-11-06 20:01:17 -0800470 UsageError("");
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +0000471 UsageError(" --copy-dex-files=true|false: enable|disable copying the dex files into the");
Mathieu Chartier792111c2018-02-15 13:02:15 -0800472 UsageError(" output vdex.");
473 UsageError("");
Calin Juravle0e09dfc2018-02-12 19:01:09 -0800474 UsageError(" --compilation-reason=<string>: optional metadata specifying the reason for");
475 UsageError(" compiling the apk. If specified, the string will be embedded verbatim in");
476 UsageError(" the key value store of the oat file.");
477 UsageError("");
478 UsageError(" Example: --compilation-reason=install");
479 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480 std::cerr << "See log for usage error information\n";
481 exit(EXIT_FAILURE);
482}
483
Brian Carlstrom7940e442013-07-12 13:46:57 -0700484// The primary goal of the watchdog is to prevent stuck build servers
485// during development when fatal aborts lead to a cascade of failures
486// that result in a deadlock.
487class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800488// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700489#undef CHECK_PTHREAD_CALL
490#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
491 do { \
492 int rc = call args; \
493 if (rc != 0) { \
494 errno = rc; \
495 std::string message(# call); \
496 message += " failed for "; \
497 message += reason; \
498 Fatal(message); \
499 } \
500 } while (false)
501
502 public:
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800503 explicit WatchDog(int64_t timeout_in_milliseconds)
Andreas Gampe0f54b0d2017-12-27 08:37:02 -0800504 : timeout_in_milliseconds_(timeout_in_milliseconds),
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800505 shutting_down_(false) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700507 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800508#ifndef __APPLE__
509 pthread_condattr_t condattr;
liulvping8f7101e2017-01-16 15:14:43 +0800510 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_init, (&condattr), reason);
511 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_setclock, (&condattr, CLOCK_MONOTONIC), reason);
512 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, &condattr), reason);
513 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_destroy, (&condattr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800514#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700515 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
516 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
517 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
518 }
519 ~WatchDog() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700520 const char* reason = "dex2oat watch dog thread shutdown";
521 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
522 shutting_down_ = true;
523 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
524 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
525
Kenny Root51316382014-05-13 14:59:37 -0700526 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700527
528 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
529 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
530 }
531
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800532 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
533 // large.
534 static constexpr int64_t kWatchdogVerifyMultiplier =
535 kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
536
537 // When setting timeouts, keep in mind that the build server may not be as fast as your
538 // desktop. Debug builds are slower so they have larger timeouts.
539 static constexpr int64_t kWatchdogSlowdownFactor = kIsDebugBuild ? 5U : 1U;
540
541 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
542 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
543 // itself before that watchdog would take down the system server.
544 static constexpr int64_t kWatchDogTimeoutSeconds = kWatchdogSlowdownFactor * (9 * 60 + 30);
545
546 static constexpr int64_t kDefaultWatchdogTimeoutInMS =
547 kWatchdogVerifyMultiplier * kWatchDogTimeoutSeconds * 1000;
548
Brian Carlstrom7940e442013-07-12 13:46:57 -0700549 private:
550 static void* CallBack(void* arg) {
551 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
552 ::art::SetThreadName("dex2oat watch dog");
553 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700554 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 }
556
Andreas Gampe794ad762015-02-23 08:12:24 -0800557 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700558 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
559 // it's rather easy to hang in unwinding.
560 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
561 // logcat logging or stderr output.
Tomasz Wasilczyk8d840902017-12-20 08:19:53 -0800562 LogHelper::LogLineLowStack(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
563
Andreas Gampe48fde372017-06-06 07:43:46 -0700564 // If we're on the host, try to dump all threads to get a sense of what's going on. This is
565 // restricted to the host as the dump may itself go bad.
566 // TODO: Use a double watchdog timeout, so we can enable this on-device.
567 if (!kIsTargetBuild && Runtime::Current() != nullptr) {
Andreas Gampecd607312017-06-05 17:03:05 -0700568 Runtime::Current()->AttachCurrentThread("Watchdog thread attached for dumping",
569 true,
570 nullptr,
571 false);
572 Runtime::Current()->DumpForSigQuit(std::cerr);
573 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574 exit(1);
575 }
576
577 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 timespec timeout_ts;
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800579#if defined(__APPLE__)
580 InitTimeSpec(true, CLOCK_REALTIME, timeout_in_milliseconds_, 0, &timeout_ts);
581#else
liulvping8f7101e2017-01-16 15:14:43 +0800582 InitTimeSpec(true, CLOCK_MONOTONIC, timeout_in_milliseconds_, 0, &timeout_ts);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800583#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700584 const char* reason = "dex2oat watch dog thread waiting";
585 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
586 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800587 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700588 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700589 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800590 timeout_in_milliseconds_/1000));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700591 } else if (rc != 0) {
592 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
593 strerror(errno)));
594 Fatal(message.c_str());
595 }
596 }
597 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
598 }
599
Brian Carlstrom7940e442013-07-12 13:46:57 -0700600 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
601 pthread_mutex_t mutex_;
602 pthread_cond_t cond_;
603 pthread_attr_t attr_;
604 pthread_t pthread_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700605
606 const int64_t timeout_in_milliseconds_;
607 bool shutting_down_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700609
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800610class Dex2Oat FINAL {
611 public:
612 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100613 compiler_kind_(Compiler::kOptimizing),
Vladimir Marko33bff252017-11-01 14:35:42 +0000614 instruction_set_(kRuntimeISA == InstructionSet::kArm ? InstructionSet::kThumb2 : kRuntimeISA),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800615 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000616 image_file_location_oat_checksum_(0),
617 image_file_location_oat_data_begin_(0),
618 image_patch_delta_(0),
619 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700620 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800621 runtime_(nullptr),
622 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
623 start_ns_(NanoTime()),
Andreas Gampec560fc02014-07-16 09:57:39 -0700624 start_cputime_ns_(ProcessCpuNanoTime()),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800625 oat_fd_(-1),
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000626 input_vdex_fd_(-1),
627 output_vdex_fd_(-1),
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000628 input_vdex_file_(nullptr),
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +0000629 dm_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800630 zip_fd_(-1),
631 image_base_(0U),
632 image_classes_zip_filename_(nullptr),
633 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800634 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700635 passes_to_run_filename_(nullptr),
Mathieu Chartierff0baff2017-08-02 23:04:19 -0700636 dirty_image_objects_filename_(nullptr),
Jeff Hao436183f2016-01-12 16:36:50 -0800637 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800638 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000639 elf_writers_(),
640 oat_writers_(),
641 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000642 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700643 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000644 opened_dex_files_maps_(),
645 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000646 no_inline_from_dex_files_(),
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700647 avoid_storing_invocation_(false),
Calin Juravle2e2db782016-02-23 12:00:03 +0000648 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800649 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000650 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800651 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000652 force_determinism_(false)
653 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800654
655 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800656 // Log completion time before deleting the runtime_, because this accesses
657 // the runtime.
658 LogCompletionTime();
659
Vladimir Marko307dac92015-10-20 11:20:09 +0100660 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
661 // We want to just exit on non-debug builds, not bringing the runtime down
662 // in an orderly fashion. So release the following fields.
663 driver_.release();
664 image_writer_.release();
665 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
666 dex_file.release();
667 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000668 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
669 map.release();
670 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100671 for (std::unique_ptr<File>& vdex_file : vdex_files_) {
672 vdex_file.release();
673 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800674 for (std::unique_ptr<File>& oat_file : oat_files_) {
675 oat_file.release();
676 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100677 runtime_.release();
678 verification_results_.release();
679 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100680 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700681 }
682
Roland Levillain9ec5e222015-08-17 20:18:41 +0100683 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800684 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800685 std::string boot_image_filename;
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800686 int64_t watch_dog_timeout_in_ms = -1;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800687 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000688 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800689 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100690 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800691
Andreas Gampe097f34c2017-08-23 08:57:51 -0700692 void ParseBase(const std::string& option) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100693 char* end;
Andreas Gampe097f34c2017-08-23 08:57:51 -0700694 image_base_ = strtoul(option.c_str(), &end, 16);
695 if (end == option.c_str() || *end != '\0') {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100696 Usage("Failed to parse hexadecimal value for option %s", option.data());
697 }
698 }
699
Shubham Ajmera188b2bf2017-09-20 15:53:35 -0700700 bool VerifyProfileData() {
701 return profile_compilation_info_->VerifyProfileData(dex_files_);
702 }
703
Andreas Gampe097f34c2017-08-23 08:57:51 -0700704 void ParseInstructionSetVariant(const std::string& option, ParserOptions* parser_options) {
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800705 instruction_set_features_ = InstructionSetFeatures::FromVariant(
Andreas Gampe097f34c2017-08-23 08:57:51 -0700706 instruction_set_, option, &parser_options->error_msg);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100707 if (instruction_set_features_.get() == nullptr) {
708 Usage("%s", parser_options->error_msg.c_str());
709 }
710 }
711
Andreas Gampe097f34c2017-08-23 08:57:51 -0700712 void ParseInstructionSetFeatures(const std::string& option, ParserOptions* parser_options) {
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800713 if (instruction_set_features_ == nullptr) {
714 instruction_set_features_ = InstructionSetFeatures::FromVariant(
715 instruction_set_, "default", &parser_options->error_msg);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100716 if (instruction_set_features_.get() == nullptr) {
717 Usage("Problem initializing default instruction set features variant: %s",
718 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 }
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800721 instruction_set_features_ =
Andreas Gampe097f34c2017-08-23 08:57:51 -0700722 instruction_set_features_->AddFeaturesFromString(option, &parser_options->error_msg);
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800723 if (instruction_set_features_ == nullptr) {
Andreas Gampe097f34c2017-08-23 08:57:51 -0700724 Usage("Error parsing '%s': %s", option.c_str(), parser_options->error_msg.c_str());
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800725 }
726 }
727
Jeff Hao436183f2016-01-12 16:36:50 -0800728 void ProcessOptions(ParserOptions* parser_options) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000729 compiler_options_->boot_image_ = !image_filenames_.empty();
730 compiler_options_->app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700731
Roland Levillain2b03a1f2017-06-06 16:09:59 +0100732 if (IsBootImage() && image_filenames_.size() == 1) {
733 const std::string& boot_image_filename = image_filenames_[0];
734 compiler_options_->core_image_ = CompilerDriver::IsCoreImageFilename(boot_image_filename);
735 }
736
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700737 if (IsAppImage() && IsBootImage()) {
738 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
739 }
740
Jeff Haodcdc85b2015-12-04 14:06:18 -0800741 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800742 Usage("Output must be supplied with either --oat-file or --oat-fd");
743 }
744
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000745 if (input_vdex_fd_ != -1 && !input_vdex_.empty()) {
746 Usage("Can't have both --input-vdex-fd and --input-vdex");
747 }
748
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100749 if (output_vdex_fd_ != -1 && !output_vdex_.empty()) {
750 Usage("Can't have both --output-vdex-fd and --output-vdex");
751 }
752
Jeff Haodcdc85b2015-12-04 14:06:18 -0800753 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 Usage("--oat-file should not be used with --oat-fd");
755 }
756
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000757 if ((output_vdex_fd_ == -1) != (oat_fd_ == -1)) {
Sascha Roth5f71c652018-04-10 00:27:15 +0200758 Usage("VDEX and OAT output must be specified either with one --oat-file "
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000759 "or with --oat-fd and --output-vdex-fd file descriptors");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100760 }
761
Roland Levillain9ec5e222015-08-17 20:18:41 +0100762 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800763 Usage("--oat-symbols should not be used with --oat-fd");
764 }
765
Roland Levillain9ec5e222015-08-17 20:18:41 +0100766 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800767 Usage("--oat-symbols should not be used with --host");
768 }
769
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000770 if (output_vdex_fd_ != -1 && !image_filenames_.empty()) {
771 Usage("--output-vdex-fd should not be used with --image");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100772 }
773
Jeff Haodcdc85b2015-12-04 14:06:18 -0800774 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800775 Usage("--oat-fd should not be used with --image");
776 }
777
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +0000778 if ((input_vdex_fd_ != -1 || !input_vdex_.empty()) &&
779 (dm_fd_ != -1 || !dm_file_location_.empty())) {
780 Usage("An input vdex should not be passed with a .dm file");
781 }
782
Jeff Haodcdc85b2015-12-04 14:06:18 -0800783 if (!parser_options->oat_symbols.empty() &&
784 parser_options->oat_symbols.size() != oat_filenames_.size()) {
785 Usage("--oat-file arguments do not match --oat-symbols arguments");
786 }
787
788 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
789 Usage("--oat-file arguments do not match --image arguments");
790 }
791
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800792 if (android_root_.empty()) {
793 const char* android_root_env_var = getenv("ANDROID_ROOT");
794 if (android_root_env_var == nullptr) {
795 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700796 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800797 android_root_ += android_root_env_var;
798 }
799
Vladimir Markoaad75c62016-10-03 08:46:48 +0000800 if (!IsBootImage() && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100801 parser_options->boot_image_filename += android_root_;
802 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800803 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100804 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000805 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800806 }
807
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700808 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800809 Usage("--image-classes should only be used with --image");
810 }
811
Vladimir Marko49b0f452015-12-10 13:49:19 +0000812 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800813 Usage("--image-classes should not be used with --boot-image");
814 }
815
816 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
817 Usage("--image-classes-zip should be used with --image-classes");
818 }
819
820 if (dex_filenames_.empty() && zip_fd_ == -1) {
821 Usage("Input must be supplied with either --dex-file or --zip-fd");
822 }
823
824 if (!dex_filenames_.empty() && zip_fd_ != -1) {
825 Usage("--dex-file should not be used with --zip-fd");
826 }
827
828 if (!dex_filenames_.empty() && !zip_location_.empty()) {
829 Usage("--dex-file should not be used with --zip-location");
830 }
831
832 if (dex_locations_.empty()) {
833 for (const char* dex_file_name : dex_filenames_) {
834 dex_locations_.push_back(dex_file_name);
835 }
836 } else if (dex_locations_.size() != dex_filenames_.size()) {
837 Usage("--dex-location arguments do not match --dex-file arguments");
838 }
839
Jeff Haodcdc85b2015-12-04 14:06:18 -0800840 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
841 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
842 Usage("--oat-file arguments must be singular or match --dex-file arguments");
843 }
844 }
845
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800846 if (zip_fd_ != -1 && zip_location_.empty()) {
847 Usage("--zip-location should be supplied with --zip-fd");
848 }
849
Vladimir Marko49b0f452015-12-10 13:49:19 +0000850 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800851 if (image_base_ == 0) {
852 Usage("Non-zero --base not specified");
853 }
854 }
855
Mathieu Chartiera8077802016-03-16 19:08:31 -0700856 const bool have_profile_file = !profile_file_.empty();
857 const bool have_profile_fd = profile_file_fd_ != kInvalidFd;
858 if (have_profile_file && have_profile_fd) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000859 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200860 }
861
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700862 if (have_profile_file || have_profile_fd) {
Andreas Gampebd600e32018-04-12 14:25:39 -0700863 if (image_classes_filename_ != nullptr ||
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700864 image_classes_zip_filename_ != nullptr) {
865 Usage("Profile based image creation is not supported with image or compiled classes");
866 }
867 }
868
Roland Levillain9ec5e222015-08-17 20:18:41 +0100869 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800870 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800871 }
872
873 // If no instruction set feature was given, use the default one for the target
874 // instruction set.
875 if (instruction_set_features_.get() == nullptr) {
Andreas Gampe0415b4e2015-01-06 15:17:07 -0800876 instruction_set_features_ = InstructionSetFeatures::FromVariant(
877 instruction_set_, "default", &parser_options->error_msg);
Ian Rogersd582fa42014-11-05 23:46:43 -0800878 if (instruction_set_features_.get() == nullptr) {
879 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100880 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800881 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800882 }
883
884 if (instruction_set_ == kRuntimeISA) {
885 std::unique_ptr<const InstructionSetFeatures> runtime_features(
886 InstructionSetFeatures::FromCppDefines());
887 if (!instruction_set_features_->Equals(runtime_features.get())) {
888 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
889 << *instruction_set_features_ << ") and those of dex2oat executable ("
890 << *runtime_features <<") for the command line:\n"
891 << CommandLine();
892 }
893 }
894
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000895 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000896 compiler_options_->inline_max_code_units_ = CompilerOptions::kDefaultInlineMaxCodeUnits;
Roland Levillaina215b952015-08-07 11:38:32 +0100897 }
898
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800899 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800900 // Set the compilation target's implicit checks options.
901 switch (instruction_set_) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000902 case InstructionSet::kArm:
903 case InstructionSet::kThumb2:
904 case InstructionSet::kArm64:
905 case InstructionSet::kX86:
906 case InstructionSet::kX86_64:
907 case InstructionSet::kMips:
908 case InstructionSet::kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000909 compiler_options_->implicit_null_checks_ = true;
910 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800911 break;
912
913 default:
914 // Defaults are correct.
915 break;
916 }
917
Jeff Hao436183f2016-01-12 16:36:50 -0800918 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800919 Usage("--multi-image can only be used when creating boot images");
920 }
Jeff Hao436183f2016-01-12 16:36:50 -0800921 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800922 Usage("--multi-image cannot be used with multiple image names");
923 }
924
925 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
926 if (!kIsTargetBuild && IsBootImage()) {
927 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800928 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800929 }
930 }
931
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800932 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100933 if (parser_options->watch_dog_enabled) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800934 int64_t timeout = parser_options->watch_dog_timeout_in_ms > 0
935 ? parser_options->watch_dog_timeout_in_ms
936 : WatchDog::kDefaultWatchdogTimeoutInMS;
937 watchdog_.reset(new WatchDog(timeout));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800938 }
939
940 // Fill some values into the key-value store for the oat header.
941 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800942
Roland Levillainb81e9e92017-04-20 17:35:32 +0100943 // Automatically force determinism for the boot image in a host build if read barriers
944 // are enabled, or if the default GC is CMS or MS. When the default GC is CMS
945 // (Concurrent Mark-Sweep), the GC is switched to a non-concurrent one by passing the
946 // option `-Xgc:nonconcurrent` (see below).
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800947 if (!kIsTargetBuild && IsBootImage()) {
948 if (SupportsDeterministicCompilation()) {
949 force_determinism_ = true;
950 } else {
951 LOG(WARNING) << "Deterministic compilation is disabled.";
952 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800953 }
954 compiler_options_->force_determinism_ = force_determinism_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700955
956 if (passes_to_run_filename_ != nullptr) {
957 passes_to_run_.reset(ReadCommentedInputFromFile<std::vector<std::string>>(
958 passes_to_run_filename_,
959 nullptr)); // No post-processing.
960 if (passes_to_run_.get() == nullptr) {
961 Usage("Failed to read list of passes to run.");
962 }
963 }
964 compiler_options_->passes_to_run_ = passes_to_run_.get();
Roland Levillain9ec5e222015-08-17 20:18:41 +0100965 }
966
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800967 static bool SupportsDeterministicCompilation() {
Roland Levillainb81e9e92017-04-20 17:35:32 +0100968 return (kUseReadBarrier ||
969 gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
970 gc::kCollectorTypeDefault == gc::kCollectorTypeMS);
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800971 }
972
Jeff Hao436183f2016-01-12 16:36:50 -0800973 void ExpandOatAndImageFilenames() {
974 std::string base_oat = oat_filenames_[0];
975 size_t last_oat_slash = base_oat.rfind('/');
976 if (last_oat_slash == std::string::npos) {
977 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
978 }
979 // We also need to honor path components that were encoded through '@'. Otherwise the loading
980 // code won't be able to find the images.
981 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
982 last_oat_slash = base_oat.rfind('@');
983 }
984 base_oat = base_oat.substr(0, last_oat_slash + 1);
985
986 std::string base_img = image_filenames_[0];
987 size_t last_img_slash = base_img.rfind('/');
988 if (last_img_slash == std::string::npos) {
989 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
990 }
991 // We also need to honor path components that were encoded through '@'. Otherwise the loading
992 // code won't be able to find the images.
993 if (base_img.find('@', last_img_slash) != std::string::npos) {
994 last_img_slash = base_img.rfind('@');
995 }
996
997 // Get the prefix, which is the primary image name (without path components). Strip the
998 // extension.
999 std::string prefix = base_img.substr(last_img_slash + 1);
1000 if (prefix.rfind('.') != std::string::npos) {
1001 prefix = prefix.substr(0, prefix.rfind('.'));
1002 }
1003 if (!prefix.empty()) {
1004 prefix = prefix + "-";
1005 }
1006
1007 base_img = base_img.substr(0, last_img_slash + 1);
1008
1009 // Note: we have some special case here for our testing. We have to inject the differentiating
1010 // parts for the different core images.
1011 std::string infix; // Empty infix by default.
1012 {
1013 // Check the first name.
1014 std::string dex_file = oat_filenames_[0];
1015 size_t last_dex_slash = dex_file.rfind('/');
1016 if (last_dex_slash != std::string::npos) {
1017 dex_file = dex_file.substr(last_dex_slash + 1);
1018 }
1019 size_t last_dex_dot = dex_file.rfind('.');
1020 if (last_dex_dot != std::string::npos) {
1021 dex_file = dex_file.substr(0, last_dex_dot);
1022 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001023 if (android::base::StartsWith(dex_file, "core-")) {
Jeff Hao436183f2016-01-12 16:36:50 -08001024 infix = dex_file.substr(strlen("core"));
1025 }
1026 }
1027
bowen_lai8bd36c02016-10-12 13:28:55 +08001028 std::string base_symbol_oat;
1029 if (!oat_unstripped_.empty()) {
1030 base_symbol_oat = oat_unstripped_[0];
1031 size_t last_symbol_oat_slash = base_symbol_oat.rfind('/');
1032 if (last_symbol_oat_slash == std::string::npos) {
1033 Usage("--multi-image used with unusable symbol filename %s", base_symbol_oat.c_str());
1034 }
1035 base_symbol_oat = base_symbol_oat.substr(0, last_symbol_oat_slash + 1);
1036 }
1037
Jeff Hao436183f2016-01-12 16:36:50 -08001038 // Now create the other names. Use a counted loop to skip the first one.
1039 for (size_t i = 1; i < dex_locations_.size(); ++i) {
1040 // TODO: Make everything properly std::string.
1041 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
Andreas Gampe097f34c2017-08-23 08:57:51 -07001042 char_backing_storage_.push_front(base_img + image_name);
1043 image_filenames_.push_back(char_backing_storage_.front().c_str());
Jeff Hao436183f2016-01-12 16:36:50 -08001044
1045 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
Andreas Gampe097f34c2017-08-23 08:57:51 -07001046 char_backing_storage_.push_front(base_oat + oat_name);
1047 oat_filenames_.push_back(char_backing_storage_.front().c_str());
bowen_lai8bd36c02016-10-12 13:28:55 +08001048
1049 if (!base_symbol_oat.empty()) {
Andreas Gampe097f34c2017-08-23 08:57:51 -07001050 char_backing_storage_.push_front(base_symbol_oat + oat_name);
1051 oat_unstripped_.push_back(char_backing_storage_.front().c_str());
bowen_lai8bd36c02016-10-12 13:28:55 +08001052 }
Jeff Hao436183f2016-01-12 16:36:50 -08001053 }
1054 }
1055
Andreas Gampe8994a042015-12-30 19:03:17 +00001056 // Modify the input string in the following way:
1057 // 0) Assume input is /a/b/c.d
1058 // 1) Strip the path -> c.d
1059 // 2) Inject prefix p -> pc.d
1060 // 3) Inject infix i -> pci.d
1061 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001062 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001063 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001064 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001065 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001066 size_t last_dex_slash = in.rfind('/');
1067 if (last_dex_slash != std::string::npos) {
1068 in = in.substr(last_dex_slash + 1);
1069 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001070 if (!prefix.empty()) {
1071 in = prefix + in;
1072 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001073 if (!infix.empty()) {
1074 // Inject infix.
1075 size_t last_dot = in.rfind('.');
1076 if (last_dot != std::string::npos) {
1077 in.insert(last_dot, infix);
1078 }
1079 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001080 if (android::base::EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001081 in = in.substr(0, in.length() - strlen(".jar")) +
1082 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001083 }
1084 return in;
1085 }
1086
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001087 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001088 std::ostringstream oss;
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07001089 if (!avoid_storing_invocation_) {
1090 for (int i = 0; i < argc; ++i) {
1091 if (i > 0) {
1092 oss << ' ';
1093 }
1094 oss << argv[i];
Roland Levillain9ec5e222015-08-17 20:18:41 +01001095 }
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07001096 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1097 oss.str(""); // Reset.
Roland Levillain9ec5e222015-08-17 20:18:41 +01001098 }
Roland Levillain9ec5e222015-08-17 20:18:41 +01001099 oss << kRuntimeISA;
1100 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1101 key_value_store_->Put(
1102 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001103 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001104 key_value_store_->Put(
1105 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001106 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Srbecky5d950762016-03-07 20:47:29 +00001107 key_value_store_->Put(
1108 OatHeader::kNativeDebuggableKey,
David Srbecky346dc992016-03-13 22:00:07 +00001109 compiler_options_->GetNativeDebuggable() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe29d38e72016-03-23 15:31:51 +00001110 key_value_store_->Put(OatHeader::kCompilerFilter,
1111 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
Andreas Gampef8cd8902017-01-18 16:05:01 -08001112 key_value_store_->Put(OatHeader::kConcurrentCopying,
1113 kUseReadBarrier ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001114 }
1115
Andreas Gampe097f34c2017-08-23 08:57:51 -07001116 // This simple forward is here so the string specializations below don't look out of place.
1117 template <typename T, typename U>
1118 void AssignIfExists(Dex2oatArgumentMap& map,
1119 const Dex2oatArgumentMap::Key<T>& key,
1120 U* out) {
1121 map.AssignIfExists(key, out);
1122 }
1123
1124 // Specializations to handle const char* vs std::string.
1125 void AssignIfExists(Dex2oatArgumentMap& map,
1126 const Dex2oatArgumentMap::Key<std::string>& key,
1127 const char** out) {
1128 if (map.Exists(key)) {
1129 char_backing_storage_.push_front(std::move(*map.Get(key)));
1130 *out = char_backing_storage_.front().c_str();
1131 }
1132 }
1133 void AssignIfExists(Dex2oatArgumentMap& map,
1134 const Dex2oatArgumentMap::Key<std::vector<std::string>>& key,
1135 std::vector<const char*>* out) {
1136 if (map.Exists(key)) {
1137 for (auto& val : *map.Get(key)) {
1138 char_backing_storage_.push_front(std::move(val));
1139 out->push_back(char_backing_storage_.front().c_str());
1140 }
1141 }
1142 }
1143
1144 template <typename T>
1145 void AssignTrueIfExists(Dex2oatArgumentMap& map,
1146 const Dex2oatArgumentMap::Key<T>& key,
1147 bool* out) {
1148 if (map.Exists(key)) {
1149 *out = true;
1150 }
1151 }
1152
Roland Levillain9ec5e222015-08-17 20:18:41 +01001153 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1154 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1155 // returns, arguments have been successfully parsed.
1156 void ParseArgs(int argc, char** argv) {
1157 original_argc = argc;
1158 original_argv = argv;
1159
David Sehrc431b9d2018-03-02 12:01:51 -08001160 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -07001161 InitLogging(argv, Runtime::Abort);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001162
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001163 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001164
Andreas Gampe097f34c2017-08-23 08:57:51 -07001165 using M = Dex2oatArgumentMap;
1166 std::string error_msg;
1167 std::unique_ptr<M> args_uptr = M::Parse(argc, const_cast<const char**>(argv), &error_msg);
1168 if (args_uptr == nullptr) {
1169 Usage("Failed to parse command line: %s", error_msg.c_str());
1170 UNREACHABLE();
1171 }
1172
1173 M& args = *args_uptr;
1174
1175 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
1176
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07001177 AssignIfExists(args, M::CompactDexLevel, &compact_dex_level_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001178 AssignIfExists(args, M::DexFiles, &dex_filenames_);
1179 AssignIfExists(args, M::DexLocations, &dex_locations_);
1180 AssignIfExists(args, M::OatFiles, &oat_filenames_);
1181 AssignIfExists(args, M::OatSymbols, &parser_options->oat_symbols);
1182 AssignIfExists(args, M::ImageFilenames, &image_filenames_);
1183 AssignIfExists(args, M::ZipFd, &zip_fd_);
1184 AssignIfExists(args, M::ZipLocation, &zip_location_);
1185 AssignIfExists(args, M::InputVdexFd, &input_vdex_fd_);
1186 AssignIfExists(args, M::OutputVdexFd, &output_vdex_fd_);
1187 AssignIfExists(args, M::InputVdex, &input_vdex_);
1188 AssignIfExists(args, M::OutputVdex, &output_vdex_);
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001189 AssignIfExists(args, M::DmFd, &dm_fd_);
1190 AssignIfExists(args, M::DmFile, &dm_file_location_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001191 AssignIfExists(args, M::OatFd, &oat_fd_);
1192 AssignIfExists(args, M::OatLocation, &oat_location_);
1193 AssignIfExists(args, M::Watchdog, &parser_options->watch_dog_enabled);
1194 AssignIfExists(args, M::WatchdogTimeout, &parser_options->watch_dog_timeout_in_ms);
1195 AssignIfExists(args, M::Threads, &thread_count_);
1196 AssignIfExists(args, M::ImageClasses, &image_classes_filename_);
1197 AssignIfExists(args, M::ImageClassesZip, &image_classes_zip_filename_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001198 AssignIfExists(args, M::Passes, &passes_to_run_filename_);
1199 AssignIfExists(args, M::BootImage, &parser_options->boot_image_filename);
1200 AssignIfExists(args, M::AndroidRoot, &android_root_);
1201 AssignIfExists(args, M::Profile, &profile_file_);
1202 AssignIfExists(args, M::ProfileFd, &profile_file_fd_);
1203 AssignIfExists(args, M::RuntimeOptions, &runtime_args_);
1204 AssignIfExists(args, M::SwapFile, &swap_file_name_);
1205 AssignIfExists(args, M::SwapFileFd, &swap_fd_);
1206 AssignIfExists(args, M::SwapDexSizeThreshold, &min_dex_file_cumulative_size_for_swap_);
1207 AssignIfExists(args, M::SwapDexCountThreshold, &min_dex_files_for_swap_);
1208 AssignIfExists(args, M::VeryLargeAppThreshold, &very_large_threshold_);
1209 AssignIfExists(args, M::AppImageFile, &app_image_file_name_);
1210 AssignIfExists(args, M::AppImageFileFd, &app_image_fd_);
1211 AssignIfExists(args, M::NoInlineFrom, &no_inline_from_string_);
1212 AssignIfExists(args, M::ClasspathDir, &classpath_dir_);
1213 AssignIfExists(args, M::DirtyImageObjects, &dirty_image_objects_filename_);
1214 AssignIfExists(args, M::ImageFormat, &image_storage_mode_);
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001215 AssignIfExists(args, M::CompilationReason, &compilation_reason_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001216
1217 AssignIfExists(args, M::Backend, &compiler_kind_);
1218 parser_options->requested_specific_compiler = args.Exists(M::Backend);
1219
1220 AssignIfExists(args, M::TargetInstructionSet, &instruction_set_);
1221 // arm actually means thumb2.
1222 if (instruction_set_ == InstructionSet::kArm) {
1223 instruction_set_ = InstructionSet::kThumb2;
1224 }
1225
1226 AssignTrueIfExists(args, M::Host, &is_host_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001227 AssignTrueIfExists(args, M::AvoidStoringInvocation, &avoid_storing_invocation_);
1228 AssignTrueIfExists(args, M::MultiImage, &multi_image_);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001229 AssignIfExists(args, M::CopyDexFiles, &copy_dex_files_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001230
1231 if (args.Exists(M::ForceDeterminism)) {
1232 if (!SupportsDeterministicCompilation()) {
1233 Usage("Option --force-determinism requires read barriers or a CMS/MS garbage collector");
Roland Levillain9ec5e222015-08-17 20:18:41 +01001234 }
Andreas Gampe097f34c2017-08-23 08:57:51 -07001235 force_determinism_ = true;
1236 }
1237
1238 if (args.Exists(M::Base)) {
1239 ParseBase(*args.Get(M::Base));
1240 }
1241 if (args.Exists(M::TargetInstructionSetVariant)) {
1242 ParseInstructionSetVariant(*args.Get(M::TargetInstructionSetVariant), parser_options.get());
1243 }
1244 if (args.Exists(M::TargetInstructionSetFeatures)) {
1245 ParseInstructionSetFeatures(*args.Get(M::TargetInstructionSetFeatures), parser_options.get());
1246 }
1247 if (args.Exists(M::ClassLoaderContext)) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001248 std::string class_loader_context_arg = *args.Get(M::ClassLoaderContext);
1249 class_loader_context_ = ClassLoaderContext::Create(class_loader_context_arg);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001250 if (class_loader_context_ == nullptr) {
1251 Usage("Option --class-loader-context has an incorrect format: %s",
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001252 class_loader_context_arg.c_str());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001253 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001254 if (args.Exists(M::StoredClassLoaderContext)) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07001255 const std::string stored_context_arg = *args.Get(M::StoredClassLoaderContext);
1256 stored_class_loader_context_ = ClassLoaderContext::Create(stored_context_arg);
1257 if (stored_class_loader_context_ == nullptr) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001258 Usage("Option --stored-class-loader-context has an incorrect format: %s",
Mathieu Chartierc4440772018-04-16 14:40:56 -07001259 stored_context_arg.c_str());
Vladimir Markod8860b42018-05-02 14:58:12 +01001260 } else if (class_loader_context_->VerifyClassLoaderContextMatch(
Mathieu Chartierc4440772018-04-16 14:40:56 -07001261 stored_context_arg,
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001262 /*verify_names*/ false,
Vladimir Markod8860b42018-05-02 14:58:12 +01001263 /*verify_checksums*/ false) != ClassLoaderContext::VerificationResult::kVerifies) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001264 Usage(
1265 "Option --stored-class-loader-context '%s' mismatches --class-loader-context '%s'",
Mathieu Chartierc4440772018-04-16 14:40:56 -07001266 stored_context_arg.c_str(),
1267 class_loader_context_arg.c_str());
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001268 }
1269 }
1270 } else if (args.Exists(M::StoredClassLoaderContext)) {
1271 Usage("Option --stored-class-loader-context should only be used if "
1272 "--class-loader-context is also specified");
Roland Levillain9ec5e222015-08-17 20:18:41 +01001273 }
1274
Andreas Gampe097f34c2017-08-23 08:57:51 -07001275 if (!ReadCompilerOptions(args, compiler_options_.get(), &error_msg)) {
1276 Usage(error_msg.c_str());
1277 }
1278
Jeff Hao436183f2016-01-12 16:36:50 -08001279 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001280
1281 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001282 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001283 }
1284
Jeff Haodcdc85b2015-12-04 14:06:18 -08001285 // Check whether the oat output files are writable, and open them for later. Also open a swap
1286 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001287 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001288 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1289 PruneNonExistentDexFiles();
1290
Jeff Hao436183f2016-01-12 16:36:50 -08001291 // Expand oat and image filenames for multi image.
1292 if (IsBootImage() && multi_image_) {
1293 ExpandOatAndImageFilenames();
1294 }
1295
David Brazdil7b49e6c2016-09-01 11:06:18 +01001296 // OAT and VDEX file handling
David Brazdil7b49e6c2016-09-01 11:06:18 +01001297 if (oat_fd_ == -1) {
1298 DCHECK(!oat_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001299 for (const char* oat_filename : oat_filenames_) {
1300 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
Calin Juravleb09be722017-09-25 16:42:48 -07001301 if (oat_file == nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001302 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1303 return false;
1304 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001305 if (fchmod(oat_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001306 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1307 oat_file->Erase();
1308 return false;
1309 }
1310 oat_files_.push_back(std::move(oat_file));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001311 DCHECK_EQ(input_vdex_fd_, -1);
1312 if (!input_vdex_.empty()) {
1313 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001314 input_vdex_file_ = VdexFile::Open(input_vdex_,
1315 /* writable */ false,
1316 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001317 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001318 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001319 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001320
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001321 DCHECK_EQ(output_vdex_fd_, -1);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01001322 std::string vdex_filename = output_vdex_.empty()
1323 ? ReplaceFileExtension(oat_filename, "vdex")
1324 : output_vdex_;
1325 if (vdex_filename == input_vdex_ && output_vdex_.empty()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001326 update_input_vdex_ = true;
1327 std::unique_ptr<File> vdex_file(OS::OpenFileReadWrite(vdex_filename.c_str()));
1328 vdex_files_.push_back(std::move(vdex_file));
1329 } else {
1330 std::unique_ptr<File> vdex_file(OS::CreateEmptyFile(vdex_filename.c_str()));
Calin Juravleb09be722017-09-25 16:42:48 -07001331 if (vdex_file == nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001332 PLOG(ERROR) << "Failed to open vdex file: " << vdex_filename;
1333 return false;
1334 }
1335 if (fchmod(vdex_file->Fd(), 0644) != 0) {
1336 PLOG(ERROR) << "Failed to make vdex file world readable: " << vdex_filename;
1337 vdex_file->Erase();
1338 return false;
1339 }
1340 vdex_files_.push_back(std::move(vdex_file));
David Brazdil7b49e6c2016-09-01 11:06:18 +01001341 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001342 }
1343 } else {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001344 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, /* check_usage */ true));
Calin Juravleb09be722017-09-25 16:42:48 -07001345 if (oat_file == nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001346 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1347 return false;
1348 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001349 oat_file->DisableAutoClose();
1350 if (oat_file->SetLength(0) != 0) {
1351 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
Calin Juravleb09be722017-09-25 16:42:48 -07001352 oat_file->Erase();
1353 return false;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001354 }
1355 oat_files_.push_back(std::move(oat_file));
1356
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001357 if (input_vdex_fd_ != -1) {
1358 struct stat s;
1359 int rc = TEMP_FAILURE_RETRY(fstat(input_vdex_fd_, &s));
1360 if (rc == -1) {
1361 PLOG(WARNING) << "Failed getting length of vdex file";
1362 } else {
1363 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001364 input_vdex_file_ = VdexFile::Open(input_vdex_fd_,
1365 s.st_size,
1366 "vdex",
1367 /* writable */ false,
1368 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001369 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001370 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001371 // If there's any problem with the passed vdex, just warn and proceed
1372 // without it.
1373 if (input_vdex_file_ == nullptr) {
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001374 PLOG(WARNING) << "Failed opening vdex file: " << error_msg;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001375 }
1376 }
1377 }
1378
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001379 DCHECK_NE(output_vdex_fd_, -1);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001380 std::string vdex_location = ReplaceFileExtension(oat_location_, "vdex");
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001381 std::unique_ptr<File> vdex_file(new File(output_vdex_fd_, vdex_location, /* check_usage */ true));
Calin Juravleb09be722017-09-25 16:42:48 -07001382 if (vdex_file == nullptr) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001383 PLOG(ERROR) << "Failed to create vdex file: " << vdex_location;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001384 return false;
1385 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001386 vdex_file->DisableAutoClose();
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001387 if (input_vdex_file_ != nullptr && output_vdex_fd_ == input_vdex_fd_) {
1388 update_input_vdex_ = true;
1389 } else {
1390 if (vdex_file->SetLength(0) != 0) {
1391 PLOG(ERROR) << "Truncating vdex file " << vdex_location << " failed.";
Calin Juravleb09be722017-09-25 16:42:48 -07001392 vdex_file->Erase();
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001393 return false;
1394 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001395 }
1396 vdex_files_.push_back(std::move(vdex_file));
1397
Jeff Haodcdc85b2015-12-04 14:06:18 -08001398 oat_filenames_.push_back(oat_location_.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001399 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001400
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001401 // If we're updating in place a vdex file, be defensive and put an invalid vdex magic in case
1402 // dex2oat gets killed.
1403 // Note: we're only invalidating the magic data in the file, as dex2oat needs the rest of
1404 // the information to remain valid.
1405 if (update_input_vdex_) {
Vladimir Marko74527972016-11-29 15:57:32 +00001406 std::unique_ptr<linker::BufferedOutputStream> vdex_out =
1407 std::make_unique<linker::BufferedOutputStream>(
1408 std::make_unique<linker::FileOutputStream>(vdex_files_.back().get()));
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001409 if (!vdex_out->WriteFully(&VdexFile::VerifierDepsHeader::kVdexInvalidMagic,
1410 arraysize(VdexFile::VerifierDepsHeader::kVdexInvalidMagic))) {
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001411 PLOG(ERROR) << "Failed to invalidate vdex header. File: " << vdex_out->GetLocation();
1412 return false;
1413 }
1414
1415 if (!vdex_out->Flush()) {
1416 PLOG(ERROR) << "Failed to flush stream after invalidating header of vdex file."
1417 << " File: " << vdex_out->GetLocation();
1418 return false;
1419 }
1420 }
1421
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001422 if (dm_fd_ != -1 || !dm_file_location_.empty()) {
1423 std::string error_msg;
1424 if (dm_fd_ != -1) {
1425 dm_file_.reset(ZipArchive::OpenFromFd(dm_fd_, "DexMetadata", &error_msg));
1426 } else {
1427 dm_file_.reset(ZipArchive::Open(dm_file_location_.c_str(), &error_msg));
1428 }
1429 if (dm_file_ == nullptr) {
1430 LOG(WARNING) << "Could not open DexMetadata archive " << error_msg;
1431 }
1432 }
1433
1434 if (dm_file_ != nullptr) {
1435 DCHECK(input_vdex_file_ == nullptr);
1436 std::string error_msg;
1437 static const char* kDexMetadata = "DexMetadata";
1438 std::unique_ptr<ZipEntry> zip_entry(dm_file_->Find(VdexFile::kVdexNameInDmFile, &error_msg));
1439 if (zip_entry == nullptr) {
1440 LOG(INFO) << "No " << VdexFile::kVdexNameInDmFile << " file in DexMetadata archive. "
1441 << "Not doing fast verification.";
1442 } else {
Mathieu Chartier792111c2018-02-15 13:02:15 -08001443 std::unique_ptr<MemMap> input_file(zip_entry->MapDirectlyOrExtract(
1444 VdexFile::kVdexNameInDmFile,
1445 kDexMetadata,
1446 &error_msg));
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001447 if (input_file == nullptr) {
1448 LOG(WARNING) << "Could not open vdex file in DexMetadata archive: " << error_msg;
1449 } else {
1450 input_vdex_file_ = std::make_unique<VdexFile>(input_file.release());
1451 }
1452 }
1453 }
1454
David Brazdil7b49e6c2016-09-01 11:06:18 +01001455 // Swap file handling
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001456 //
1457 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1458 // that we can use for swap.
1459 //
1460 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1461 // will immediately unlink to satisfy the swap fd assumption.
1462 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1463 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1464 if (swap_file.get() == nullptr) {
1465 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1466 return false;
1467 }
1468 swap_fd_ = swap_file->Fd();
1469 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1470 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1471 // released immediately.
1472 unlink(swap_file_name_.c_str());
1473 }
Jeff Hao436183f2016-01-12 16:36:50 -08001474
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001475 return true;
1476 }
1477
David Brazdil7b49e6c2016-09-01 11:06:18 +01001478 void EraseOutputFiles() {
1479 for (auto& files : { &vdex_files_, &oat_files_ }) {
1480 for (size_t i = 0; i < files->size(); ++i) {
1481 if ((*files)[i].get() != nullptr) {
1482 (*files)[i]->Erase();
1483 (*files)[i].reset();
1484 }
1485 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001486 }
Andreas Gampea650e702014-12-03 14:28:02 -08001487 }
1488
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001489 void LoadClassProfileDescriptors() {
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07001490 if (!IsImage()) {
1491 return;
1492 }
1493 // If we don't have a profile, treat it as an empty set of classes. b/77340429
1494 if (image_classes_ == nullptr) {
1495 // May be non-null when --image-classes is passed in, in that case avoid clearing the list.
1496 image_classes_.reset(new std::unordered_set<std::string>());
1497 }
1498 if (profile_compilation_info_ != nullptr) {
Mathieu Chartier0b490842016-05-25 15:05:59 -07001499 // Filter out class path classes since we don't want to include these in the image.
Mathieu Chartier4f342b02017-07-21 17:12:39 -07001500 image_classes_.reset(
1501 new std::unordered_set<std::string>(
1502 profile_compilation_info_->GetClassDescriptors(dex_files_)));
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001503 VLOG(compiler) << "Loaded " << image_classes_->size()
1504 << " image class descriptors from profile";
1505 if (VLOG_IS_ON(compiler)) {
1506 for (const std::string& s : *image_classes_) {
1507 LOG(INFO) << "Image class " << s;
1508 }
1509 }
1510 }
1511 }
1512
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001513 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1514 // boot class path.
Andreas Gampef7882972017-03-20 16:35:24 -07001515 dex2oat::ReturnCode Setup() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001516 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001517
Andreas Gampebd600e32018-04-12 14:25:39 -07001518 if (!PrepareImageClasses() || !PrepareDirtyObjects()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001519 return dex2oat::ReturnCode::kOther;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001520 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001521
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001522 // Verification results are null since we don't know if we will need them yet as the compler
1523 // filter may change.
Andreas Gampe4585f872015-03-27 23:45:15 -07001524 callbacks_.reset(new QuickCompilerCallbacks(
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001525 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001526 CompilerCallbacks::CallbackMode::kCompileBootImage :
1527 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001528
Vladimir Marko49b0f452015-12-10 13:49:19 +00001529 RuntimeArgumentMap runtime_options;
Mathieu Chartier46331a62017-07-21 09:49:10 -07001530 if (!PrepareRuntimeOptions(&runtime_options, callbacks_.get())) {
Andreas Gampef7882972017-03-20 16:35:24 -07001531 return dex2oat::ReturnCode::kOther;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001532 }
1533
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001534 CreateOatWriters();
1535 if (!AddDexFileSources()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001536 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001537 }
1538
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001539 if (!compilation_reason_.empty()) {
1540 key_value_store_->Put(OatHeader::kCompilationReasonKey, compilation_reason_);
1541 }
1542
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001543 if (IsBootImage() && image_filenames_.size() > 1) {
1544 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1545 // We need this for the multi-image case.
Mathieu Chartier866d8742016-09-21 15:24:18 -07001546 key_value_store_->Put(OatHeader::kBootClassPathKey,
1547 gc::space::ImageSpace::GetMultiImageBootClassPath(dex_locations_,
1548 oat_filenames_,
1549 image_filenames_));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001550 }
1551
1552 if (!IsBootImage()) {
1553 // When compiling an app, create the runtime early to retrieve
1554 // the image location key needed for the oat header.
1555 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampef7882972017-03-20 16:35:24 -07001556 return dex2oat::ReturnCode::kCreateRuntime;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001557 }
1558
Andreas Gampe29d38e72016-03-23 15:31:51 +00001559 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001560 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1561 std::vector<gc::space::ImageSpace*> image_spaces =
1562 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Richard Uhlerbc26b722017-03-10 14:27:10 +00001563 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001564 image_file_location_oat_data_begin_ =
1565 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1566 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1567 // Store the boot image filename(s).
1568 std::vector<std::string> image_filenames;
1569 for (const gc::space::ImageSpace* image_space : image_spaces) {
1570 image_filenames.push_back(image_space->GetImageFilename());
1571 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001572 std::string image_file_location = android::base::Join(image_filenames, ':');
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001573 if (!image_file_location.empty()) {
1574 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1575 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001576 } else {
1577 image_file_location_oat_checksum_ = 0u;
1578 image_file_location_oat_data_begin_ = 0u;
1579 image_patch_delta_ = 0;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001580 }
1581
1582 // Open dex files for class path.
Calin Juravle19915892017-08-03 17:10:36 +00001583
Calin Juravle1ce70852017-06-28 10:59:03 -07001584 if (class_loader_context_ == nullptr) {
Calin Juravle19915892017-08-03 17:10:36 +00001585 // If no context was specified use the default one (which is an empty PathClassLoader).
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001586 class_loader_context_ = ClassLoaderContext::Default();
Jeff Haof0192c82016-03-28 20:39:50 -07001587 }
Calin Juravle19915892017-08-03 17:10:36 +00001588
Calin Juravle1ce70852017-06-28 10:59:03 -07001589 DCHECK_EQ(oat_writers_.size(), 1u);
1590
1591 // Note: Ideally we would reject context where the source dex files are also
1592 // specified in the classpath (as it doesn't make sense). However this is currently
1593 // needed for non-prebuild tests and benchmarks which expects on the fly compilation.
1594 // Also, for secondary dex files we do not have control on the actual classpath.
1595 // Instead of aborting, remove all the source location from the context classpaths.
1596 if (class_loader_context_->RemoveLocationsFromClassPaths(
1597 oat_writers_[0]->GetSourceLocations())) {
1598 LOG(WARNING) << "The source files to be compiled are also in the classpath.";
1599 }
1600
1601 // We need to open the dex files before encoding the context in the oat file.
1602 // (because the encoding adds the dex checksum...)
1603 // TODO(calin): consider redesigning this so we don't have to open the dex files before
1604 // creating the actual class loader.
1605 if (!class_loader_context_->OpenDexFiles(runtime_->GetInstructionSet(), classpath_dir_)) {
1606 // Do not abort if we couldn't open files from the classpath. They might be
1607 // apks without dex files and right now are opening flow will fail them.
1608 LOG(WARNING) << "Failed to open classpath dex files";
1609 }
1610
1611 // Store the class loader context in the oat header.
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001612 // TODO: deprecate this since store_class_loader_context should be enough to cover the users
1613 // of classpath_dir as well.
Mathieu Chartierc4440772018-04-16 14:40:56 -07001614 std::string class_path_key =
1615 class_loader_context_->EncodeContextForOatFile(classpath_dir_,
1616 stored_class_loader_context_.get());
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001617 key_value_store_->Put(OatHeader::kClassPathKey, class_path_key);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001618 }
1619
1620 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001621 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001622 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1623 rodata_.reserve(oat_writers_.size());
1624 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1625 rodata_.push_back(elf_writers_[i]->StartRoData());
1626 // Unzip or copy dex files straight to the oat file.
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001627 std::vector<std::unique_ptr<MemMap>> opened_dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001628 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001629 // No need to verify the dex file when we have a vdex file, which means it was already
1630 // verified.
1631 const bool verify = (input_vdex_file_ == nullptr);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001632 if (!oat_writers_[i]->WriteAndOpenDexFiles(
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001633 vdex_files_[i].get(),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001634 rodata_.back(),
1635 instruction_set_,
1636 instruction_set_features_.get(),
1637 key_value_store_.get(),
Jeff Hao042e8982016-10-19 11:17:11 -07001638 verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001639 update_input_vdex_,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001640 copy_dex_files_,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001641 &opened_dex_files_map,
1642 &opened_dex_files)) {
Andreas Gampef7882972017-03-20 16:35:24 -07001643 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001644 }
1645 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001646 if (opened_dex_files_map.empty()) {
1647 DCHECK(opened_dex_files.empty());
1648 } else {
1649 for (std::unique_ptr<MemMap>& map : opened_dex_files_map) {
1650 opened_dex_files_maps_.push_back(std::move(map));
1651 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001652 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001653 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001654 opened_dex_files_.push_back(std::move(dex_file));
1655 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001656 }
1657 }
1658 }
1659
1660 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
Andreas Gampe7386da42016-06-08 18:18:47 -07001661
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001662 // If we need to downgrade the compiler-filter for size reasons.
1663 if (!IsBootImage() && IsVeryLarge(dex_files_)) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -07001664 // Disable app image to make sure dex2oat unloading is enabled.
1665 compiler_options_->DisableAppImage();
1666
Mathieu Chartier72041a02017-07-14 18:23:25 -07001667 // If we need to downgrade the compiler-filter for size reasons, do that early before we read
1668 // it below for creating verification callbacks.
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001669 if (!CompilerFilter::IsAsGoodAs(kLargeAppFilter, compiler_options_->GetCompilerFilter())) {
1670 LOG(INFO) << "Very large app, downgrading to verify.";
1671 // Note: this change won't be reflected in the key-value store, as that had to be
1672 // finalized before loading the dex files. This setup is currently required
1673 // to get the size from the DexFile objects.
1674 // TODO: refactor. b/29790079
1675 compiler_options_->SetCompilerFilter(kLargeAppFilter);
1676 }
1677 }
1678
1679 if (CompilerFilter::IsAnyCompilationEnabled(compiler_options_->GetCompilerFilter())) {
1680 // Only modes with compilation require verification results, do this here instead of when we
1681 // create the compilation callbacks since the compilation mode may have been changed by the
1682 // very large app logic.
1683 // Avoiding setting the verification results saves RAM by not adding the dex files later in
1684 // the function.
1685 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1686 callbacks_->SetVerificationResults(verification_results_.get());
1687 }
1688
Andreas Gampe7386da42016-06-08 18:18:47 -07001689 // We had to postpone the swap decision till now, as this is the point when we actually
1690 // know about the dex files we're going to use.
1691
1692 // Make sure that we didn't create the driver, yet.
1693 CHECK(driver_ == nullptr);
1694 // If we use a swap file, ensure we are above the threshold to make it necessary.
1695 if (swap_fd_ != -1) {
1696 if (!UseSwap(IsBootImage(), dex_files_)) {
1697 close(swap_fd_);
1698 swap_fd_ = -1;
1699 VLOG(compiler) << "Decided to run without swap.";
1700 } else {
1701 LOG(INFO) << "Large app, accepted running with swap.";
1702 }
1703 }
1704 // 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 +00001705 if (IsBootImage()) {
1706 // For boot image, pass opened dex files to the Runtime::Create().
1707 // Note: Runtime acquires ownership of these dex files.
1708 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001709 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampef7882972017-03-20 16:35:24 -07001710 return dex2oat::ReturnCode::kOther;
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001711 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001712 }
1713
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001714 // If we're doing the image, override the compiler filter to force full compilation. Must be
1715 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1716 // compilation of class initializers.
1717 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001718 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001719 WellKnownClasses::Init(self->GetJniEnv());
1720
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001721 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001722 constexpr bool kSaveDexInput = false;
1723 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001724 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001725 }
1726 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001727
1728 // Ensure opened dex files are writable for dex-to-dex transformations.
1729 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1730 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1731 PLOG(ERROR) << "Failed to make .dex files writeable.";
Andreas Gampef7882972017-03-20 16:35:24 -07001732 return dex2oat::ReturnCode::kOther;
Vladimir Marko919f5532016-01-20 19:13:01 +00001733 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001734 }
1735
Mathieu Chartier72041a02017-07-14 18:23:25 -07001736 // Verification results are only required for modes that have any compilation. Avoid
1737 // adding the dex files if possible to prevent allocating large arrays.
1738 if (verification_results_ != nullptr) {
1739 for (const auto& dex_file : dex_files_) {
1740 // Pre-register dex files so that we can access verification results without locks during
1741 // compilation and verification.
Mathieu Chartier0733dc82017-07-17 14:05:28 -07001742 verification_results_->AddDexFile(dex_file);
1743 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001744 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001745
Andreas Gampef7882972017-03-20 16:35:24 -07001746 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001747 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001748
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001749 // If we need to keep the oat file open for the image writer.
1750 bool ShouldKeepOatFileOpen() const {
1751 return IsImage() && oat_fd_ != kInvalidFd;
1752 }
1753
Mathieu Chartier72041a02017-07-14 18:23:25 -07001754 // Doesn't return the class loader since it's not meant to be used for image compilation.
1755 void CompileDexFilesIndividually() {
1756 CHECK(!IsImage()) << "Not supported with image";
1757 for (const DexFile* dex_file : dex_files_) {
1758 std::vector<const DexFile*> dex_files(1u, dex_file);
1759 VLOG(compiler) << "Compiling " << dex_file->GetLocation();
1760 jobject class_loader = CompileDexFiles(dex_files);
1761 CHECK(class_loader != nullptr);
1762 ScopedObjectAccess soa(Thread::Current());
1763 // Unload class loader to free RAM.
Ian Rogers55256cb2017-12-21 17:07:11 -08001764 jweak weak_class_loader = soa.Env()->GetVm()->AddWeakGlobalRef(
Mathieu Chartier72041a02017-07-14 18:23:25 -07001765 soa.Self(),
1766 soa.Decode<mirror::ClassLoader>(class_loader));
Ian Rogers55256cb2017-12-21 17:07:11 -08001767 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), class_loader);
Roland Levillainaf290312018-02-27 20:02:17 +00001768 runtime_->GetHeap()->CollectGarbage(/* clear_soft_references */ true);
Mathieu Chartier72041a02017-07-14 18:23:25 -07001769 ObjPtr<mirror::ClassLoader> decoded_weak = soa.Decode<mirror::ClassLoader>(weak_class_loader);
1770 if (decoded_weak != nullptr) {
1771 LOG(FATAL) << "Failed to unload class loader, path from root set: "
1772 << runtime_->GetHeap()->GetVerification()->FirstPathFromRootSet(decoded_weak);
1773 }
1774 VLOG(compiler) << "Unloaded classloader";
1775 }
1776 }
1777
1778 bool ShouldCompileDexFilesIndividually() const {
Nicolas Geoffraya6fc7872017-08-14 11:29:22 +01001779 // Compile individually if we are:
1780 // 1. not building an image,
1781 // 2. not verifying a vdex file,
1782 // 3. using multidex,
1783 // 4. not doing any AOT compilation.
1784 // This means extract, no-vdex verify, and quicken, will use the individual compilation
1785 // mode (to reduce RAM used by the compiler).
Mathieu Chartier72041a02017-07-14 18:23:25 -07001786 return !IsImage() &&
Nicolas Geoffraya6fc7872017-08-14 11:29:22 +01001787 !update_input_vdex_ &&
Mathieu Chartier72041a02017-07-14 18:23:25 -07001788 dex_files_.size() > 1 &&
Mathieu Chartier6a2b67b2017-08-08 15:09:29 -07001789 !CompilerFilter::IsAotCompilationEnabled(compiler_options_->GetCompilerFilter());
Mathieu Chartier72041a02017-07-14 18:23:25 -07001790 }
1791
1792 // Set up and create the compiler driver and then invoke it to compile all the dex files.
1793 jobject Compile() {
1794 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1795
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001796 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001797
Vladimir Marko47496c22016-01-27 16:15:08 +00001798 // Find the dex files we should not inline from.
Vladimir Marko47496c22016-01-27 16:15:08 +00001799 std::vector<std::string> no_inline_filters;
1800 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001801
1802 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001803 const std::string core_oj = "core-oj";
1804 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1805 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001806 }
1807
Vladimir Marko47496c22016-01-27 16:15:08 +00001808 if (!no_inline_filters.empty()) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001809 std::vector<const DexFile*> class_path_files;
1810 if (!IsBootImage()) {
1811 // The class loader context is used only for apps.
1812 class_path_files = class_loader_context_->FlattenOpenedDexFiles();
1813 }
1814
Jeff Haodcdc85b2015-12-04 14:06:18 -08001815 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1816 &class_linker->GetBootClassPath(),
1817 &class_path_files,
1818 &dex_files_
1819 };
1820 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001821 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001822 for (const std::string& filter : no_inline_filters) {
1823 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
Calin Juravlea308a322017-07-18 16:51:51 -07001824 // allows tests to specify <test-dexfile>!classes2.dex if needed but if the
Vladimir Marko47496c22016-01-27 16:15:08 +00001825 // base location passes the StartsWith() test, so do all extra locations.
1826 std::string dex_location = dex_file->GetLocation();
1827 if (filter.find('/') == std::string::npos) {
1828 // The filter does not contain the path. Remove the path from dex_location as well.
1829 size_t last_slash = dex_file->GetLocation().rfind('/');
1830 if (last_slash != std::string::npos) {
1831 dex_location = dex_location.substr(last_slash + 1);
1832 }
1833 }
1834
Andreas Gampe9186ced2016-12-12 14:28:21 -08001835 if (android::base::StartsWith(dex_location, filter.c_str())) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001836 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1837 no_inline_from_dex_files_.push_back(dex_file);
1838 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001839 }
1840 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001841 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001842 }
1843 if (!no_inline_from_dex_files_.empty()) {
1844 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001845 }
1846 }
1847
Vladimir Marko307dac92015-10-20 11:20:09 +01001848 driver_.reset(new CompilerDriver(compiler_options_.get(),
1849 verification_results_.get(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001850 compiler_kind_,
1851 instruction_set_,
1852 instruction_set_features_.get(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001853 image_classes_.release(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001854 thread_count_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001855 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001856 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001857 driver_->SetDexFilesForOatFile(dex_files_);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01001858 if (!IsBootImage()) {
1859 driver_->SetClasspathDexFiles(class_loader_context_->FlattenOpenedDexFiles());
1860 }
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001861
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001862 const bool compile_individually = ShouldCompileDexFilesIndividually();
1863 if (compile_individually) {
1864 // Set the compiler driver in the callbacks so that we can avoid re-verification. This not
1865 // only helps performance but also prevents reverifying quickened bytecodes. Attempting
1866 // verify quickened bytecode causes verification failures.
1867 // Only set the compiler filter if we are doing separate compilation since there is a bit
1868 // of overhead when checking if a class was previously verified.
1869 callbacks_->SetDoesClassUnloading(true, driver_.get());
1870 }
1871
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001872 // Setup vdex for compilation.
1873 if (!DoEagerUnquickeningOfVdex() && input_vdex_file_ != nullptr) {
1874 callbacks_->SetVerifierDeps(
1875 new verifier::VerifierDeps(dex_files_, input_vdex_file_->GetVerifierDepsData()));
1876
1877 // TODO: we unquicken unconditionally, as we don't know
1878 // if the boot image has changed. How exactly we'll know is under
1879 // experimentation.
1880 TimingLogger::ScopedTiming time_unquicken("Unquicken", timings_);
Anestis Bechtsoudisa1f56a82017-10-08 23:37:10 +03001881
1882 // We do not decompile a RETURN_VOID_NO_BARRIER into a RETURN_VOID, as the quickening
1883 // optimization does not depend on the boot image (the optimization relies on not
1884 // having final fields in a class, which does not change for an app).
Mathieu Chartier210531f2018-01-12 10:15:51 -08001885 input_vdex_file_->Unquicken(dex_files_, /* decompile_return_instruction */ false);
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_);
Andreas Gampee9934582018-01-19 21:23:04 -08001907 callbacks_->SetDexFiles(&dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07001908 }
1909
1910 // Register dex caches and key them to the class loader so that they only unload when the
1911 // class loader unloads.
1912 for (const auto& dex_file : dex_files) {
1913 ScopedObjectAccess soa(Thread::Current());
1914 // Registering the dex cache adds a strong root in the class loader that prevents the dex
1915 // cache from being unloaded early.
1916 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
1917 *dex_file,
1918 soa.Decode<mirror::ClassLoader>(class_loader));
1919 if (dex_cache == nullptr) {
1920 soa.Self()->AssertPendingException();
1921 LOG(FATAL) << "Failed to register dex file " << dex_file->GetLocation() << " "
1922 << soa.Self()->GetException()->Dump();
1923 }
1924 }
1925 driver_->CompileAll(class_loader, dex_files, timings_);
1926 return class_loader;
Vladimir Markof4da6752014-08-01 19:04:18 +01001927 }
1928
Jeff Hao436183f2016-01-12 16:36:50 -08001929 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001930 // ensure the references between the two are correct.
1931 //
1932 // Currently we have a memory layout that looks something like this:
1933 //
1934 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001935 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001936 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001937 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938 // +--------------+
1939 // | alloc spaces |
1940 // +--------------+
1941 //
Jeff Hao436183f2016-01-12 16:36:50 -08001942 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001943 //
Jeff Hao436183f2016-01-12 16:36:50 -08001944 // 1. The images are expected to be loaded at an absolute address and
1945 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946 //
Jeff Hao436183f2016-01-12 16:36:50 -08001947 // 2. There are absolute pointers from Methods in the images to their
1948 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001949 //
Jeff Hao436183f2016-01-12 16:36:50 -08001950 // 3. There are absolute pointers from the code in the oat files to Methods
1951 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001952 //
Jeff Hao436183f2016-01-12 16:36:50 -08001953 // 4. There are absolute pointers from code in the oat files to other code
1954 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001955 //
1956 // To get this all correct, we go through several steps.
1957 //
Jeff Hao436183f2016-01-12 16:36:50 -08001958 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001959 // the oat data size and code size. During this stage, we also set
1960 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001961 //
Jeff Hao436183f2016-01-12 16:36:50 -08001962 // 2. We prepare offsets for the objects in the images and calculate
1963 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001964 //
Jeff Hao436183f2016-01-12 16:36:50 -08001965 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001966 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001967 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001968 // can prepare the ELF headers and we then know the ELF memory segment
1969 // layout and we can now resolve all references. The compiler provides
1970 // LinkerPatch information in each CompiledMethod and we resolve these,
1971 // using the layout information and image object locations provided by
1972 // image writer, as we're writing the method code.
1973 //
Jeff Hao436183f2016-01-12 16:36:50 -08001974 // 4. We create the image files. They need to know where the oat files
1975 // will be loaded after itself. Originally oat files were simply
1976 // memory mapped so we could predict where their contents were based
1977 // on the file size. Now that they are ELF files, we need to inspect
1978 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001979 // where the oat header is located within.
1980 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001981 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001982 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001983 // load the .so at the desired location at runtime by offsetting the
1984 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001985 // TODO: Do this in step 3. We already know the layout there.
1986 //
1987 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1988 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001989
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001990 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1991 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001992 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1993 // case (when the file will be explicitly erased).
David Brazdil7b49e6c2016-09-01 11:06:18 +01001994 bool WriteOutputFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001995 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1996
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001997 // Sync the data to the file, in case we did dex2dex transformations.
1998 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1999 if (!map->Sync()) {
2000 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
2001 return false;
2002 }
2003 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002004
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002005 if (IsImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002006 if (IsAppImage() && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002007 gc::Heap* const heap = Runtime::Current()->GetHeap();
2008 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002009 image_base_ = std::max(image_base_, RoundUp(
2010 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
2011 kPageSize));
2012 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002013 // The non moving space is right after the oat file. Put the preferred app image location
2014 // right after the non moving space so that we ideally get a continuous immune region for
2015 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002016 // Use the default non moving space capacity since dex2oat does not have a separate non-
2017 // moving space. This means the runtime's non moving space space size will be as large
2018 // as the growth limit for dex2oat, but smaller in the zygote.
2019 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002021 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
2022 }
2023
Vladimir Marko74527972016-11-29 15:57:32 +00002024 image_writer_.reset(new linker::ImageWriter(*driver_,
2025 image_base_,
2026 compiler_options_->GetCompilePic(),
2027 IsAppImage(),
2028 image_storage_mode_,
2029 oat_filenames_,
2030 dex_file_oat_index_map_,
2031 dirty_image_objects_.get()));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002032
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002033 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002034 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
Mathieu Chartier703b82a2018-04-10 15:52:32 -07002035 if (!image_writer_->PrepareImageAddressSpace(timings_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002036 LOG(ERROR) << "Failed to prepare image address space.";
2037 return false;
2038 }
2039 }
2040
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002041 // Initialize the writers with the compiler driver, image writer, and their
2042 // dex files. The writers were created without those being there yet.
2043 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko74527972016-11-29 15:57:32 +00002044 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002045 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
2046 oat_writer->Initialize(driver_.get(), image_writer_.get(), dex_files);
2047 }
2048
David Brazdil5d5a36b2016-09-14 15:34:10 +01002049 {
2050 TimingLogger::ScopedTiming t2("dex2oat Write VDEX", timings_);
2051 DCHECK(IsBootImage() || oat_files_.size() == 1u);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002052 verifier::VerifierDeps* verifier_deps = callbacks_->GetVerifierDeps();
David Brazdil5d5a36b2016-09-14 15:34:10 +01002053 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2054 File* vdex_file = vdex_files_[i].get();
Vladimir Marko74527972016-11-29 15:57:32 +00002055 std::unique_ptr<linker::BufferedOutputStream> vdex_out =
2056 std::make_unique<linker::BufferedOutputStream>(
2057 std::make_unique<linker::FileOutputStream>(vdex_file));
David Brazdil5d5a36b2016-09-14 15:34:10 +01002058
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002059 if (!oat_writers_[i]->WriteVerifierDeps(vdex_out.get(), verifier_deps)) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002060 LOG(ERROR) << "Failed to write verifier dependencies into VDEX " << vdex_file->GetPath();
2061 return false;
2062 }
2063
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002064 if (!oat_writers_[i]->WriteQuickeningInfo(vdex_out.get())) {
2065 LOG(ERROR) << "Failed to write quickening info into VDEX " << vdex_file->GetPath();
2066 return false;
2067 }
2068
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002069 // VDEX finalized, seek back to the beginning and write checksums and the header.
2070 if (!oat_writers_[i]->WriteChecksumsAndVdexHeader(vdex_out.get())) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002071 LOG(ERROR) << "Failed to write vdex header into VDEX " << vdex_file->GetPath();
2072 return false;
2073 }
2074 }
2075 }
2076
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002077 {
2078 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Markoca1e0382018-04-11 09:58:41 +00002079 linker::MultiOatRelativePatcher patcher(instruction_set_,
2080 instruction_set_features_.get(),
2081 driver_->GetCompiledMethodStorage());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002082 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko74527972016-11-29 15:57:32 +00002083 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2084 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko944da602016-02-19 12:27:55 +00002085
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002086 oat_writer->PrepareLayout(&patcher);
Vladimir Markob066d432018-01-03 13:14:37 +00002087 elf_writer->PrepareDynamicSection(oat_writer->GetOatHeader().GetExecutableOffset(),
2088 oat_writer->GetCodeSize(),
2089 oat_writer->GetDataBimgRelRoSize(),
Vladimir Markoaad75c62016-10-03 08:46:48 +00002090 oat_writer->GetBssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002091 oat_writer->GetBssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +00002092 oat_writer->GetBssRootsOffset(),
2093 oat_writer->GetVdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +00002094 if (IsImage()) {
2095 // Update oat layout.
2096 DCHECK(image_writer_ != nullptr);
2097 DCHECK_LT(i, oat_filenames_.size());
2098 image_writer_->UpdateOatFileLayout(i,
2099 elf_writer->GetLoadedSize(),
2100 oat_writer->GetOatDataOffset(),
David Brazdil7b49e6c2016-09-01 11:06:18 +01002101 oat_writer->GetOatSize());
Vladimir Marko944da602016-02-19 12:27:55 +00002102 }
Richard Uhlerbc26b722017-03-10 14:27:10 +00002103
2104 if (IsBootImage()) {
2105 // Have the image_file_location_oat_checksum_ for boot oat files
2106 // depend on the contents of all the boot oat files. This way only
2107 // the primary image checksum needs to be checked to determine
2108 // whether any of the images are out of date.
2109 image_file_location_oat_checksum_ ^= oat_writer->GetOatHeader().GetChecksum();
2110 }
Vladimir Marko944da602016-02-19 12:27:55 +00002111 }
2112
2113 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002114 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko74527972016-11-29 15:57:32 +00002115 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2116 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00002117
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.
David Srbecky32210b92017-12-04 14:39:21 +00002120 debug::DebugInfo debug_info = oat_writer->GetDebugInfo(); // Keep the variable alive.
2121 elf_writer->PrepareDebugInfo(debug_info); // Processes the data on background thread.
David Srbecky0c4572e2016-01-22 19:19:25 +00002122
Vladimir Marko74527972016-11-29 15:57:32 +00002123 linker::OutputStream*& rodata = rodata_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002124 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002125 if (!oat_writer->WriteRodata(rodata)) {
2126 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
2127 return false;
2128 }
2129 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002130 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00002131
Vladimir Marko74527972016-11-29 15:57:32 +00002132 linker::OutputStream* text = elf_writer->StartText();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002133 if (!oat_writer->WriteCode(text)) {
2134 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
2135 return false;
2136 }
2137 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00002138
Vladimir Markob066d432018-01-03 13:14:37 +00002139 if (oat_writer->GetDataBimgRelRoSize() != 0u) {
2140 linker::OutputStream* data_bimg_rel_ro = elf_writer->StartDataBimgRelRo();
2141 if (!oat_writer->WriteDataBimgRelRo(data_bimg_rel_ro)) {
2142 LOG(ERROR) << "Failed to write .data.bimg.rel.ro section to the ELF file "
2143 << oat_file->GetPath();
2144 return false;
2145 }
2146 elf_writer->EndDataBimgRelRo(data_bimg_rel_ro);
2147 }
2148
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002149 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
2150 image_file_location_oat_checksum_,
2151 image_file_location_oat_data_begin_,
2152 image_patch_delta_)) {
2153 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
2154 return false;
2155 }
2156
Vladimir Marko944da602016-02-19 12:27:55 +00002157 if (IsImage()) {
2158 // Update oat header information.
2159 DCHECK(image_writer_ != nullptr);
2160 DCHECK_LT(i, oat_filenames_.size());
2161 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
2162 }
2163
Jeff Haodcdc85b2015-12-04 14:06:18 -08002164 elf_writer->WriteDynamicSection();
David Srbecky32210b92017-12-04 14:39:21 +00002165 elf_writer->WriteDebugInfo(oat_writer->GetDebugInfo());
Vladimir Marko10c13562015-11-25 14:33:36 +00002166
Jeff Haodcdc85b2015-12-04 14:06:18 -08002167 if (!elf_writer->End()) {
2168 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
2169 return false;
2170 }
2171
David Brazdil7b49e6c2016-09-01 11:06:18 +01002172 if (!FlushOutputFile(&vdex_files_[i]) || !FlushOutputFile(&oat_files_[i])) {
2173 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002174 }
2175
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002177
2178 oat_writer.reset();
2179 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002180 }
2181 }
2182
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002183 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002184 }
2185
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002186 // If we are compiling an image, invoke the image creation routine. Else just skip.
2187 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002188 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002189 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
2190 if (!CreateImageFile()) {
2191 return false;
2192 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002193 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07002194 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002195 return true;
2196 }
2197
Jeff Haodcdc85b2015-12-04 14:06:18 -08002198 // Create a copy from stripped to unstripped.
2199 bool CopyStrippedToUnstripped() {
2200 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
2201 // If we don't want to strip in place, copy from stripped location to unstripped location.
2202 // We need to strip after image creation because FixupElf needs to use .strtab.
2203 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
2204 // If the oat file is still open, flush it.
2205 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002206 if (!FlushCloseOutputFile(&oat_files_[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002207 return false;
2208 }
2209 }
2210
2211 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
2212 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
2213 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
Vladimir Markob55cc6d2016-10-17 15:25:10 +01002214 int64_t in_length = in->GetLength();
2215 if (in_length < 0) {
2216 PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
2217 return false;
2218 }
2219 if (!out->Copy(in.get(), 0, in_length)) {
2220 PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
2221 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002222 }
2223 if (out->FlushCloseOrErase() != 0) {
2224 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
2225 return false;
2226 }
2227 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
2228 }
2229 }
2230 return true;
2231 }
2232
David Brazdil7b49e6c2016-09-01 11:06:18 +01002233 bool FlushOutputFile(std::unique_ptr<File>* file) {
2234 if (file->get() != nullptr) {
2235 if (file->get()->Flush() != 0) {
2236 PLOG(ERROR) << "Failed to flush output file: " << file->get()->GetPath();
2237 return false;
2238 }
2239 }
2240 return true;
2241 }
2242
2243 bool FlushCloseOutputFile(std::unique_ptr<File>* file) {
2244 if (file->get() != nullptr) {
2245 std::unique_ptr<File> tmp(file->release());
2246 if (tmp->FlushCloseOrErase() != 0) {
2247 PLOG(ERROR) << "Failed to flush and close output file: " << tmp->GetPath();
2248 return false;
2249 }
2250 }
2251 return true;
2252 }
2253
2254 bool FlushOutputFiles() {
2255 TimingLogger::ScopedTiming t2("dex2oat Flush Output Files", timings_);
2256 for (auto& files : { &vdex_files_, &oat_files_ }) {
2257 for (size_t i = 0; i < files->size(); ++i) {
2258 if (!FlushOutputFile(&(*files)[i])) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002259 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002260 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002261 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00002262 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08002263 return true;
2264 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265
David Brazdil7b49e6c2016-09-01 11:06:18 +01002266 bool FlushCloseOutputFiles() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002267 bool result = true;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002268 for (auto& files : { &vdex_files_, &oat_files_ }) {
2269 for (size_t i = 0; i < files->size(); ++i) {
2270 result &= FlushCloseOutputFile(&(*files)[i]);
2271 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002272 }
2273 return result;
2274 }
2275
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002276 void DumpTiming() {
Nicolas Geoffray2d8801f2017-11-28 15:50:07 +00002277 if (compiler_options_->GetDumpTimings() ||
2278 (kIsDebugBuild && timings_->GetTotalNs() > MsToNs(1000))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002279 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
2280 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002281 }
2282
Andreas Gampe10e477d2014-11-19 12:57:42 -08002283 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002284 return IsAppImage() || IsBootImage();
2285 }
2286
2287 bool IsAppImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002288 return compiler_options_->IsAppImage();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002289 }
2290
2291 bool IsBootImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002292 return compiler_options_->IsBootImage();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002293 }
2294
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002295 bool IsHost() const {
2296 return is_host_;
2297 }
2298
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002299 bool UseProfile() const {
Mathieu Chartierd0af56c2017-02-17 12:56:25 -08002300 return profile_file_fd_ != -1 || !profile_file_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02002301 }
2302
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002303 bool DoProfileGuidedOptimizations() const {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002304 return UseProfile();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002305 }
2306
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07002307 bool DoGenerateCompactDex() const {
2308 return compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone;
2309 }
2310
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002311 bool DoDexLayoutOptimizations() const {
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07002312 return DoProfileGuidedOptimizations() || DoGenerateCompactDex();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002313 }
2314
Igor Murashkin545412b2017-08-17 15:26:54 -07002315 bool DoOatLayoutOptimizations() const {
2316 return DoProfileGuidedOptimizations();
2317 }
2318
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002319 bool MayInvalidateVdexMetadata() const {
2320 // DexLayout can invalidate the vdex metadata if changing the class def order is enabled, so
2321 // we need to unquicken the vdex file eagerly, before passing it to dexlayout.
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01002322 return DoDexLayoutOptimizations();
2323 }
2324
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002325 bool DoEagerUnquickeningOfVdex() const {
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00002326 return MayInvalidateVdexMetadata() && dm_file_ == nullptr;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002327 }
2328
Calin Juravle2e2db782016-02-23 12:00:03 +00002329 bool LoadProfile() {
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002330 DCHECK(UseProfile());
Calin Juravlee6f87cc2017-05-24 17:41:05 -07002331 // TODO(calin): We should be using the runtime arena pool (instead of the
2332 // default profile arena). However the setup logic is messy and needs
2333 // cleaning up before that (e.g. the oat writers are created before the
2334 // runtime).
Calin Juravle2e2db782016-02-23 12:00:03 +00002335 profile_compilation_info_.reset(new ProfileCompilationInfo());
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002336 ScopedFlock profile_file;
Calin Juravle2e2db782016-02-23 12:00:03 +00002337 std::string error;
2338 if (profile_file_fd_ != -1) {
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002339 profile_file = LockedFile::DupOf(profile_file_fd_, "profile",
2340 true /* read_only_mode */, &error);
Andreas Gampe29d38e72016-03-23 15:31:51 +00002341 } else if (profile_file_ != "") {
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002342 profile_file = LockedFile::Open(profile_file_.c_str(), O_RDONLY, true, &error);
Calin Juravle998c2162015-12-21 15:39:33 +02002343 }
Calin Juravle877fd962016-01-05 14:29:29 +00002344
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002345 // Return early if we're unable to obtain a lock on the profile.
2346 if (profile_file.get() == nullptr) {
2347 LOG(ERROR) << "Cannot lock profiles: " << error;
2348 return false;
2349 }
2350
2351 if (!profile_compilation_info_->Load(profile_file->Fd())) {
Calin Juravle2e2db782016-02-23 12:00:03 +00002352 profile_compilation_info_.reset(nullptr);
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002353 return false;
Calin Juravle2e2db782016-02-23 12:00:03 +00002354 }
Calin Juravle877fd962016-01-05 14:29:29 +00002355
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002356 return true;
Calin Juravle998c2162015-12-21 15:39:33 +02002357 }
2358
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002359 private:
Andreas Gampee1459ae2016-06-29 09:36:30 -07002360 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) {
2361 if (is_image) {
2362 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
2363 return false;
2364 }
2365 if (dex_files.size() < min_dex_files_for_swap_) {
2366 // If there are less dex files than the threshold, assume it's gonna be fine.
2367 return false;
2368 }
2369 size_t dex_files_size = 0;
2370 for (const auto* dex_file : dex_files) {
2371 dex_files_size += dex_file->GetHeader().file_size_;
2372 }
2373 return dex_files_size >= min_dex_file_cumulative_size_for_swap_;
2374 }
2375
Andreas Gampe67f02822016-06-24 21:05:23 -07002376 bool IsVeryLarge(std::vector<const DexFile*>& dex_files) {
2377 size_t dex_files_size = 0;
2378 for (const auto* dex_file : dex_files) {
2379 dex_files_size += dex_file->GetHeader().file_size_;
2380 }
2381 return dex_files_size >= very_large_threshold_;
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
Vladimir Marko49b0f452015-12-10 13:49:19 +00002398 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2399 const char* classes_filename,
2400 const char* tag) {
2401 std::unique_ptr<std::unordered_set<std::string>> classes;
2402 std::string error_msg;
2403 if (zip_filename != nullptr) {
2404 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2405 } else {
2406 classes.reset(ReadImageClassesFromFile(classes_filename));
2407 }
2408 if (classes == nullptr) {
2409 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2410 << classes_filename << "': " << error_msg;
2411 }
2412 return classes;
2413 }
2414
Jeff Haoc23b0c02017-07-27 18:19:38 -07002415 bool PrepareDirtyObjects() {
2416 if (dirty_image_objects_filename_ != nullptr) {
2417 dirty_image_objects_.reset(ReadCommentedInputFromFile<std::unordered_set<std::string>>(
2418 dirty_image_objects_filename_,
2419 nullptr));
2420 if (dirty_image_objects_ == nullptr) {
2421 LOG(ERROR) << "Failed to create list of dirty objects from '"
2422 << dirty_image_objects_filename_ << "'";
2423 return false;
2424 }
2425 } else {
2426 dirty_image_objects_.reset(nullptr);
2427 }
2428 return true;
2429 }
2430
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002431 void PruneNonExistentDexFiles() {
2432 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2433 size_t kept = 0u;
2434 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2435 if (!OS::FileExists(dex_filenames_[i])) {
2436 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2437 } else {
2438 dex_filenames_[kept] = dex_filenames_[i];
2439 dex_locations_[kept] = dex_locations_[i];
2440 ++kept;
2441 }
2442 }
2443 dex_filenames_.resize(kept);
2444 dex_locations_.resize(kept);
2445 }
2446
2447 bool AddDexFileSources() {
2448 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
Nicolas Geoffraybc177272018-01-24 14:55:32 +00002449 if (input_vdex_file_ != nullptr && input_vdex_file_->HasDexSection()) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002450 DCHECK_EQ(oat_writers_.size(), 1u);
2451 const std::string& name = zip_location_.empty() ? dex_locations_[0] : zip_location_;
2452 DCHECK(!name.empty());
2453 if (!oat_writers_[0]->AddVdexDexFilesSource(*input_vdex_file_.get(), name.c_str())) {
2454 return false;
2455 }
2456 } else if (zip_fd_ != -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002457 DCHECK_EQ(oat_writers_.size(), 1u);
Andreas Gampe43e10b02016-07-15 17:17:34 -07002458 if (!oat_writers_[0]->AddZippedDexFilesSource(File(zip_fd_, /* check_usage */ false),
2459 zip_location_.c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002460 return false;
2461 }
2462 } else if (oat_writers_.size() > 1u) {
2463 // Multi-image.
2464 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2465 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2466 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2467 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2468 return false;
2469 }
2470 }
2471 } else {
2472 DCHECK_EQ(oat_writers_.size(), 1u);
2473 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2474 DCHECK_NE(dex_filenames_.size(), 0u);
2475 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2476 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2477 return false;
2478 }
2479 }
2480 }
2481 return true;
2482 }
2483
2484 void CreateOatWriters() {
2485 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2486 elf_writers_.reserve(oat_files_.size());
2487 oat_writers_.reserve(oat_files_.size());
2488 for (const std::unique_ptr<File>& oat_file : oat_files_) {
Vladimir Marko74527972016-11-29 15:57:32 +00002489 elf_writers_.emplace_back(linker::CreateElfWriterQuick(instruction_set_,
2490 instruction_set_features_.get(),
2491 compiler_options_.get(),
2492 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002493 elf_writers_.back()->Start();
Mathieu Chartier4a265c22018-04-09 14:25:14 -07002494 bool do_oat_writer_layout = DoDexLayoutOptimizations() || DoOatLayoutOptimizations();
2495 if (profile_compilation_info_ != nullptr && profile_compilation_info_->IsEmpty()) {
2496 do_oat_writer_layout = false;
2497 }
Vladimir Marko74527972016-11-29 15:57:32 +00002498 oat_writers_.emplace_back(new linker::OatWriter(
Igor Murashkin545412b2017-08-17 15:26:54 -07002499 IsBootImage(),
2500 timings_,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07002501 do_oat_writer_layout ? profile_compilation_info_.get() : nullptr,
2502 compact_dex_level_));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002503 }
2504 }
2505
Vladimir Marko49b0f452015-12-10 13:49:19 +00002506 void SaveDexInput() {
2507 for (size_t i = 0; i < dex_files_.size(); ++i) {
2508 const DexFile* dex_file = dex_files_[i];
2509 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2510 getpid(), i));
2511 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2512 if (tmp_file.get() == nullptr) {
2513 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2514 << ". Try: adb shell chmod 777 /data/local/tmp";
2515 continue;
2516 }
2517 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2518 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2519 UNUSED(tmp_file->Flush());
2520 UNUSED(tmp_file->Close());
2521 LOG(INFO) << "Wrote input to " << tmp_file_name;
2522 }
2523 }
2524
Mathieu Chartier46331a62017-07-21 09:49:10 -07002525 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options,
2526 QuickCompilerCallbacks* callbacks) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002527 RuntimeOptions raw_options;
2528 if (boot_image_filename_.empty()) {
2529 std::string boot_class_path = "-Xbootclasspath:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002530 boot_class_path += android::base::Join(dex_filenames_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002531 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2532 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002533 boot_class_path_locations += android::base::Join(dex_locations_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002534 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2535 } else {
2536 std::string boot_image_option = "-Ximage:";
2537 boot_image_option += boot_image_filename_;
2538 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2539 }
2540 for (size_t i = 0; i < runtime_args_.size(); i++) {
2541 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2542 }
2543
Mathieu Chartier46331a62017-07-21 09:49:10 -07002544 raw_options.push_back(std::make_pair("compilercallbacks", callbacks));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002545 raw_options.push_back(
2546 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2547
2548 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2549 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2550 // have been stripped in preopting, anyways).
2551 if (!IsBootImage()) {
2552 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2553 }
Andreas Gampec8e35202017-04-28 15:47:12 -07002554 // Never allow implicit image compilation.
2555 raw_options.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002556 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2557 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2558 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002559 // Disable Hspace compaction to save heap size virtual space.
2560 // Only need disable Hspace for OOM becasue background collector is equal to
2561 // foreground collector by default for dex2oat.
2562 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002563
Andreas Gampeace0dc12016-01-20 13:33:13 -08002564 if (compiler_options_->IsForceDeterminism()) {
Roland Levillainb81e9e92017-04-20 17:35:32 +01002565 // If we're asked to be deterministic, ensure non-concurrent GC for determinism.
2566 //
2567 // Note that with read barriers, this option is ignored, because Runtime::Init
2568 // overrides the foreground GC to be gc::kCollectorTypeCC when instantiating
2569 // gc::Heap. This is fine, as concurrent GC requests are not honored in dex2oat,
2570 // which uses an unstarted runtime.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002571 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
Roland Levillainb81e9e92017-04-20 17:35:32 +01002572
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002573 // The default LOS implementation (map) is not deterministic. So disable it.
2574 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=disabled", nullptr));
Andreas Gampeace0dc12016-01-20 13:33:13 -08002575
2576 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2577 // compaction (done above) and ensure that neither foreground nor background collectors
2578 // are concurrent.
Roland Levillainb81e9e92017-04-20 17:35:32 +01002579 //
2580 // Likewise, this option is ignored with read barriers because Runtime::Init
2581 // overrides the background GC to be gc::kCollectorTypeCCBackground, but that's
2582 // fine too, for the same reason (see above).
Andreas Gampeace0dc12016-01-20 13:33:13 -08002583 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2584
2585 // To make identity hashcode deterministic, set a known seed.
2586 mirror::Object::SetHashCodeSeed(987654321U);
2587 }
2588
Vladimir Marko49b0f452015-12-10 13:49:19 +00002589 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2590 LOG(ERROR) << "Failed to parse runtime options";
2591 return false;
2592 }
2593 return true;
2594 }
2595
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002596 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002597 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2598 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002599 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002600 LOG(ERROR) << "Failed to create runtime";
2601 return false;
2602 }
Andreas Gampe49c144d2016-11-14 10:11:16 -08002603
2604 // Runtime::Init will rename this thread to be "main". Prefer "dex2oat" so that "top" and
2605 // "ps -a" don't change to non-descript "main."
2606 SetThreadName(kIsDebugBuild ? "dex2oatd" : "dex2oat");
2607
Vladimir Marko307dac92015-10-20 11:20:09 +01002608 runtime_.reset(Runtime::Current());
2609 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002610 for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2611 CalleeSaveType type = CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002612 if (!runtime_->HasCalleeSaveMethod(type)) {
2613 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002614 }
2615 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002616
2617 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2618 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002619 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002620
Vladimir Marko307dac92015-10-20 11:20:09 +01002621 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002622
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002623 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2624 // Runtime::Start, give it away now so that we don't starve GC.
2625 Thread* self = Thread::Current();
2626 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002627
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002628 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002629 }
2630
Jeff Haodcdc85b2015-12-04 14:06:18 -08002631 // 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 -08002632 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002633 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002634 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002635 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002636 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002637 image_filenames_.push_back(app_image_file_name_.c_str());
2638 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002639 if (!image_writer_->Write(app_image_fd_,
2640 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002641 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002642 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002643 return false;
2644 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002645
Jeff Haodcdc85b2015-12-04 14:06:18 -08002646 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002647 dchecked_vector<uintptr_t> oat_data_begins;
2648 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2649 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002650 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002651 // Destroy ImageWriter before doing FixupElf.
2652 image_writer_.reset();
2653
Vladimir Marko944da602016-02-19 12:27:55 +00002654 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2655 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002656 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2657 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2658 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2659 if (oat_file.get() == nullptr) {
2660 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2661 return false;
2662 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002663
Vladimir Marko74527972016-11-29 15:57:32 +00002664 if (!linker::ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002665 oat_file->Erase();
2666 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2667 return false;
2668 }
2669
2670 if (oat_file->FlushCloseOrErase()) {
2671 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2672 return false;
2673 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002674 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002675 }
2676
2677 return true;
2678 }
2679
2680 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002681 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2682 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002683 std::function<std::string(const char*)> process = DotToDescriptor;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002684 return ReadCommentedInputFromFile<std::unordered_set<std::string>>(image_classes_filename,
2685 &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002686 }
2687
2688 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002689 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002690 const char* zip_filename,
2691 const char* image_classes_filename,
2692 std::string* error_msg) {
2693 std::function<std::string(const char*)> process = DotToDescriptor;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002694 return ReadCommentedInputFromZip<std::unordered_set<std::string>>(zip_filename,
2695 image_classes_filename,
2696 &process,
2697 error_msg);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002698 }
2699
2700 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2701 // the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002702 template <typename T>
2703 static T* ReadCommentedInputFromFile(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002704 const char* input_filename, std::function<std::string(const char*)>* process) {
2705 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2706 if (input_file.get() == nullptr) {
2707 LOG(ERROR) << "Failed to open input file " << input_filename;
2708 return nullptr;
2709 }
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002710 std::unique_ptr<T> result(
2711 ReadCommentedInputStream<T>(*input_file, process));
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002712 input_file->close();
2713 return result.release();
2714 }
2715
2716 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2717 // Post-process each line with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002718 template <typename T>
2719 static T* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002720 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002721 const char* input_filename,
2722 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002723 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002724 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2725 if (zip_archive.get() == nullptr) {
2726 return nullptr;
2727 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002728 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002729 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002730 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002731 zip_filename, error_msg->c_str());
2732 return nullptr;
2733 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002734 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2735 input_filename,
2736 error_msg));
2737 if (input_file.get() == nullptr) {
2738 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002739 zip_filename, error_msg->c_str());
2740 return nullptr;
2741 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002742 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2743 input_file->Size());
2744 std::istringstream input_stream(input_string);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002745 return ReadCommentedInputStream<T>(input_stream, process);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002746 }
2747
2748 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2749 // with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002750 template <typename T>
2751 static T* ReadCommentedInputStream(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002752 std::istream& in_stream,
2753 std::function<std::string(const char*)>* process) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002754 std::unique_ptr<T> output(new T());
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002755 while (in_stream.good()) {
2756 std::string dot;
2757 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08002758 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002759 continue;
2760 }
2761 if (process != nullptr) {
2762 std::string descriptor((*process)(dot.c_str()));
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002763 output->insert(output->end(), descriptor);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002764 } else {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002765 output->insert(output->end(), dot);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002766 }
2767 }
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002768 return output.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002769 }
2770
Mathieu Chartier49285c52014-12-02 15:43:48 -08002771 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002772 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2773 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002774 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampec560fc02014-07-16 09:57:39 -07002775 LOG(INFO) << "dex2oat took "
2776 << PrettyDuration(NanoTime() - start_ns_)
Andreas Gampecc967752016-12-12 13:49:00 -08002777 << " (" << PrettyDuration(ProcessCpuNanoTime() - start_cputime_ns_) << " cpu)"
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002778 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002779 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002780 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2781 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002782 }
2783
Jeff Haodcdc85b2015-12-04 14:06:18 -08002784 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2785 std::string res(image_filename);
2786 size_t last_slash = res.rfind('/');
2787 if (last_slash == std::string::npos || last_slash == 0) {
2788 return res;
2789 }
2790 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2791 if (penultimate_slash == std::string::npos) {
2792 return res;
2793 }
2794 // Check that the string in-between is the expected one.
2795 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2796 GetInstructionSetString(isa)) {
2797 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2798 return res;
2799 }
2800 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2801 }
2802
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002803 std::unique_ptr<CompilerOptions> compiler_options_;
2804 Compiler::Kind compiler_kind_;
2805
2806 InstructionSet instruction_set_;
2807 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2808
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002809 uint32_t image_file_location_oat_checksum_;
2810 uintptr_t image_file_location_oat_data_begin_;
2811 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002812 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2813
Vladimir Marko307dac92015-10-20 11:20:09 +01002814 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002815
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002816 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2817
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002818 std::unique_ptr<Runtime> runtime_;
2819
Calin Juravle1ce70852017-06-28 10:59:03 -07002820 // The spec describing how the class loader should be setup for compilation.
2821 std::unique_ptr<ClassLoaderContext> class_loader_context_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002822
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002823 // The class loader context stored in the oat file. May be equal to class_loader_context_.
Mathieu Chartierc4440772018-04-16 14:40:56 -07002824 std::unique_ptr<ClassLoaderContext> stored_class_loader_context_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002825
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002826 size_t thread_count_;
2827 uint64_t start_ns_;
Andreas Gampec560fc02014-07-16 09:57:39 -07002828 uint64_t start_cputime_ns_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002829 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002830 std::vector<std::unique_ptr<File>> oat_files_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002831 std::vector<std::unique_ptr<File>> vdex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002832 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002833 std::vector<const char*> oat_filenames_;
2834 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002835 int oat_fd_;
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00002836 int input_vdex_fd_;
2837 int output_vdex_fd_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002838 std::string input_vdex_;
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01002839 std::string output_vdex_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002840 std::unique_ptr<VdexFile> input_vdex_file_;
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00002841 int dm_fd_;
2842 std::string dm_file_location_;
2843 std::unique_ptr<ZipArchive> dm_file_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002844 std::vector<const char*> dex_filenames_;
2845 std::vector<const char*> dex_locations_;
2846 int zip_fd_;
2847 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002848 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002849 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002850 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002851 uintptr_t image_base_;
2852 const char* image_classes_zip_filename_;
2853 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002854 ImageHeader::StorageMode image_storage_mode_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002855 const char* passes_to_run_filename_;
Jeff Haoc23b0c02017-07-27 18:19:38 -07002856 const char* dirty_image_objects_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002857 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2858 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002859 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Jeff Haoc23b0c02017-07-27 18:19:38 -07002860 std::unique_ptr<std::unordered_set<std::string>> dirty_image_objects_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002861 std::unique_ptr<std::vector<std::string>> passes_to_run_;
Jeff Hao436183f2016-01-12 16:36:50 -08002862 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002863 bool is_host_;
2864 std::string android_root_;
Mathieu Chartier0b490842016-05-25 15:05:59 -07002865 // Dex files we are compiling, does not include the class path dex files.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002866 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002867 std::string no_inline_from_string_;
Mathieu Chartiera7f6b812017-12-11 13:34:29 -08002868 CompactDexLevel compact_dex_level_ = kDefaultCompactDexLevel;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002869
Vladimir Marko74527972016-11-29 15:57:32 +00002870 std::vector<std::unique_ptr<linker::ElfWriter>> elf_writers_;
2871 std::vector<std::unique_ptr<linker::OatWriter>> oat_writers_;
2872 std::vector<linker::OutputStream*> rodata_;
2873 std::vector<std::unique_ptr<linker::OutputStream>> vdex_out_;
2874 std::unique_ptr<linker::ImageWriter> image_writer_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002875 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002876
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002877 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2878 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2879
Calin Juravle1ce70852017-06-28 10:59:03 -07002880 // Note that this might contain pointers owned by class_loader_context_.
Vladimir Marko47496c22016-01-27 16:15:08 +00002881 std::vector<const DexFile*> no_inline_from_dex_files_;
2882
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07002883 bool avoid_storing_invocation_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002884 std::string swap_file_name_;
2885 int swap_fd_;
Andreas Gampee1459ae2016-06-29 09:36:30 -07002886 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap;
2887 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap;
Andreas Gampe67f02822016-06-24 21:05:23 -07002888 size_t very_large_threshold_ = std::numeric_limits<size_t>::max();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002889 std::string app_image_file_name_;
2890 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002891 std::string profile_file_;
2892 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002893 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002894 TimingLogger* timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002895 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002896 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002897
2898 // Backing storage.
Andreas Gampe097f34c2017-08-23 08:57:51 -07002899 std::forward_list<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002900
Andreas Gampeace0dc12016-01-20 13:33:13 -08002901 // See CompilerOptions.force_determinism_.
2902 bool force_determinism_;
2903
Jeff Hao16d48432017-04-05 17:05:46 -07002904 // Directory of relative classpaths.
2905 std::string classpath_dir_;
2906
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002907 // Whether the given input vdex is also the output.
2908 bool update_input_vdex_ = false;
2909
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00002910 // By default, copy the dex to the vdex file only if dex files are
2911 // compressed in APK.
2912 CopyOption copy_dex_files_ = CopyOption::kOnlyIfCompressed;
Mathieu Chartier792111c2018-02-15 13:02:15 -08002913
Calin Juravle0e09dfc2018-02-12 19:01:09 -08002914 // The reason for invoking the compiler.
2915 std::string compilation_reason_;
2916
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002917 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2918};
2919
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002920static void b13564922() {
2921#if defined(__linux__) && defined(__arm__)
2922 int major, minor;
2923 struct utsname uts;
2924 if (uname(&uts) != -1 &&
2925 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2926 ((major < 3) || ((major == 3) && (minor < 4)))) {
2927 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2928 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2929 int old_personality = personality(0xffffffff);
2930 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2931 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2932 if (new_personality == -1) {
2933 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2934 }
2935 }
2936 }
2937#endif
2938}
2939
Mathieu Chartier72041a02017-07-14 18:23:25 -07002940class ScopedGlobalRef {
2941 public:
2942 explicit ScopedGlobalRef(jobject obj) : obj_(obj) {}
2943 ~ScopedGlobalRef() {
2944 if (obj_ != nullptr) {
2945 ScopedObjectAccess soa(Thread::Current());
Ian Rogers55256cb2017-12-21 17:07:11 -08002946 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), obj_);
Mathieu Chartier72041a02017-07-14 18:23:25 -07002947 }
2948 }
2949
2950 private:
2951 jobject obj_;
2952};
2953
Andreas Gampe7b565912017-03-20 15:48:52 -07002954static dex2oat::ReturnCode CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002955 dex2oat.LoadClassProfileDescriptors();
Mathieu Chartier9e050df2017-08-09 10:05:47 -07002956 // Keep the class loader that was used for compilation live for the rest of the compilation
2957 // process.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002958 ScopedGlobalRef class_loader(dex2oat.Compile());
Andreas Gampe10e477d2014-11-19 12:57:42 -08002959
David Brazdil7b49e6c2016-09-01 11:06:18 +01002960 if (!dex2oat.WriteOutputFiles()) {
2961 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07002962 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002963 }
2964
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002965 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2966 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2967 // image writer will require this fd to generate the image.
2968 if (dex2oat.ShouldKeepOatFileOpen()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002969 if (!dex2oat.FlushOutputFiles()) {
2970 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07002971 return dex2oat::ReturnCode::kOther;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002972 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002973 } else if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07002974 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002975 }
2976
Jeff Haodcdc85b2015-12-04 14:06:18 -08002977 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002978 if (!dex2oat.HandleImage()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07002979 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002980 }
2981
2982 // When given --host, finish early without stripping.
2983 if (dex2oat.IsHost()) {
Mathieu Chartier00bf2602017-03-02 10:14:08 -08002984 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07002985 return dex2oat::ReturnCode::kOther;
Mathieu Chartier00bf2602017-03-02 10:14:08 -08002986 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08002987 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07002988 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002989 }
2990
Jeff Haodcdc85b2015-12-04 14:06:18 -08002991 // Copy stripped to unstripped location, if necessary.
2992 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07002993 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002994 }
2995
Jeff Haodcdc85b2015-12-04 14:06:18 -08002996 // FlushClose again, as stripping might have re-opened the oat files.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002997 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07002998 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002999 }
3000
3001 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003002 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003003}
3004
Andreas Gampe7b565912017-03-20 15:48:52 -07003005static dex2oat::ReturnCode CompileApp(Dex2Oat& dex2oat) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003006 // Keep the class loader that was used for compilation live for the rest of the compilation
3007 // process.
Mathieu Chartier72041a02017-07-14 18:23:25 -07003008 ScopedGlobalRef class_loader(dex2oat.Compile());
Andreas Gampe10e477d2014-11-19 12:57:42 -08003009
David Brazdil7b49e6c2016-09-01 11:06:18 +01003010 if (!dex2oat.WriteOutputFiles()) {
3011 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003012 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003013 }
3014
Jeff Haodcdc85b2015-12-04 14:06:18 -08003015 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08003016 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08003017
3018 // When given --host, finish early without stripping.
3019 if (dex2oat.IsHost()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003020 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003021 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003022 }
3023
3024 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003025 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003026 }
3027
Jeff Haodcdc85b2015-12-04 14:06:18 -08003028 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
3029 // stripped versions. If this is given, we expect to be able to open writable files by name.
3030 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003031 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003032 }
3033
Jeff Haodcdc85b2015-12-04 14:06:18 -08003034 // Flush and close the files.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003035 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003036 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003037 }
3038
3039 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003040 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003041}
3042
Andreas Gampe7b565912017-03-20 15:48:52 -07003043static dex2oat::ReturnCode Dex2oat(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003044 b13564922();
3045
3046 TimingLogger timings("compiler", false, false);
3047
Roland Levillain5c7e2602016-02-23 18:08:53 +00003048 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
3049 // might produce a stack frame too large for this function or for
3050 // functions inlining it (such as main), that would not fit the
3051 // requirements of the `-Wframe-larger-than` option.
Andreas Gampe8bdda5a2017-06-08 15:30:36 -07003052 std::unique_ptr<Dex2Oat> dex2oat = std::make_unique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003053
3054 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00003055 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003056
Calin Juravleb077e152016-02-18 18:47:37 +00003057 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02003058 // This operation involves I/O.
Mathieu Chartier11b3df32017-02-21 13:41:54 -08003059 if (dex2oat->UseProfile()) {
Calin Juravleb077e152016-02-18 18:47:37 +00003060 if (!dex2oat->LoadProfile()) {
3061 LOG(ERROR) << "Failed to process profile file";
Andreas Gampe7b565912017-03-20 15:48:52 -07003062 return dex2oat::ReturnCode::kOther;
Calin Juravle998c2162015-12-21 15:39:33 +02003063 }
3064 }
3065
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00003066 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap, and vdex.
3067
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003068 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00003069 if (!dex2oat->OpenFile()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003070 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003071 }
3072
Andreas Gampe046c7062015-05-18 23:22:54 -07003073 // Print the complete line when any of the following is true:
3074 // 1) Debug build
3075 // 2) Compiling an image
3076 // 3) Compiling with --host
3077 // 4) Compiling on the host (not a target build)
3078 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00003079 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07003080 LOG(INFO) << CommandLine();
3081 } else {
3082 LOG(INFO) << StrippedCommandLine();
3083 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003084
Andreas Gampef7882972017-03-20 16:35:24 -07003085 dex2oat::ReturnCode setup_code = dex2oat->Setup();
3086 if (setup_code != dex2oat::ReturnCode::kNoFailure) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003087 dex2oat->EraseOutputFiles();
Andreas Gampef7882972017-03-20 16:35:24 -07003088 return setup_code;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003089 }
3090
Shubham Ajmera188b2bf2017-09-20 15:53:35 -07003091 // TODO: Due to the cyclic dependencies, profile loading and verifying are
3092 // being done separately. Refactor and place the two next to each other.
3093 // If verification fails, we don't abort the compilation and instead log an
3094 // error.
3095 // TODO(b/62602192, b/65260586): We should consider aborting compilation when
3096 // the profile verification fails.
3097 // Note: If dex2oat fails, installd will remove the oat files causing the app
3098 // to fallback to apk with possible in-memory extraction. We want to avoid
3099 // that, and thus we're lenient towards profile corruptions.
3100 if (dex2oat->UseProfile()) {
3101 dex2oat->VerifyProfileData();
3102 }
3103
Wojciech Staszkiewicz529827d2016-09-15 10:30:30 -07003104 // Helps debugging on device. Can be used to determine which dalvikvm instance invoked a dex2oat
3105 // instance. Used by tools/bisection_search/bisection_search.py.
Wojciech Staszkiewicz0a4c75f2016-09-13 12:06:36 -07003106 VLOG(compiler) << "Running dex2oat (parent PID = " << getppid() << ")";
3107
Andreas Gampe7b565912017-03-20 15:48:52 -07003108 dex2oat::ReturnCode result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00003109 if (dex2oat->IsImage()) {
3110 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08003111 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00003112 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003113 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003114
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003115 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003116}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003117} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07003118
3119int main(int argc, char** argv) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003120 int result = static_cast<int>(art::Dex2oat(argc, argv));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003121 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
Pirama Arumuga Nainarab898922018-01-04 10:37:48 -08003122 // time (bug 10645725) unless we're a debug or instrumented build or running on valgrind. Note:
3123 // The Dex2Oat class should not destruct the runtime in this case.
3124 if (!art::kIsDebugBuild && !art::kIsPGOInstrumentation && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampee286b642017-04-13 12:20:42 -07003125 _exit(result);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003126 }
3127 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07003128}