blob: 782926827af3c7baa0e639cfa1a6887770e8241c [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Ian Rogersd582fa42014-11-05 23:46:43 -080038#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080039#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000040#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000051#include "debug/method_debug_info.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Ian Rogerse63db272014-07-15 15:36:11 -070053#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000054#include "dex/quick_compiler_callbacks.h"
55#include "dex/verification_results.h"
56#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080058#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020066#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/class-inl.h"
69#include "mirror/class_loader.h"
70#include "mirror/object-inl.h"
71#include "mirror/object_array-inl.h"
72#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "os.h"
Calin Juravle998c2162015-12-21 15:39:33 +020074#include "profile_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000076#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "ScopedLocalRef.h"
78#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070079#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070080#include "well_known_classes.h"
81#include "zip_archive.h"
82
83namespace art {
84
Brian Carlstrom6449c622014-02-10 23:48:36 -080085static int original_argc;
86static char** original_argv;
87
88static std::string CommandLine() {
89 std::vector<std::string> command;
90 for (int i = 0; i < original_argc; ++i) {
91 command.push_back(original_argv[i]);
92 }
93 return Join(command, ' ');
94}
95
Andreas Gampe046c7062015-05-18 23:22:54 -070096// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
97// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
98// locations are all staged).
99static std::string StrippedCommandLine() {
100 std::vector<std::string> command;
101
102 // Do a pre-pass to look for zip-fd.
103 bool saw_zip_fd = false;
104 for (int i = 0; i < original_argc; ++i) {
105 if (StartsWith(original_argv[i], "--zip-fd=")) {
106 saw_zip_fd = true;
107 break;
108 }
109 }
110
111 // Now filter out things.
112 for (int i = 0; i < original_argc; ++i) {
113 // All runtime-arg parameters are dropped.
114 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
115 i++; // Drop the next part, too.
116 continue;
117 }
118
119 // Any instruction-setXXX is dropped.
120 if (StartsWith(original_argv[i], "--instruction-set")) {
121 continue;
122 }
123
124 // The boot image is dropped.
125 if (StartsWith(original_argv[i], "--boot-image=")) {
126 continue;
127 }
128
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800129 // The image format is dropped.
130 if (StartsWith(original_argv[i], "--image-format=")) {
131 continue;
132 }
133
Andreas Gampe046c7062015-05-18 23:22:54 -0700134 // This should leave any dex-file and oat-file options, describing what we compiled.
135
136 // However, we prefer to drop this when we saw --zip-fd.
137 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700138 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700139 if (StartsWith(original_argv[i], "--zip-") ||
140 StartsWith(original_argv[i], "--dex-") ||
141 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700142 StartsWith(original_argv[i], "--swap-") ||
143 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700144 continue;
145 }
146 }
147
148 command.push_back(original_argv[i]);
149 }
150
151 // Construct the final output.
152 if (command.size() <= 1U) {
153 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
154 return "Starting dex2oat.";
155 }
156 return Join(command, ' ');
157}
158
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159static void UsageErrorV(const char* fmt, va_list ap) {
160 std::string error;
161 StringAppendV(&error, fmt, ap);
162 LOG(ERROR) << error;
163}
164
165static void UsageError(const char* fmt, ...) {
166 va_list ap;
167 va_start(ap, fmt);
168 UsageErrorV(fmt, ap);
169 va_end(ap);
170}
171
Andreas Gampe794ad762015-02-23 08:12:24 -0800172NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 va_list ap;
174 va_start(ap, fmt);
175 UsageErrorV(fmt, ap);
176 va_end(ap);
177
Brian Carlstrom6449c622014-02-10 23:48:36 -0800178 UsageError("Command: %s", CommandLine().c_str());
179
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180 UsageError("Usage: dex2oat [options]...");
181 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100182 UsageError(" -j<number>: specifies the number of threads used for compilation.");
183 UsageError(" Default is the number of detected hardware threads available on the");
184 UsageError(" host system.");
185 UsageError(" Example: -j12");
186 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700187 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 UsageError(" Example: --dex-file=/system/framework/core.jar");
189 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700190 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
191 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
192 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
193 UsageError(" --dex-location=/system/framework/core.jar");
194 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
196 UsageError(" containing a classes.dex file to compile.");
197 UsageError(" Example: --zip-fd=5");
198 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700199 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
200 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
202 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800203 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 UsageError(" Example: --oat-file=/system/framework/boot.oat");
205 UsageError("");
206 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900207 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 UsageError("");
209 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
210 UsageError(" to the file descriptor specified by --oat-fd.");
211 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
212 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800213 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
215 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800216 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 UsageError(" Example: --image=/system/framework/boot.art");
218 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 UsageError(" --image-format=(uncompressed|lz4):");
220 UsageError(" Which format to store the image.");
221 UsageError(" Example: --image-format=lz4");
222 UsageError(" Default: uncompressed");
223 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
225 UsageError(" Example: --image=frameworks/base/preloaded-classes");
226 UsageError("");
227 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
228 UsageError(" Example: --base=0x50000000");
229 UsageError("");
230 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000231 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000233 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000234 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 UsageError("");
236 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
237 UsageError(" Example: --android-root=out/host/linux-x86");
238 UsageError(" Default: $ANDROID_ROOT");
239 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800240 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700241 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700242 UsageError(" Example: --instruction-set=x86");
243 UsageError(" Default: arm");
244 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700245 UsageError(" --instruction-set-features=...,: Specify instruction set features");
246 UsageError(" Example: --instruction-set-features=div");
247 UsageError(" Default: default");
248 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700249 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
250 UsageError(" Default: disabled");
251 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800252 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800254 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100255 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100257 UsageError(" --compiler-filter="
258 "(verify-none"
259 "|interpret-only"
260 "|space"
261 "|balanced"
262 "|speed"
263 "|everything"
264 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700265 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800266 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800268 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800269 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
270 UsageError(" method for compiler filter tuning.");
271 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
272 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
273 UsageError("");
274 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
275 UsageError(" method for compiler filter tuning.");
276 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
278 UsageError("");
279 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
280 UsageError(" method for compiler filter tuning.");
281 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
282 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
283 UsageError("");
284 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
285 UsageError(" method for compiler filter tuning.");
286 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
287 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
288 UsageError("");
289 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
290 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700291 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
292 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800293 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
294 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
295 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100296 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
297 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100298 UsageError(" Has priority over the --compiler-filter option. Intended for ");
299 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100300 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
301 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
302 UsageError("");
303 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
304 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100305 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
306 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100307 UsageError(" Example: --inline-max-code-units=%d",
308 CompilerOptions::kDefaultInlineMaxCodeUnits);
309 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
310 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700311 UsageError(" --dump-timing: display a breakdown of where time was spent");
312 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700313 UsageError(" --include-patch-information: Include patching information so the generated code");
314 UsageError(" can have its base address moved without full recompilation.");
315 UsageError("");
316 UsageError(" --no-include-patch-information: Do not include patching information.");
317 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100318 UsageError(" -g");
319 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
320 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000321 UsageError(" If used without --native-debuggable, it will be best-effort only.");
322 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700323 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100324 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100325 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000326 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
327 UsageError(" debug information necessary to print backtraces. (disabled by default)");
328 UsageError("");
329 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
330 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000331 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000332 UsageError("");
333 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
334 UsageError(" Implies --debuggable.");
335 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700336 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
337 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
338 UsageError(" Use a separate --runtime-arg switch for each argument.");
339 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700340 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000341 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200342 UsageError(" Can be specified multiple time, in which case the data from the different");
343 UsageError(" profiles will be aggregated.");
344 UsageError("");
345 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
346 UsageError(" compiling. The data in this file will be compared with the data in the");
347 UsageError(" associated --profile-file and the compilation will proceed only if there is");
348 UsageError(" a significant difference (--reference-profile-file is paired with");
349 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
350 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
351 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700352 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000353 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
354 UsageError(" Cannot be used together with --profile-file.");
355 UsageError("");
356 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
357 UsageError(" accepts a file descriptor. Cannot be used together with");
358 UsageError(" --reference-profile-file.");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700359 UsageError(" --print-pass-names: print a list of pass names");
360 UsageError("");
361 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
362 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
363 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700364 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
365 "with the setting.");
366 UsageError(" Will print default if no overridden setting exists.");
367 UsageError("");
368 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
369 "Pass2Name:Pass2OptionName:Pass2Option#");
370 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
371 UsageError(" Separator used between options is a comma.");
372 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800373 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
374 UsageError(" Example: --swap-file=/data/tmp/swap.001");
375 UsageError("");
376 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
377 UsageError(" Example: --swap-fd=10");
378 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700379 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
380 UsageError(" Example: --app-image-fd=10");
381 UsageError("");
382 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
383 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
384 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800385 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
386 "input dex file.");
387 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000388 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
389 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
390 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
391 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392 std::cerr << "See log for usage error information\n";
393 exit(EXIT_FAILURE);
394}
395
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396// The primary goal of the watchdog is to prevent stuck build servers
397// during development when fatal aborts lead to a cascade of failures
398// that result in a deadlock.
399class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800400// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401#undef CHECK_PTHREAD_CALL
402#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
403 do { \
404 int rc = call args; \
405 if (rc != 0) { \
406 errno = rc; \
407 std::string message(# call); \
408 message += " failed for "; \
409 message += reason; \
410 Fatal(message); \
411 } \
412 } while (false)
413
414 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700415 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416 is_watch_dog_enabled_ = is_watch_dog_enabled;
417 if (!is_watch_dog_enabled_) {
418 return;
419 }
420 shutting_down_ = false;
421 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
425 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
427 }
428 ~WatchDog() {
429 if (!is_watch_dog_enabled_) {
430 return;
431 }
432 const char* reason = "dex2oat watch dog thread shutdown";
433 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
434 shutting_down_ = true;
435 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
436 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
437
Kenny Root51316382014-05-13 14:59:37 -0700438 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439
440 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
441 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
442 }
443
444 private:
445 static void* CallBack(void* arg) {
446 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
447 ::art::SetThreadName("dex2oat watch dog");
448 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700449 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450 }
451
Andreas Gampe794ad762015-02-23 08:12:24 -0800452 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700453 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
454 // it's rather easy to hang in unwinding.
455 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
456 // logcat logging or stderr output.
457 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 exit(1);
459 }
460
461 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
463 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700464 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465 timespec timeout_ts;
466 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
467 const char* reason = "dex2oat watch dog thread waiting";
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
469 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800470 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700472 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
473 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474 } else if (rc != 0) {
475 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
476 strerror(errno)));
477 Fatal(message.c_str());
478 }
479 }
480 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
481 }
482
483 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
Mathieu Chartier13b9f432014-09-09 17:26:58 -0700484 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700485 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800486
Andreas Gampe540138a2015-09-14 15:34:38 -0700487 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
488 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
489 // itself before that watchdog would take down the system server.
490 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491
492 bool is_watch_dog_enabled_;
493 bool shutting_down_;
494 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
495 pthread_mutex_t mutex_;
496 pthread_cond_t cond_;
497 pthread_attr_t attr_;
498 pthread_t pthread_;
499};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700500
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800501static constexpr size_t kMinDexFilesForSwap = 2;
502static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
503
504static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
505 if (is_image) {
506 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
507 return false;
508 }
509 if (dex_files.size() < kMinDexFilesForSwap) {
510 // If there are less dex files than the threshold, assume it's gonna be fine.
511 return false;
512 }
513 size_t dex_files_size = 0;
514 for (const auto* dex_file : dex_files) {
515 dex_files_size += dex_file->GetHeader().file_size_;
516 }
517 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
518}
519
Calin Juravle877fd962016-01-05 14:29:29 +0000520static void CloseAllFds(const std::vector<uint32_t>& fds, const char* descriptor) {
521 for (size_t i = 0; i < fds.size(); i++) {
522 if (close(fds[i]) < 0) {
523 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
524 }
525 }
526}
527
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800528class Dex2Oat FINAL {
529 public:
530 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100531 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800532 instruction_set_(kRuntimeISA),
533 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000534 image_file_location_oat_checksum_(0),
535 image_file_location_oat_data_begin_(0),
536 image_patch_delta_(0),
537 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700538 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800539 method_inliner_map_(),
540 runtime_(nullptr),
541 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
542 start_ns_(NanoTime()),
543 oat_fd_(-1),
544 zip_fd_(-1),
545 image_base_(0U),
546 image_classes_zip_filename_(nullptr),
547 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800548 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800549 compiled_classes_zip_filename_(nullptr),
550 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700551 compiled_methods_zip_filename_(nullptr),
552 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700553 app_image_(false),
554 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800555 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 class_loader_(nullptr),
558 elf_writers_(),
559 oat_writers_(),
560 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000561 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700562 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000563 opened_dex_files_maps_(),
564 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000565 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800566 dump_stats_(false),
567 dump_passes_(false),
568 dump_timing_(false),
569 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800570 swap_fd_(-1),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800571 app_image_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800572 timings_(timings),
573 force_determinism_(false) {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800574
575 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800576 // Log completion time before deleting the runtime_, because this accesses
577 // the runtime.
578 LogCompletionTime();
579
Vladimir Marko307dac92015-10-20 11:20:09 +0100580 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
581 // We want to just exit on non-debug builds, not bringing the runtime down
582 // in an orderly fashion. So release the following fields.
583 driver_.release();
584 image_writer_.release();
585 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
586 dex_file.release();
587 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000588 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
589 map.release();
590 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800591 for (std::unique_ptr<File>& oat_file : oat_files_) {
592 oat_file.release();
593 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100594 runtime_.release();
595 verification_results_.release();
596 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100597 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598 }
599
Roland Levillain9ec5e222015-08-17 20:18:41 +0100600 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800601 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800602 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800603 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000604 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800605 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100606 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800607
Roland Levillain9ec5e222015-08-17 20:18:41 +0100608 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000609 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100610 }
611
612 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000613 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100614 }
615
Calin Juravle877fd962016-01-05 14:29:29 +0000616 void ParseFdForCollection(const StringPiece& option,
617 const char* arg_name,
618 std::vector<uint32_t>* fds) {
619 uint32_t fd;
620 ParseUintOption(option, arg_name, &fd, Usage);
621 fds->push_back(fd);
622 }
623
Roland Levillain9ec5e222015-08-17 20:18:41 +0100624 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000625 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100626 }
627
628 void ParseBase(const StringPiece& option) {
629 DCHECK(option.starts_with("--base="));
630 const char* image_base_str = option.substr(strlen("--base=")).data();
631 char* end;
632 image_base_ = strtoul(image_base_str, &end, 16);
633 if (end == image_base_str || *end != '\0') {
634 Usage("Failed to parse hexadecimal value for option %s", option.data());
635 }
636 }
637
638 void ParseInstructionSet(const StringPiece& option) {
639 DCHECK(option.starts_with("--instruction-set="));
640 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
641 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
642 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
643 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
644 buf.get()[instruction_set_str.length()] = 0;
645 instruction_set_ = GetInstructionSetFromString(buf.get());
646 // arm actually means thumb2.
647 if (instruction_set_ == InstructionSet::kArm) {
648 instruction_set_ = InstructionSet::kThumb2;
649 }
650 }
651
652 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
653 DCHECK(option.starts_with("--instruction-set-variant="));
654 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
655 instruction_set_features_.reset(
656 InstructionSetFeatures::FromVariant(
657 instruction_set_, str.as_string(), &parser_options->error_msg));
658 if (instruction_set_features_.get() == nullptr) {
659 Usage("%s", parser_options->error_msg.c_str());
660 }
661 }
662
663 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
664 DCHECK(option.starts_with("--instruction-set-features="));
665 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
666 if (instruction_set_features_.get() == nullptr) {
667 instruction_set_features_.reset(
668 InstructionSetFeatures::FromVariant(
669 instruction_set_, "default", &parser_options->error_msg));
670 if (instruction_set_features_.get() == nullptr) {
671 Usage("Problem initializing default instruction set features variant: %s",
672 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700673 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800674 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100675 instruction_set_features_.reset(
676 instruction_set_features_->AddFeaturesFromString(str.as_string(),
677 &parser_options->error_msg));
678 if (instruction_set_features_.get() == nullptr) {
679 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
680 }
681 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682
Roland Levillain9ec5e222015-08-17 20:18:41 +0100683 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
684 DCHECK(option.starts_with("--compiler-backend="));
685 parser_options->requested_specific_compiler = true;
686 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
687 if (backend_str == "Quick") {
688 compiler_kind_ = Compiler::kQuick;
689 } else if (backend_str == "Optimizing") {
690 compiler_kind_ = Compiler::kOptimizing;
691 } else {
692 Usage("Unknown compiler backend: %s", backend_str.data());
693 }
694 }
695
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800696 void ParseImageFormat(const StringPiece& option) {
697 const StringPiece substr("--image-format=");
698 DCHECK(option.starts_with(substr));
699 const StringPiece format_str = option.substr(substr.length());
700 if (format_str == "lz4") {
701 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
702 } else if (format_str == "uncompressed") {
703 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
704 } else {
705 Usage("Unknown image format: %s", format_str.data());
706 }
707 }
708
Jeff Hao436183f2016-01-12 16:36:50 -0800709 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800710 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700711 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
712
713 if (IsAppImage() && IsBootImage()) {
714 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
715 }
716
717 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100718 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000719 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000720 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000721
Jeff Haodcdc85b2015-12-04 14:06:18 -0800722 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 Usage("Output must be supplied with either --oat-file or --oat-fd");
724 }
725
Jeff Haodcdc85b2015-12-04 14:06:18 -0800726 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800727 Usage("--oat-file should not be used with --oat-fd");
728 }
729
Roland Levillain9ec5e222015-08-17 20:18:41 +0100730 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800731 Usage("--oat-symbols should not be used with --oat-fd");
732 }
733
Roland Levillain9ec5e222015-08-17 20:18:41 +0100734 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800735 Usage("--oat-symbols should not be used with --host");
736 }
737
Jeff Haodcdc85b2015-12-04 14:06:18 -0800738 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800739 Usage("--oat-fd should not be used with --image");
740 }
741
Jeff Haodcdc85b2015-12-04 14:06:18 -0800742 if (!parser_options->oat_symbols.empty() &&
743 parser_options->oat_symbols.size() != oat_filenames_.size()) {
744 Usage("--oat-file arguments do not match --oat-symbols arguments");
745 }
746
747 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
748 Usage("--oat-file arguments do not match --image arguments");
749 }
750
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 if (android_root_.empty()) {
752 const char* android_root_env_var = getenv("ANDROID_ROOT");
753 if (android_root_env_var == nullptr) {
754 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800756 android_root_ += android_root_env_var;
757 }
758
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700759 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100760 parser_options->boot_image_filename += android_root_;
761 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800762 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100763 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000764 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800765 }
766
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700767 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800768 Usage("--image-classes should only be used with --image");
769 }
770
Vladimir Marko49b0f452015-12-10 13:49:19 +0000771 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800772 Usage("--image-classes should not be used with --boot-image");
773 }
774
775 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
776 Usage("--image-classes-zip should be used with --image-classes");
777 }
778
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700779 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800780 Usage("--compiled-classes should only be used with --image");
781 }
782
Vladimir Marko49b0f452015-12-10 13:49:19 +0000783 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800784 Usage("--compiled-classes should not be used with --boot-image");
785 }
786
787 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
788 Usage("--compiled-classes-zip should be used with --compiled-classes");
789 }
790
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800791 if (dex_filenames_.empty() && zip_fd_ == -1) {
792 Usage("Input must be supplied with either --dex-file or --zip-fd");
793 }
794
795 if (!dex_filenames_.empty() && zip_fd_ != -1) {
796 Usage("--dex-file should not be used with --zip-fd");
797 }
798
799 if (!dex_filenames_.empty() && !zip_location_.empty()) {
800 Usage("--dex-file should not be used with --zip-location");
801 }
802
803 if (dex_locations_.empty()) {
804 for (const char* dex_file_name : dex_filenames_) {
805 dex_locations_.push_back(dex_file_name);
806 }
807 } else if (dex_locations_.size() != dex_filenames_.size()) {
808 Usage("--dex-location arguments do not match --dex-file arguments");
809 }
810
Jeff Haodcdc85b2015-12-04 14:06:18 -0800811 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
812 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
813 Usage("--oat-file arguments must be singular or match --dex-file arguments");
814 }
815 }
816
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800817 if (zip_fd_ != -1 && zip_location_.empty()) {
818 Usage("--zip-location should be supplied with --zip-fd");
819 }
820
Vladimir Marko49b0f452015-12-10 13:49:19 +0000821 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800822 if (image_base_ == 0) {
823 Usage("Non-zero --base not specified");
824 }
825 }
826
Calin Juravle877fd962016-01-05 14:29:29 +0000827 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
828 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
829 }
Calin Juravle998c2162015-12-21 15:39:33 +0200830 if (!profile_files_.empty()) {
831 if (!reference_profile_files_.empty() &&
832 (reference_profile_files_.size() != profile_files_.size())) {
833 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
834 }
Calin Juravle877fd962016-01-05 14:29:29 +0000835 } else if (!reference_profile_files_.empty()) {
836 Usage("--reference-profile-file should only be supplied with --profile-file");
837 }
838 if (!profile_files_fd_.empty()) {
839 if (!reference_profile_files_fd_.empty() &&
840 (reference_profile_files_fd_.size() != profile_files_fd_.size())) {
841 Usage("If specified, --reference-profile-file-fd should match the number",
842 " of --profile-file-fd.");
843 }
844 } else if (!reference_profile_files_fd_.empty()) {
845 Usage("--reference-profile-file-fd should only be supplied with --profile-file-fd");
Calin Juravle998c2162015-12-21 15:39:33 +0200846 }
847
Roland Levillain9ec5e222015-08-17 20:18:41 +0100848 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800849 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800850 }
851
852 // If no instruction set feature was given, use the default one for the target
853 // instruction set.
854 if (instruction_set_features_.get() == nullptr) {
855 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100856 InstructionSetFeatures::FromVariant(
857 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800858 if (instruction_set_features_.get() == nullptr) {
859 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100860 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800861 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800862 }
863
864 if (instruction_set_ == kRuntimeISA) {
865 std::unique_ptr<const InstructionSetFeatures> runtime_features(
866 InstructionSetFeatures::FromCppDefines());
867 if (!instruction_set_features_->Equals(runtime_features.get())) {
868 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
869 << *instruction_set_features_ << ") and those of dex2oat executable ("
870 << *runtime_features <<") for the command line:\n"
871 << CommandLine();
872 }
873 }
874
Roland Levillaina215b952015-08-07 11:38:32 +0100875 // It they are not set, use default values for inlining settings.
876 // TODO: We should rethink the compiler filter. We mostly save
877 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000878 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
879 compiler_options_->inline_depth_limit_ =
880 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100881 // Implementation of the space filter: limit inlining depth.
882 ? CompilerOptions::kSpaceFilterInlineDepthLimit
883 : CompilerOptions::kDefaultInlineDepthLimit;
884 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000885 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
886 compiler_options_->inline_max_code_units_ =
887 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100888 // Implementation of the space filter: limit inlining max code units.
889 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
890 : CompilerOptions::kDefaultInlineMaxCodeUnits;
891 }
892
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800893 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800894 // Set the compilation target's implicit checks options.
895 switch (instruction_set_) {
896 case kArm:
897 case kThumb2:
898 case kArm64:
899 case kX86:
900 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700901 case kMips:
902 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000903 compiler_options_->implicit_null_checks_ = true;
904 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800905 break;
906
907 default:
908 // Defaults are correct.
909 break;
910 }
911
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000912 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800913
Jeff Hao436183f2016-01-12 16:36:50 -0800914 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800915 Usage("--multi-image can only be used when creating boot images");
916 }
Jeff Hao436183f2016-01-12 16:36:50 -0800917 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800918 Usage("--multi-image cannot be used with multiple image names");
919 }
920
921 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
922 if (!kIsTargetBuild && IsBootImage()) {
923 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800924 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800925 }
926 }
927
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800928 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100929 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800930 watchdog_.reset(new WatchDog(true));
931 }
932
933 // Fill some values into the key-value store for the oat header.
934 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800935
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800936 // Automatically force determinism for the boot image in a host build if the default GC is CMS
937 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
938 // one by passing the option `-Xgc:nonconcurrent` (see below).
939 if (!kIsTargetBuild && IsBootImage()) {
940 if (SupportsDeterministicCompilation()) {
941 force_determinism_ = true;
942 } else {
943 LOG(WARNING) << "Deterministic compilation is disabled.";
944 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800945 }
946 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100947 }
948
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800949 static bool SupportsDeterministicCompilation() {
950 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
951 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
952 !kEmitCompilerReadBarrier;
953 }
954
Jeff Hao436183f2016-01-12 16:36:50 -0800955 void ExpandOatAndImageFilenames() {
956 std::string base_oat = oat_filenames_[0];
957 size_t last_oat_slash = base_oat.rfind('/');
958 if (last_oat_slash == std::string::npos) {
959 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
960 }
961 // We also need to honor path components that were encoded through '@'. Otherwise the loading
962 // code won't be able to find the images.
963 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
964 last_oat_slash = base_oat.rfind('@');
965 }
966 base_oat = base_oat.substr(0, last_oat_slash + 1);
967
968 std::string base_img = image_filenames_[0];
969 size_t last_img_slash = base_img.rfind('/');
970 if (last_img_slash == std::string::npos) {
971 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
972 }
973 // We also need to honor path components that were encoded through '@'. Otherwise the loading
974 // code won't be able to find the images.
975 if (base_img.find('@', last_img_slash) != std::string::npos) {
976 last_img_slash = base_img.rfind('@');
977 }
978
979 // Get the prefix, which is the primary image name (without path components). Strip the
980 // extension.
981 std::string prefix = base_img.substr(last_img_slash + 1);
982 if (prefix.rfind('.') != std::string::npos) {
983 prefix = prefix.substr(0, prefix.rfind('.'));
984 }
985 if (!prefix.empty()) {
986 prefix = prefix + "-";
987 }
988
989 base_img = base_img.substr(0, last_img_slash + 1);
990
991 // Note: we have some special case here for our testing. We have to inject the differentiating
992 // parts for the different core images.
993 std::string infix; // Empty infix by default.
994 {
995 // Check the first name.
996 std::string dex_file = oat_filenames_[0];
997 size_t last_dex_slash = dex_file.rfind('/');
998 if (last_dex_slash != std::string::npos) {
999 dex_file = dex_file.substr(last_dex_slash + 1);
1000 }
1001 size_t last_dex_dot = dex_file.rfind('.');
1002 if (last_dex_dot != std::string::npos) {
1003 dex_file = dex_file.substr(0, last_dex_dot);
1004 }
1005 if (StartsWith(dex_file, "core-")) {
1006 infix = dex_file.substr(strlen("core"));
1007 }
1008 }
1009
1010 // Now create the other names. Use a counted loop to skip the first one.
1011 for (size_t i = 1; i < dex_locations_.size(); ++i) {
1012 // TODO: Make everything properly std::string.
1013 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
1014 char_backing_storage_.push_back(base_img + image_name);
1015 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1016
1017 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
1018 char_backing_storage_.push_back(base_oat + oat_name);
1019 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1020 }
1021 }
1022
Andreas Gampe8994a042015-12-30 19:03:17 +00001023 // Modify the input string in the following way:
1024 // 0) Assume input is /a/b/c.d
1025 // 1) Strip the path -> c.d
1026 // 2) Inject prefix p -> pc.d
1027 // 3) Inject infix i -> pci.d
1028 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001029 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001030 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001031 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001032 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001033 size_t last_dex_slash = in.rfind('/');
1034 if (last_dex_slash != std::string::npos) {
1035 in = in.substr(last_dex_slash + 1);
1036 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001037 if (!prefix.empty()) {
1038 in = prefix + in;
1039 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001040 if (!infix.empty()) {
1041 // Inject infix.
1042 size_t last_dot = in.rfind('.');
1043 if (last_dot != std::string::npos) {
1044 in.insert(last_dot, infix);
1045 }
1046 }
1047 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001048 in = in.substr(0, in.length() - strlen(".jar")) +
1049 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001050 }
1051 return in;
1052 }
1053
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001054 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001055 std::ostringstream oss;
1056 for (int i = 0; i < argc; ++i) {
1057 if (i > 0) {
1058 oss << ' ';
1059 }
1060 oss << argv[i];
1061 }
1062 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1063 oss.str(""); // Reset.
1064 oss << kRuntimeISA;
1065 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1066 key_value_store_->Put(
1067 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001068 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001069 key_value_store_->Put(
1070 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001071 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdilce4b0ba2016-01-28 15:05:49 +00001072 key_value_store_->Put(
1073 OatHeader::kExtractOnlyKey,
1074 compiler_options_->IsExtractOnly() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001075 }
1076
1077 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1078 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1079 // returns, arguments have been successfully parsed.
1080 void ParseArgs(int argc, char** argv) {
1081 original_argc = argc;
1082 original_argv = argv;
1083
1084 InitLogging(argv);
1085
1086 // Skip over argv[0].
1087 argv++;
1088 argc--;
1089
1090 if (argc == 0) {
1091 Usage("No arguments specified");
1092 }
1093
1094 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001095 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001096
1097 for (int i = 0; i < argc; i++) {
1098 const StringPiece option(argv[i]);
1099 const bool log_options = false;
1100 if (log_options) {
1101 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1102 }
1103 if (option.starts_with("--dex-file=")) {
1104 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1105 } else if (option.starts_with("--dex-location=")) {
1106 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1107 } else if (option.starts_with("--zip-fd=")) {
1108 ParseZipFd(option);
1109 } else if (option.starts_with("--zip-location=")) {
1110 zip_location_ = option.substr(strlen("--zip-location=")).data();
1111 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001112 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001113 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001114 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001115 } else if (option.starts_with("--oat-fd=")) {
1116 ParseOatFd(option);
1117 } else if (option == "--watch-dog") {
1118 parser_options->watch_dog_enabled = true;
1119 } else if (option == "--no-watch-dog") {
1120 parser_options->watch_dog_enabled = false;
1121 } else if (option.starts_with("-j")) {
1122 ParseJ(option);
1123 } else if (option.starts_with("--oat-location=")) {
1124 oat_location_ = option.substr(strlen("--oat-location=")).data();
1125 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001127 } else if (option.starts_with("--image-classes=")) {
1128 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1129 } else if (option.starts_with("--image-classes-zip=")) {
1130 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001131 } else if (option.starts_with("--image-format=")) {
1132 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001133 } else if (option.starts_with("--compiled-classes=")) {
1134 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1135 } else if (option.starts_with("--compiled-classes-zip=")) {
1136 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1137 } else if (option.starts_with("--compiled-methods=")) {
1138 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1139 } else if (option.starts_with("--compiled-methods-zip=")) {
1140 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1141 } else if (option.starts_with("--base=")) {
1142 ParseBase(option);
1143 } else if (option.starts_with("--boot-image=")) {
1144 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1145 } else if (option.starts_with("--android-root=")) {
1146 android_root_ = option.substr(strlen("--android-root=")).data();
1147 } else if (option.starts_with("--instruction-set=")) {
1148 ParseInstructionSet(option);
1149 } else if (option.starts_with("--instruction-set-variant=")) {
1150 ParseInstructionSetVariant(option, parser_options.get());
1151 } else if (option.starts_with("--instruction-set-features=")) {
1152 ParseInstructionSetFeatures(option, parser_options.get());
1153 } else if (option.starts_with("--compiler-backend=")) {
1154 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001155 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001156 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1157 } else if (option.starts_with("--reference-profile-file=")) {
1158 reference_profile_files_.push_back(
1159 option.substr(strlen("--reference-profile-file=")).ToString());
Calin Juravle877fd962016-01-05 14:29:29 +00001160 } else if (option.starts_with("--profile-file-fd=")) {
1161 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
1162 } else if (option.starts_with("--reference-profile-file-fd=")) {
1163 ParseFdForCollection(option, "--reference_profile-file-fd", &reference_profile_files_fd_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001164 } else if (option == "--no-profile-file") {
1165 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001166 } else if (option == "--host") {
1167 is_host_ = true;
1168 } else if (option == "--runtime-arg") {
1169 if (++i >= argc) {
1170 Usage("Missing required argument for --runtime-arg");
1171 }
1172 if (log_options) {
1173 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1174 }
1175 runtime_args_.push_back(argv[i]);
1176 } else if (option == "--dump-timing") {
1177 dump_timing_ = true;
1178 } else if (option == "--dump-passes") {
1179 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001180 } else if (option == "--dump-stats") {
1181 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001182 } else if (option.starts_with("--swap-file=")) {
1183 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1184 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001185 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1186 } else if (option.starts_with("--app-image-file=")) {
1187 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1188 } else if (option.starts_with("--app-image-fd=")) {
1189 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001190 } else if (option.starts_with("--verbose-methods=")) {
1191 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1192 // conditional on having verbost methods.
1193 gLogVerbosity.compiler = false;
1194 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001195 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001196 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001197 } else if (option.starts_with("--no-inline-from=")) {
1198 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001199 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001200 if (!SupportsDeterministicCompilation()) {
1201 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001202 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001203 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001204 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001205 Usage("Unknown argument %s", option.data());
1206 }
1207 }
1208
Jeff Hao436183f2016-01-12 16:36:50 -08001209 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001210
1211 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001212 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001213 }
1214
Jeff Haodcdc85b2015-12-04 14:06:18 -08001215 // Check whether the oat output files are writable, and open them for later. Also open a swap
1216 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001217 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001218 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1219 PruneNonExistentDexFiles();
1220
Jeff Hao436183f2016-01-12 16:36:50 -08001221 // Expand oat and image filenames for multi image.
1222 if (IsBootImage() && multi_image_) {
1223 ExpandOatAndImageFilenames();
1224 }
1225
Jeff Haodcdc85b2015-12-04 14:06:18 -08001226 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001227 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001228 for (const char* oat_filename : oat_filenames_) {
1229 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1230 if (oat_file.get() == nullptr) {
1231 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1232 return false;
1233 }
1234 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1235 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1236 oat_file->Erase();
1237 return false;
1238 }
1239 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001240 }
1241 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001242 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1243 oat_file->DisableAutoClose();
1244 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001245 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1246 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001247 if (oat_file.get() == nullptr) {
1248 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1249 return false;
1250 }
1251 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1252 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1253 oat_file->Erase();
1254 return false;
1255 }
1256 oat_filenames_.push_back(oat_location_.c_str());
1257 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001258 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001259
1260 // Swap file handling.
1261 //
1262 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1263 // that we can use for swap.
1264 //
1265 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1266 // will immediately unlink to satisfy the swap fd assumption.
1267 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1268 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1269 if (swap_file.get() == nullptr) {
1270 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1271 return false;
1272 }
1273 swap_fd_ = swap_file->Fd();
1274 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1275 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1276 // released immediately.
1277 unlink(swap_file_name_.c_str());
1278 }
Jeff Hao436183f2016-01-12 16:36:50 -08001279
1280 // If we use a swap file, ensure we are above the threshold to make it necessary.
1281 if (swap_fd_ != -1) {
1282 if (!UseSwap(IsBootImage(), dex_files_)) {
1283 close(swap_fd_);
1284 swap_fd_ = -1;
1285 VLOG(compiler) << "Decided to run without swap.";
1286 } else {
1287 LOG(INFO) << "Large app, accepted running with swap.";
1288 }
1289 }
1290 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1291
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001292 return true;
1293 }
1294
Jeff Haodcdc85b2015-12-04 14:06:18 -08001295 void EraseOatFiles() {
1296 for (size_t i = 0; i < oat_files_.size(); ++i) {
1297 DCHECK(oat_files_[i].get() != nullptr);
1298 oat_files_[i]->Erase();
1299 oat_files_[i].reset();
1300 }
Andreas Gampea650e702014-12-03 14:28:02 -08001301 }
1302
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001303 void Shutdown() {
1304 ScopedObjectAccess soa(Thread::Current());
1305 for (jobject dex_cache : dex_caches_) {
1306 soa.Env()->DeleteLocalRef(dex_cache);
1307 }
1308 dex_caches_.clear();
1309 }
1310
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001311 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1312 // boot class path.
1313 bool Setup() {
1314 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001315 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001316
1317 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1318 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001319 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001320
Vladimir Marko307dac92015-10-20 11:20:09 +01001321 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001322 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001323 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001324 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001325 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001326 CompilerCallbacks::CallbackMode::kCompileBootImage :
1327 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001328
Vladimir Marko49b0f452015-12-10 13:49:19 +00001329 RuntimeArgumentMap runtime_options;
1330 if (!PrepareRuntimeOptions(&runtime_options)) {
1331 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001332 }
1333
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001334 CreateOatWriters();
1335 if (!AddDexFileSources()) {
1336 return false;
1337 }
1338
1339 if (IsBootImage() && image_filenames_.size() > 1) {
1340 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1341 // We need this for the multi-image case.
1342 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1343 }
1344
1345 if (!IsBootImage()) {
1346 // When compiling an app, create the runtime early to retrieve
1347 // the image location key needed for the oat header.
1348 if (!CreateRuntime(std::move(runtime_options))) {
1349 return false;
1350 }
1351
David Brazdilce4b0ba2016-01-28 15:05:49 +00001352 if (compiler_options_->IsExtractOnly()) {
1353 // ExtractOnly oat files only contain non-quickened DEX code and are
1354 // therefore independent of the image file.
1355 image_file_location_oat_checksum_ = 0u;
1356 image_file_location_oat_data_begin_ = 0u;
1357 image_patch_delta_ = 0;
1358 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001359 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1360 std::vector<gc::space::ImageSpace*> image_spaces =
1361 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1362 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1363 image_file_location_oat_data_begin_ =
1364 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1365 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1366 // Store the boot image filename(s).
1367 std::vector<std::string> image_filenames;
1368 for (const gc::space::ImageSpace* image_space : image_spaces) {
1369 image_filenames.push_back(image_space->GetImageFilename());
1370 }
1371 std::string image_file_location = Join(image_filenames, ':');
1372 if (!image_file_location.empty()) {
1373 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1374 }
1375 }
1376
1377 // Open dex files for class path.
1378 const std::vector<std::string> class_path_locations =
1379 GetClassPathLocations(runtime_->GetClassPathString());
1380 OpenClassPathFiles(class_path_locations, &class_path_files_);
1381
1382 // Store the classpath we have right now.
1383 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1384 key_value_store_->Put(OatHeader::kClassPathKey,
1385 OatFile::EncodeDexFileDependencies(class_path_files));
1386 }
1387
1388 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001389 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001390 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1391 rodata_.reserve(oat_writers_.size());
1392 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1393 rodata_.push_back(elf_writers_[i]->StartRoData());
1394 // Unzip or copy dex files straight to the oat file.
1395 std::unique_ptr<MemMap> opened_dex_files_map;
1396 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1397 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1398 oat_files_[i].get(),
1399 instruction_set_,
1400 instruction_set_features_.get(),
1401 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001402 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001403 &opened_dex_files_map,
1404 &opened_dex_files)) {
1405 return false;
1406 }
1407 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1408 if (opened_dex_files_map != nullptr) {
1409 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1410 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
1411 dex_file_oat_filename_map_.emplace(dex_file.get(), oat_filenames_[i]);
1412 opened_dex_files_.push_back(std::move(dex_file));
1413 }
1414 } else {
1415 DCHECK(opened_dex_files.empty());
1416 }
1417 }
1418 }
1419
1420 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1421 if (IsBootImage()) {
1422 // For boot image, pass opened dex files to the Runtime::Create().
1423 // Note: Runtime acquires ownership of these dex files.
1424 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001425 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001426 return false;
1427 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001428 }
1429
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001430 // If we're doing the image, override the compiler filter to force full compilation. Must be
1431 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1432 // compilation of class initializers.
1433 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001434 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001435 WellKnownClasses::Init(self->GetJniEnv());
1436
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001437 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001438 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001439 constexpr bool kSaveDexInput = false;
1440 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001441 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001442 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001443
1444 // Handle and ClassLoader creation needs to come after Runtime::Create.
1445 ScopedObjectAccess soa(self);
1446
1447 // Classpath: first the class-path given.
1448 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1449
1450 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1451 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1452
1453 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001454 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001455
1456 // Ensure opened dex files are writable for dex-to-dex transformations.
1457 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1458 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1459 PLOG(ERROR) << "Failed to make .dex files writeable.";
1460 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001461 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001462 }
1463
1464 // Ensure that the dex caches stay live since we don't want class unloading
1465 // to occur during compilation.
1466 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001467 ScopedObjectAccess soa(self);
1468 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001469 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001470 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001471
1472 /*
1473 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1474 * Don't bother to check if we're doing the image.
1475 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001476 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001477 compiler_options_->IsCompilationEnabled() &&
1478 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001479 size_t num_methods = 0;
1480 for (size_t i = 0; i != dex_files_.size(); ++i) {
1481 const DexFile* dex_file = dex_files_[i];
1482 CHECK(dex_file != nullptr);
1483 num_methods += dex_file->NumMethodIds();
1484 }
1485 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1486 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1487 VLOG(compiler) << "Below method threshold, compiling anyways";
1488 }
1489 }
1490
1491 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001492 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001493
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001494 // If we need to keep the oat file open for the image writer.
1495 bool ShouldKeepOatFileOpen() const {
1496 return IsImage() && oat_fd_ != kInvalidFd;
1497 }
1498
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001499 // Create and invoke the compiler driver. This will compile all the dex files.
1500 void Compile() {
1501 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1502 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001503
Vladimir Marko47496c22016-01-27 16:15:08 +00001504 // Find the dex files we should not inline from.
1505
1506 std::vector<std::string> no_inline_filters;
1507 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001508
1509 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001510 const std::string core_oj = "core-oj";
1511 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1512 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001513 }
1514
Vladimir Marko47496c22016-01-27 16:15:08 +00001515 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001516 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1517 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1518 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1519 &class_linker->GetBootClassPath(),
1520 &class_path_files,
1521 &dex_files_
1522 };
1523 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001524 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001525 for (const std::string& filter : no_inline_filters) {
1526 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1527 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1528 // base location passes the StartsWith() test, so do all extra locations.
1529 std::string dex_location = dex_file->GetLocation();
1530 if (filter.find('/') == std::string::npos) {
1531 // The filter does not contain the path. Remove the path from dex_location as well.
1532 size_t last_slash = dex_file->GetLocation().rfind('/');
1533 if (last_slash != std::string::npos) {
1534 dex_location = dex_location.substr(last_slash + 1);
1535 }
1536 }
1537
1538 if (StartsWith(dex_location, filter.c_str())) {
1539 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1540 no_inline_from_dex_files_.push_back(dex_file);
1541 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001542 }
1543 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001544 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001545 }
1546 if (!no_inline_from_dex_files_.empty()) {
1547 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001548 }
1549 }
1550
Vladimir Marko307dac92015-10-20 11:20:09 +01001551 driver_.reset(new CompilerDriver(compiler_options_.get(),
1552 verification_results_.get(),
1553 &method_inliner_map_,
1554 compiler_kind_,
1555 instruction_set_,
1556 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001557 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001558 image_classes_.release(),
1559 compiled_classes_.release(),
Vladimir Marko60654022016-02-16 12:50:23 +00001560 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001561 thread_count_,
1562 dump_stats_,
1563 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001564 compiler_phases_timings_.get(),
1565 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001566 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001567 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001568 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 }
1570
Jeff Hao436183f2016-01-12 16:36:50 -08001571 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001572 // ensure the references between the two are correct.
1573 //
1574 // Currently we have a memory layout that looks something like this:
1575 //
1576 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001577 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001578 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001579 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001580 // +--------------+
1581 // | alloc spaces |
1582 // +--------------+
1583 //
Jeff Hao436183f2016-01-12 16:36:50 -08001584 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001585 //
Jeff Hao436183f2016-01-12 16:36:50 -08001586 // 1. The images are expected to be loaded at an absolute address and
1587 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001588 //
Jeff Hao436183f2016-01-12 16:36:50 -08001589 // 2. There are absolute pointers from Methods in the images to their
1590 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001591 //
Jeff Hao436183f2016-01-12 16:36:50 -08001592 // 3. There are absolute pointers from the code in the oat files to Methods
1593 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001594 //
Jeff Hao436183f2016-01-12 16:36:50 -08001595 // 4. There are absolute pointers from code in the oat files to other code
1596 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001597 //
1598 // To get this all correct, we go through several steps.
1599 //
Jeff Hao436183f2016-01-12 16:36:50 -08001600 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001601 // the oat data size and code size. During this stage, we also set
1602 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001603 //
Jeff Hao436183f2016-01-12 16:36:50 -08001604 // 2. We prepare offsets for the objects in the images and calculate
1605 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 //
Jeff Hao436183f2016-01-12 16:36:50 -08001607 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001608 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001609 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001610 // can prepare the ELF headers and we then know the ELF memory segment
1611 // layout and we can now resolve all references. The compiler provides
1612 // LinkerPatch information in each CompiledMethod and we resolve these,
1613 // using the layout information and image object locations provided by
1614 // image writer, as we're writing the method code.
1615 //
Jeff Hao436183f2016-01-12 16:36:50 -08001616 // 4. We create the image files. They need to know where the oat files
1617 // will be loaded after itself. Originally oat files were simply
1618 // memory mapped so we could predict where their contents were based
1619 // on the file size. Now that they are ELF files, we need to inspect
1620 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001621 // where the oat header is located within.
1622 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001623 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001624 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001625 // load the .so at the desired location at runtime by offsetting the
1626 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001627 // TODO: Do this in step 3. We already know the layout there.
1628 //
1629 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1630 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001631
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1633 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001634 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1635 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001636 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001637 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1638
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001639 // Sync the data to the file, in case we did dex2dex transformations.
1640 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1641 if (!map->Sync()) {
1642 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1643 return false;
1644 }
1645 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001646
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001647 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001648 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001649 gc::Heap* const heap = Runtime::Current()->GetHeap();
1650 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001651 image_base_ = std::max(image_base_, RoundUp(
1652 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1653 kPageSize));
1654 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001655 // The non moving space is right after the oat file. Put the preferred app image location
1656 // right after the non moving space so that we ideally get a continuous immune region for
1657 // the GC.
1658 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1659 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001660 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1661 }
1662
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001663 image_writer_.reset(new ImageWriter(*driver_,
1664 image_base_,
1665 compiler_options_->GetCompilePic(),
1666 IsAppImage(),
1667 image_storage_mode_,
1668 oat_filenames_,
1669 dex_file_oat_filename_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001670
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001671 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001672 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1673 if (!image_writer_->PrepareImageAddressSpace()) {
1674 LOG(ERROR) << "Failed to prepare image address space.";
1675 return false;
1676 }
1677 }
1678
1679 {
1680 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001681 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1683 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001684
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1686 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files);
Vladimir Marko10c13562015-11-25 14:33:36 +00001687
David Srbecky0c4572e2016-01-22 19:19:25 +00001688 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1689 size_t text_size = oat_writer->GetSize() - rodata_size;
Vladimir Marko60654022016-02-16 12:50:23 +00001690 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1691
1692 if (IsImage()) {
1693 // Update oat estimates.
1694 DCHECK(image_writer_ != nullptr);
1695 DCHECK_LT(i, oat_filenames_.size());
1696
1697 image_writer_->UpdateOatFile(i, elf_writer->GetLoadedSize());
1698 }
1699 }
1700
1701 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
1702 std::unique_ptr<File>& oat_file = oat_files_[i];
1703 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1704 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1705
1706 // We need to mirror the layout of the ELF file in the compressed debug-info.
1707 // Therefore we need to propagate the sizes of at least those sections.
1708 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001709
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001710 OutputStream*& rodata = rodata_[i];
1711 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001712 if (!oat_writer->WriteRodata(rodata)) {
1713 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1714 return false;
1715 }
1716 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001717 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001718
Jeff Haodcdc85b2015-12-04 14:06:18 -08001719 OutputStream* text = elf_writer->StartText();
1720 if (!oat_writer->WriteCode(text)) {
1721 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1722 return false;
1723 }
1724 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001725
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001726 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1727 image_file_location_oat_checksum_,
1728 image_file_location_oat_data_begin_,
1729 image_patch_delta_)) {
1730 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1731 return false;
1732 }
1733
Jeff Haodcdc85b2015-12-04 14:06:18 -08001734 elf_writer->WriteDynamicSection();
1735 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1736 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001737
Jeff Haodcdc85b2015-12-04 14:06:18 -08001738 if (!elf_writer->End()) {
1739 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1740 return false;
1741 }
1742
1743 // Flush the oat file.
1744 if (oat_files_[i] != nullptr) {
1745 if (oat_files_[i]->Flush() != 0) {
1746 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001747 return false;
1748 }
1749 }
1750
Jeff Haodcdc85b2015-12-04 14:06:18 -08001751 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001752
1753 oat_writer.reset();
1754 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001755 }
1756 }
1757
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001758 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001759 }
1760
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001761 // If we are compiling an image, invoke the image creation routine. Else just skip.
1762 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001763 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001764 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1765 if (!CreateImageFile()) {
1766 return false;
1767 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001768 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001769 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001770 return true;
1771 }
1772
Jeff Haodcdc85b2015-12-04 14:06:18 -08001773 // Create a copy from stripped to unstripped.
1774 bool CopyStrippedToUnstripped() {
1775 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1776 // If we don't want to strip in place, copy from stripped location to unstripped location.
1777 // We need to strip after image creation because FixupElf needs to use .strtab.
1778 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1779 // If the oat file is still open, flush it.
1780 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1781 if (!FlushCloseOatFile(i)) {
1782 return false;
1783 }
1784 }
1785
1786 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1787 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1788 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1789 size_t buffer_size = 8192;
1790 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1791 while (true) {
1792 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1793 if (bytes_read <= 0) {
1794 break;
1795 }
1796 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1797 CHECK(write_ok);
1798 }
1799 if (out->FlushCloseOrErase() != 0) {
1800 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1801 return false;
1802 }
1803 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1804 }
1805 }
1806 return true;
1807 }
1808
1809 bool FlushOatFiles() {
1810 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1811 for (size_t i = 0; i < oat_files_.size(); ++i) {
1812 if (oat_files_[i].get() != nullptr) {
1813 if (oat_files_[i]->Flush() != 0) {
1814 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1815 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001816 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001817 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001818 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001819 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001820 return true;
1821 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001822
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 bool FlushCloseOatFile(size_t i) {
1824 if (oat_files_[i].get() != nullptr) {
1825 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001826 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001827 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001828 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001829 }
1830 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001831 return true;
1832 }
1833
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 bool FlushCloseOatFiles() {
1835 bool result = true;
1836 for (size_t i = 0; i < oat_files_.size(); ++i) {
1837 result &= FlushCloseOatFile(i);
1838 }
1839 return result;
1840 }
1841
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001842 void DumpTiming() {
1843 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1844 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1845 }
1846 if (dump_passes_) {
1847 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1848 }
1849 }
1850
1851 CompilerOptions* GetCompilerOptions() const {
1852 return compiler_options_.get();
1853 }
1854
Andreas Gampe10e477d2014-11-19 12:57:42 -08001855 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001856 return IsAppImage() || IsBootImage();
1857 }
1858
1859 bool IsAppImage() const {
1860 return app_image_;
1861 }
1862
1863 bool IsBootImage() const {
1864 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001865 }
1866
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001867 bool IsHost() const {
1868 return is_host_;
1869 }
1870
Calin Juravle998c2162015-12-21 15:39:33 +02001871 bool UseProfileGuidedCompilation() const {
Calin Juravle877fd962016-01-05 14:29:29 +00001872 return !profile_files_.empty() || !profile_files_fd_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02001873 }
1874
1875 bool ProcessProfiles() {
1876 DCHECK(UseProfileGuidedCompilation());
1877 ProfileCompilationInfo* info = nullptr;
Calin Juravle877fd962016-01-05 14:29:29 +00001878 bool result = false;
1879 if (profile_files_.empty()) {
1880 DCHECK(!profile_files_fd_.empty());
1881 result = ProfileAssistant::ProcessProfiles(
1882 profile_files_fd_, reference_profile_files_fd_, &info);
1883 CloseAllFds(profile_files_fd_, "profile_files_fd_");
1884 CloseAllFds(reference_profile_files_fd_, "reference_profile_files_fd_");
1885 } else {
1886 result = ProfileAssistant::ProcessProfiles(
1887 profile_files_, reference_profile_files_, &info);
Calin Juravle998c2162015-12-21 15:39:33 +02001888 }
Calin Juravle877fd962016-01-05 14:29:29 +00001889
1890 profile_compilation_info_.reset(info);
1891
1892 return result;
Calin Juravle998c2162015-12-21 15:39:33 +02001893 }
1894
1895 bool ShouldCompileBasedOnProfiles() const {
1896 DCHECK(UseProfileGuidedCompilation());
1897 // If we are given profiles, compile only if we have new information.
1898 return profile_compilation_info_ != nullptr;
1899 }
1900
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001901 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001902 template <typename T>
1903 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1904 std::vector<T*> result;
1905 result.reserve(src.size());
1906 for (const std::unique_ptr<T>& t : src) {
1907 result.push_back(t.get());
1908 }
1909 return result;
1910 }
1911
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001912 std::string GetMultiImageBootClassPath() {
1913 DCHECK(IsBootImage());
1914 DCHECK_GT(oat_filenames_.size(), 1u);
1915 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1916 // too, but need to strip all path components (they will be re-established when loading).
1917 std::ostringstream bootcp_oss;
1918 bool first_bootcp = true;
1919 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1920 if (!first_bootcp) {
1921 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001922 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001923
1924 std::string dex_loc = dex_locations_[i];
1925 std::string image_filename = image_filenames_[i];
1926
1927 // Use the dex_loc path, but the image_filename name (without path elements).
1928 size_t dex_last_slash = dex_loc.rfind('/');
1929
1930 // npos is max(size_t). That makes this a bit ugly.
1931 size_t image_last_slash = image_filename.rfind('/');
1932 size_t image_last_at = image_filename.rfind('@');
1933 size_t image_last_sep = (image_last_slash == std::string::npos)
1934 ? image_last_at
1935 : (image_last_at == std::string::npos)
1936 ? std::string::npos
1937 : std::max(image_last_slash, image_last_at);
1938 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1939
1940 if (dex_last_slash == std::string::npos) {
1941 dex_loc = image_filename.substr(image_last_sep + 1);
1942 } else {
1943 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1944 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001945 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001946
1947 // Image filenames already end with .art, no need to replace.
1948
1949 bootcp_oss << dex_loc;
1950 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001951 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001952 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001953 }
1954
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001955 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1956 // This function is used only for apps and for an app we have exactly one oat file.
1957 DCHECK(!IsBootImage());
1958 DCHECK_EQ(oat_writers_.size(), 1u);
1959 std::vector<std::string> dex_files_canonical_locations;
1960 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1961 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001962 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001963
Vladimir Marko919f5532016-01-20 19:13:01 +00001964 std::vector<std::string> parsed;
1965 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001966 auto kept_it = std::remove_if(parsed.begin(),
1967 parsed.end(),
1968 [dex_files_canonical_locations](const std::string& location) {
1969 return ContainsElement(dex_files_canonical_locations,
1970 DexFile::GetDexCanonicalLocation(location.c_str()));
1971 });
1972 parsed.erase(kept_it, parsed.end());
1973 return parsed;
1974 }
1975
1976 // Opens requested class path files and appends them to opened_dex_files.
1977 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1978 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1979 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1980 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001981 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001982 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1983 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001984 }
1985 }
1986 }
1987
Vladimir Marko49b0f452015-12-10 13:49:19 +00001988 bool PrepareImageClasses() {
1989 // If --image-classes was specified, calculate the full list of classes to include in the image.
1990 if (image_classes_filename_ != nullptr) {
1991 image_classes_ =
1992 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1993 if (image_classes_ == nullptr) {
1994 return false;
1995 }
1996 } else if (IsBootImage()) {
1997 image_classes_.reset(new std::unordered_set<std::string>);
1998 }
1999 return true;
2000 }
2001
2002 bool PrepareCompiledClasses() {
2003 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2004 // image.
2005 if (compiled_classes_filename_ != nullptr) {
2006 compiled_classes_ =
2007 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2008 if (compiled_classes_ == nullptr) {
2009 return false;
2010 }
2011 } else {
2012 compiled_classes_.reset(nullptr); // By default compile everything.
2013 }
2014 return true;
2015 }
2016
2017 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2018 const char* classes_filename,
2019 const char* tag) {
2020 std::unique_ptr<std::unordered_set<std::string>> classes;
2021 std::string error_msg;
2022 if (zip_filename != nullptr) {
2023 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2024 } else {
2025 classes.reset(ReadImageClassesFromFile(classes_filename));
2026 }
2027 if (classes == nullptr) {
2028 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2029 << classes_filename << "': " << error_msg;
2030 }
2031 return classes;
2032 }
2033
2034 bool PrepareCompiledMethods() {
2035 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2036 if (compiled_methods_filename_ != nullptr) {
2037 std::string error_msg;
2038 if (compiled_methods_zip_filename_ != nullptr) {
2039 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2040 compiled_methods_filename_,
2041 nullptr, // No post-processing.
2042 &error_msg));
2043 } else {
2044 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2045 nullptr)); // No post-processing.
2046 }
2047 if (compiled_methods_.get() == nullptr) {
2048 LOG(ERROR) << "Failed to create list of compiled methods from '"
2049 << compiled_methods_filename_ << "': " << error_msg;
2050 return false;
2051 }
2052 } else {
2053 compiled_methods_.reset(nullptr); // By default compile everything.
2054 }
2055 return true;
2056 }
2057
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002058 void PruneNonExistentDexFiles() {
2059 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2060 size_t kept = 0u;
2061 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2062 if (!OS::FileExists(dex_filenames_[i])) {
2063 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2064 } else {
2065 dex_filenames_[kept] = dex_filenames_[i];
2066 dex_locations_[kept] = dex_locations_[i];
2067 ++kept;
2068 }
2069 }
2070 dex_filenames_.resize(kept);
2071 dex_locations_.resize(kept);
2072 }
2073
2074 bool AddDexFileSources() {
2075 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2076 if (zip_fd_ != -1) {
2077 DCHECK_EQ(oat_writers_.size(), 1u);
2078 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2079 return false;
2080 }
2081 } else if (oat_writers_.size() > 1u) {
2082 // Multi-image.
2083 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2084 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2085 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2086 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2087 return false;
2088 }
2089 }
2090 } else {
2091 DCHECK_EQ(oat_writers_.size(), 1u);
2092 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2093 DCHECK_NE(dex_filenames_.size(), 0u);
2094 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2095 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2096 return false;
2097 }
2098 }
2099 }
2100 return true;
2101 }
2102
2103 void CreateOatWriters() {
2104 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2105 elf_writers_.reserve(oat_files_.size());
2106 oat_writers_.reserve(oat_files_.size());
2107 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2108 elf_writers_.emplace_back(
2109 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2110 elf_writers_.back()->Start();
2111 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2112 }
2113 }
2114
Vladimir Marko49b0f452015-12-10 13:49:19 +00002115 void SaveDexInput() {
2116 for (size_t i = 0; i < dex_files_.size(); ++i) {
2117 const DexFile* dex_file = dex_files_[i];
2118 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2119 getpid(), i));
2120 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2121 if (tmp_file.get() == nullptr) {
2122 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2123 << ". Try: adb shell chmod 777 /data/local/tmp";
2124 continue;
2125 }
2126 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2127 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2128 UNUSED(tmp_file->Flush());
2129 UNUSED(tmp_file->Close());
2130 LOG(INFO) << "Wrote input to " << tmp_file_name;
2131 }
2132 }
2133
2134 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2135 RuntimeOptions raw_options;
2136 if (boot_image_filename_.empty()) {
2137 std::string boot_class_path = "-Xbootclasspath:";
2138 boot_class_path += Join(dex_filenames_, ':');
2139 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2140 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2141 boot_class_path_locations += Join(dex_locations_, ':');
2142 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2143 } else {
2144 std::string boot_image_option = "-Ximage:";
2145 boot_image_option += boot_image_filename_;
2146 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2147 }
2148 for (size_t i = 0; i < runtime_args_.size(); i++) {
2149 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2150 }
2151
2152 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2153 raw_options.push_back(
2154 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2155
2156 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2157 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2158 // have been stripped in preopting, anyways).
2159 if (!IsBootImage()) {
2160 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2161 }
2162 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2163 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2164 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002165 // Disable Hspace compaction to save heap size virtual space.
2166 // Only need disable Hspace for OOM becasue background collector is equal to
2167 // foreground collector by default for dex2oat.
2168 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002169
Andreas Gampeace0dc12016-01-20 13:33:13 -08002170 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2171 // force the free-list implementation for large objects.
2172 if (compiler_options_->IsForceDeterminism()) {
2173 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2174 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2175
2176 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2177 // compaction (done above) and ensure that neither foreground nor background collectors
2178 // are concurrent.
2179 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2180
2181 // To make identity hashcode deterministic, set a known seed.
2182 mirror::Object::SetHashCodeSeed(987654321U);
2183 }
2184
Vladimir Marko49b0f452015-12-10 13:49:19 +00002185 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2186 LOG(ERROR) << "Failed to parse runtime options";
2187 return false;
2188 }
2189 return true;
2190 }
2191
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002192 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002193 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2194 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002195 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002196 LOG(ERROR) << "Failed to create runtime";
2197 return false;
2198 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002199 runtime_.reset(Runtime::Current());
2200 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002201 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2202 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002203 if (!runtime_->HasCalleeSaveMethod(type)) {
2204 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002205 }
2206 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002207 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002208
2209 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2210 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002211 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002212
Vladimir Marko307dac92015-10-20 11:20:09 +01002213 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002214
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002215 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2216 // Runtime::Start, give it away now so that we don't starve GC.
2217 Thread* self = Thread::Current();
2218 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002219
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002220 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002221 }
2222
Jeff Haodcdc85b2015-12-04 14:06:18 -08002223 // 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 -08002224 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002225 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002226 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002227 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002228 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002229 image_filenames_.push_back(app_image_file_name_.c_str());
2230 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002231 if (!image_writer_->Write(app_image_fd_,
2232 image_filenames_,
2233 oat_fd_,
2234 oat_filenames_,
2235 oat_location_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002236 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002237 return false;
2238 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002239
Jeff Haodcdc85b2015-12-04 14:06:18 -08002240 // We need the OatDataBegin entries.
2241 std::map<const char*, uintptr_t> oat_data_begins;
2242 for (const char* oat_filename : oat_filenames_) {
2243 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2244 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002245 // Destroy ImageWriter before doing FixupElf.
2246 image_writer_.reset();
2247
Jeff Haodcdc85b2015-12-04 14:06:18 -08002248 for (const char* oat_filename : oat_filenames_) {
2249 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2250 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2251 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2252 if (oat_file.get() == nullptr) {
2253 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2254 return false;
2255 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002256
Jeff Haodcdc85b2015-12-04 14:06:18 -08002257 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002258
Jeff Haodcdc85b2015-12-04 14:06:18 -08002259 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2260 oat_file->Erase();
2261 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2262 return false;
2263 }
2264
2265 if (oat_file->FlushCloseOrErase()) {
2266 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2267 return false;
2268 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002269 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002270 }
2271
2272 return true;
2273 }
2274
2275 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002276 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2277 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002278 std::function<std::string(const char*)> process = DotToDescriptor;
2279 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002280 }
2281
2282 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002283 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002284 const char* zip_filename,
2285 const char* image_classes_filename,
2286 std::string* error_msg) {
2287 std::function<std::string(const char*)> process = DotToDescriptor;
2288 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2289 }
2290
2291 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2292 // the given function.
2293 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2294 const char* input_filename, std::function<std::string(const char*)>* process) {
2295 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2296 if (input_file.get() == nullptr) {
2297 LOG(ERROR) << "Failed to open input file " << input_filename;
2298 return nullptr;
2299 }
2300 std::unique_ptr<std::unordered_set<std::string>> result(
2301 ReadCommentedInputStream(*input_file, process));
2302 input_file->close();
2303 return result.release();
2304 }
2305
2306 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2307 // Post-process each line with the given function.
2308 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002309 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002310 const char* input_filename,
2311 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002312 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002313 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2314 if (zip_archive.get() == nullptr) {
2315 return nullptr;
2316 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002317 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002318 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002319 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002320 zip_filename, error_msg->c_str());
2321 return nullptr;
2322 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002323 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2324 input_filename,
2325 error_msg));
2326 if (input_file.get() == nullptr) {
2327 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002328 zip_filename, error_msg->c_str());
2329 return nullptr;
2330 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002331 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2332 input_file->Size());
2333 std::istringstream input_stream(input_string);
2334 return ReadCommentedInputStream(input_stream, process);
2335 }
2336
2337 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2338 // with the given function.
2339 static std::unordered_set<std::string>* ReadCommentedInputStream(
2340 std::istream& in_stream,
2341 std::function<std::string(const char*)>* process) {
2342 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2343 new std::unordered_set<std::string>);
2344 while (in_stream.good()) {
2345 std::string dot;
2346 std::getline(in_stream, dot);
2347 if (StartsWith(dot, "#") || dot.empty()) {
2348 continue;
2349 }
2350 if (process != nullptr) {
2351 std::string descriptor((*process)(dot.c_str()));
2352 image_classes->insert(descriptor);
2353 } else {
2354 image_classes->insert(dot);
2355 }
2356 }
2357 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002358 }
2359
Mathieu Chartier49285c52014-12-02 15:43:48 -08002360 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002361 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2362 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002363 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002364 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002365 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002366 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002367 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2368 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002369 }
2370
Jeff Haodcdc85b2015-12-04 14:06:18 -08002371 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2372 std::string res(image_filename);
2373 size_t last_slash = res.rfind('/');
2374 if (last_slash == std::string::npos || last_slash == 0) {
2375 return res;
2376 }
2377 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2378 if (penultimate_slash == std::string::npos) {
2379 return res;
2380 }
2381 // Check that the string in-between is the expected one.
2382 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2383 GetInstructionSetString(isa)) {
2384 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2385 return res;
2386 }
2387 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2388 }
2389
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002390 std::unique_ptr<CompilerOptions> compiler_options_;
2391 Compiler::Kind compiler_kind_;
2392
2393 InstructionSet instruction_set_;
2394 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2395
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002396 uint32_t image_file_location_oat_checksum_;
2397 uintptr_t image_file_location_oat_data_begin_;
2398 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002399 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2400
Vladimir Marko307dac92015-10-20 11:20:09 +01002401 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002402
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002403 DexFileToMethodInlinerMap method_inliner_map_;
2404 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2405
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002406 std::unique_ptr<Runtime> runtime_;
2407
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002408 // Ownership for the class path files.
2409 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2410
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 size_t thread_count_;
2412 uint64_t start_ns_;
2413 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002414 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002415 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002416 std::vector<const char*> oat_filenames_;
2417 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002418 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002419 std::vector<const char*> dex_filenames_;
2420 std::vector<const char*> dex_locations_;
2421 int zip_fd_;
2422 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002423 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002424 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002425 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002426 uintptr_t image_base_;
2427 const char* image_classes_zip_filename_;
2428 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002429 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002430 const char* compiled_classes_zip_filename_;
2431 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002432 const char* compiled_methods_zip_filename_;
2433 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002434 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2435 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002436 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002437 bool app_image_;
2438 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002439 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002440 bool is_host_;
2441 std::string android_root_;
2442 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002443 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002444 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002445 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002446
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002447 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2448 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2449 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002450 std::unique_ptr<ImageWriter> image_writer_;
2451 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002452
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002453 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2454 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2455
Vladimir Marko47496c22016-01-27 16:15:08 +00002456 std::vector<const DexFile*> no_inline_from_dex_files_;
2457
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002458 std::vector<std::string> verbose_methods_;
2459 bool dump_stats_;
2460 bool dump_passes_;
2461 bool dump_timing_;
2462 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002463 std::string swap_file_name_;
2464 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002465 std::string app_image_file_name_;
2466 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002467 std::vector<std::string> profile_files_;
2468 std::vector<std::string> reference_profile_files_;
Calin Juravle877fd962016-01-05 14:29:29 +00002469 std::vector<uint32_t> profile_files_fd_;
2470 std::vector<uint32_t> reference_profile_files_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002471 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002472 TimingLogger* timings_;
2473 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002474 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2475 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2476
2477 // Backing storage.
2478 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002479
Andreas Gampeace0dc12016-01-20 13:33:13 -08002480 // See CompilerOptions.force_determinism_.
2481 bool force_determinism_;
2482
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002483 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2484};
2485
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002486static void b13564922() {
2487#if defined(__linux__) && defined(__arm__)
2488 int major, minor;
2489 struct utsname uts;
2490 if (uname(&uts) != -1 &&
2491 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2492 ((major < 3) || ((major == 3) && (minor < 4)))) {
2493 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2494 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2495 int old_personality = personality(0xffffffff);
2496 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2497 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2498 if (new_personality == -1) {
2499 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2500 }
2501 }
2502 }
2503#endif
2504}
2505
Andreas Gampe10e477d2014-11-19 12:57:42 -08002506static int CompileImage(Dex2Oat& dex2oat) {
2507 dex2oat.Compile();
2508
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002509 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002510 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002511 return EXIT_FAILURE;
2512 }
2513
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002514 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2515 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2516 // image writer will require this fd to generate the image.
2517 if (dex2oat.ShouldKeepOatFileOpen()) {
2518 if (!dex2oat.FlushOatFiles()) {
2519 return EXIT_FAILURE;
2520 }
2521 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002522 return EXIT_FAILURE;
2523 }
2524
Jeff Haodcdc85b2015-12-04 14:06:18 -08002525 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002526 if (!dex2oat.HandleImage()) {
2527 return EXIT_FAILURE;
2528 }
2529
2530 // When given --host, finish early without stripping.
2531 if (dex2oat.IsHost()) {
2532 dex2oat.DumpTiming();
2533 return EXIT_SUCCESS;
2534 }
2535
Jeff Haodcdc85b2015-12-04 14:06:18 -08002536 // Copy stripped to unstripped location, if necessary.
2537 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002538 return EXIT_FAILURE;
2539 }
2540
Jeff Haodcdc85b2015-12-04 14:06:18 -08002541 // FlushClose again, as stripping might have re-opened the oat files.
2542 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002543 return EXIT_FAILURE;
2544 }
2545
2546 dex2oat.DumpTiming();
2547 return EXIT_SUCCESS;
2548}
2549
2550static int CompileApp(Dex2Oat& dex2oat) {
2551 dex2oat.Compile();
2552
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002553 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002554 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002555 return EXIT_FAILURE;
2556 }
2557
Jeff Haodcdc85b2015-12-04 14:06:18 -08002558 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002559 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002560
2561 // When given --host, finish early without stripping.
2562 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002563 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002564 return EXIT_FAILURE;
2565 }
2566
2567 dex2oat.DumpTiming();
2568 return EXIT_SUCCESS;
2569 }
2570
Jeff Haodcdc85b2015-12-04 14:06:18 -08002571 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2572 // stripped versions. If this is given, we expect to be able to open writable files by name.
2573 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002574 return EXIT_FAILURE;
2575 }
2576
Jeff Haodcdc85b2015-12-04 14:06:18 -08002577 // Flush and close the files.
2578 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002579 return EXIT_FAILURE;
2580 }
2581
2582 dex2oat.DumpTiming();
2583 return EXIT_SUCCESS;
2584}
2585
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002586static int dex2oat(int argc, char** argv) {
2587 b13564922();
2588
2589 TimingLogger timings("compiler", false, false);
2590
2591 Dex2Oat dex2oat(&timings);
2592
2593 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2594 dex2oat.ParseArgs(argc, argv);
2595
Calin Juravle998c2162015-12-21 15:39:33 +02002596 // Process profile information and assess if we need to do a profile guided compilation.
2597 // This operation involves I/O.
2598 if (dex2oat.UseProfileGuidedCompilation()) {
2599 if (dex2oat.ProcessProfiles()) {
2600 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2601 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2602 return EXIT_SUCCESS;
2603 }
2604 } else {
2605 LOG(WARNING) << "Failed to process profile files";
2606 return EXIT_FAILURE;
2607 }
2608 }
2609
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002610 // Check early that the result of compilation can be written
2611 if (!dex2oat.OpenFile()) {
2612 return EXIT_FAILURE;
2613 }
2614
Andreas Gampe046c7062015-05-18 23:22:54 -07002615 // Print the complete line when any of the following is true:
2616 // 1) Debug build
2617 // 2) Compiling an image
2618 // 3) Compiling with --host
2619 // 4) Compiling on the host (not a target build)
2620 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002621 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002622 LOG(INFO) << CommandLine();
2623 } else {
2624 LOG(INFO) << StrippedCommandLine();
2625 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002626
2627 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002628 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002629 return EXIT_FAILURE;
2630 }
2631
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002632 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002633 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002634 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002635 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002636 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002637 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002638
2639 dex2oat.Shutdown();
2640 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002641}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002642} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002643
2644int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002645 int result = art::dex2oat(argc, argv);
2646 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2647 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2648 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002649 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002650 exit(result);
2651 }
2652 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002653}