blob: b1f71cee3d7dfc9542454fa4489ce901bf63ec60 [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000053#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick_compiler_callbacks.h"
55#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000058#include "dwarf/method_debug_info.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(),
1560 nullptr,
1561 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 &dex_file_oat_filename_map_,
1567 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001568 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001569 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001570 }
1571
Jeff Hao436183f2016-01-12 16:36:50 -08001572 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001573 // ensure the references between the two are correct.
1574 //
1575 // Currently we have a memory layout that looks something like this:
1576 //
1577 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001578 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001579 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001580 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001581 // +--------------+
1582 // | alloc spaces |
1583 // +--------------+
1584 //
Jeff Hao436183f2016-01-12 16:36:50 -08001585 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586 //
Jeff Hao436183f2016-01-12 16:36:50 -08001587 // 1. The images are expected to be loaded at an absolute address and
1588 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589 //
Jeff Hao436183f2016-01-12 16:36:50 -08001590 // 2. There are absolute pointers from Methods in the images to their
1591 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001592 //
Jeff Hao436183f2016-01-12 16:36:50 -08001593 // 3. There are absolute pointers from the code in the oat files to Methods
1594 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001595 //
Jeff Hao436183f2016-01-12 16:36:50 -08001596 // 4. There are absolute pointers from code in the oat files to other code
1597 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001598 //
1599 // To get this all correct, we go through several steps.
1600 //
Jeff Hao436183f2016-01-12 16:36:50 -08001601 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001602 // the oat data size and code size. During this stage, we also set
1603 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001604 //
Jeff Hao436183f2016-01-12 16:36:50 -08001605 // 2. We prepare offsets for the objects in the images and calculate
1606 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001607 //
Jeff Hao436183f2016-01-12 16:36:50 -08001608 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001609 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001610 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001611 // can prepare the ELF headers and we then know the ELF memory segment
1612 // layout and we can now resolve all references. The compiler provides
1613 // LinkerPatch information in each CompiledMethod and we resolve these,
1614 // using the layout information and image object locations provided by
1615 // image writer, as we're writing the method code.
1616 //
Jeff Hao436183f2016-01-12 16:36:50 -08001617 // 4. We create the image files. They need to know where the oat files
1618 // will be loaded after itself. Originally oat files were simply
1619 // memory mapped so we could predict where their contents were based
1620 // on the file size. Now that they are ELF files, we need to inspect
1621 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001622 // where the oat header is located within.
1623 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001624 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001625 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001626 // load the .so at the desired location at runtime by offsetting the
1627 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001628 // TODO: Do this in step 3. We already know the layout there.
1629 //
1630 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1631 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1634 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001635 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1636 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001638 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1639
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001640 // Sync the data to the file, in case we did dex2dex transformations.
1641 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1642 if (!map->Sync()) {
1643 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1644 return false;
1645 }
1646 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001647
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001648 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001650 gc::Heap* const heap = Runtime::Current()->GetHeap();
1651 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001652 image_base_ = std::max(image_base_, RoundUp(
1653 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1654 kPageSize));
1655 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001656 // The non moving space is right after the oat file. Put the preferred app image location
1657 // right after the non moving space so that we ideally get a continuous immune region for
1658 // the GC.
1659 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1660 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001661 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1662 }
1663
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001664 image_writer_.reset(new ImageWriter(*driver_,
1665 image_base_,
1666 compiler_options_->GetCompilePic(),
1667 IsAppImage(),
1668 image_storage_mode_,
1669 oat_filenames_,
1670 dex_file_oat_filename_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001672 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001673 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1674 if (!image_writer_->PrepareImageAddressSpace()) {
1675 LOG(ERROR) << "Failed to prepare image address space.";
1676 return false;
1677 }
1678 }
1679
1680 {
1681 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001683 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001684 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1685 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001686
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001687 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1688 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files);
Vladimir Marko10c13562015-11-25 14:33:36 +00001689
David Srbecky0c4572e2016-01-22 19:19:25 +00001690 // We need to mirror the layout of the ELF file in the compressed debug-info.
1691 // Therefore we need to propagate the sizes of at least those sections.
1692 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1693 size_t text_size = oat_writer->GetSize() - rodata_size;
1694 elf_writer->PrepareDebugInfo(rodata_size, text_size, oat_writer->GetMethodDebugInfo());
1695
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001696 OutputStream*& rodata = rodata_[i];
1697 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001698 if (!oat_writer->WriteRodata(rodata)) {
1699 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1700 return false;
1701 }
1702 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001703 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001704
Jeff Haodcdc85b2015-12-04 14:06:18 -08001705 OutputStream* text = elf_writer->StartText();
1706 if (!oat_writer->WriteCode(text)) {
1707 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1708 return false;
1709 }
1710 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001711
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001712 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1713 image_file_location_oat_checksum_,
1714 image_file_location_oat_data_begin_,
1715 image_patch_delta_)) {
1716 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1717 return false;
1718 }
1719
Jeff Haodcdc85b2015-12-04 14:06:18 -08001720 elf_writer->SetBssSize(oat_writer->GetBssSize());
1721 elf_writer->WriteDynamicSection();
1722 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1723 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001724
Jeff Haodcdc85b2015-12-04 14:06:18 -08001725 if (!elf_writer->End()) {
1726 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1727 return false;
1728 }
1729
1730 // Flush the oat file.
1731 if (oat_files_[i] != nullptr) {
1732 if (oat_files_[i]->Flush() != 0) {
1733 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1734 oat_files_[i]->Erase();
1735 return false;
1736 }
1737 }
1738
1739 if (IsImage()) {
1740 // Update oat estimates.
Vladimir Markod8904a52016-01-29 16:27:27 +00001741 DCHECK(image_writer_ != nullptr);
1742 DCHECK_LT(i, oat_filenames_.size());
1743
1744 image_writer_->UpdateOatFile(oat_file.get(), oat_filenames_[i]);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 }
1746
1747 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001748
1749 oat_writer.reset();
1750 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001751 }
1752 }
1753
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001754 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001755 }
1756
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001757 // If we are compiling an image, invoke the image creation routine. Else just skip.
1758 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001759 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001760 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1761 if (!CreateImageFile()) {
1762 return false;
1763 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001764 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001765 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001766 return true;
1767 }
1768
Jeff Haodcdc85b2015-12-04 14:06:18 -08001769 // Create a copy from stripped to unstripped.
1770 bool CopyStrippedToUnstripped() {
1771 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1772 // If we don't want to strip in place, copy from stripped location to unstripped location.
1773 // We need to strip after image creation because FixupElf needs to use .strtab.
1774 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1775 // If the oat file is still open, flush it.
1776 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1777 if (!FlushCloseOatFile(i)) {
1778 return false;
1779 }
1780 }
1781
1782 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1783 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1784 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1785 size_t buffer_size = 8192;
1786 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1787 while (true) {
1788 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1789 if (bytes_read <= 0) {
1790 break;
1791 }
1792 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1793 CHECK(write_ok);
1794 }
1795 if (out->FlushCloseOrErase() != 0) {
1796 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1797 return false;
1798 }
1799 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1800 }
1801 }
1802 return true;
1803 }
1804
1805 bool FlushOatFiles() {
1806 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1807 for (size_t i = 0; i < oat_files_.size(); ++i) {
1808 if (oat_files_[i].get() != nullptr) {
1809 if (oat_files_[i]->Flush() != 0) {
1810 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1811 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001812 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001813 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001814 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001815 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001816 return true;
1817 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001818
Jeff Haodcdc85b2015-12-04 14:06:18 -08001819 bool FlushCloseOatFile(size_t i) {
1820 if (oat_files_[i].get() != nullptr) {
1821 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001822 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001824 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001825 }
1826 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001827 return true;
1828 }
1829
Jeff Haodcdc85b2015-12-04 14:06:18 -08001830 bool FlushCloseOatFiles() {
1831 bool result = true;
1832 for (size_t i = 0; i < oat_files_.size(); ++i) {
1833 result &= FlushCloseOatFile(i);
1834 }
1835 return result;
1836 }
1837
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001838 void DumpTiming() {
1839 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1840 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1841 }
1842 if (dump_passes_) {
1843 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1844 }
1845 }
1846
1847 CompilerOptions* GetCompilerOptions() const {
1848 return compiler_options_.get();
1849 }
1850
Andreas Gampe10e477d2014-11-19 12:57:42 -08001851 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001852 return IsAppImage() || IsBootImage();
1853 }
1854
1855 bool IsAppImage() const {
1856 return app_image_;
1857 }
1858
1859 bool IsBootImage() const {
1860 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001861 }
1862
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001863 bool IsHost() const {
1864 return is_host_;
1865 }
1866
Calin Juravle998c2162015-12-21 15:39:33 +02001867 bool UseProfileGuidedCompilation() const {
Calin Juravle877fd962016-01-05 14:29:29 +00001868 return !profile_files_.empty() || !profile_files_fd_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02001869 }
1870
1871 bool ProcessProfiles() {
1872 DCHECK(UseProfileGuidedCompilation());
1873 ProfileCompilationInfo* info = nullptr;
Calin Juravle877fd962016-01-05 14:29:29 +00001874 bool result = false;
1875 if (profile_files_.empty()) {
1876 DCHECK(!profile_files_fd_.empty());
1877 result = ProfileAssistant::ProcessProfiles(
1878 profile_files_fd_, reference_profile_files_fd_, &info);
1879 CloseAllFds(profile_files_fd_, "profile_files_fd_");
1880 CloseAllFds(reference_profile_files_fd_, "reference_profile_files_fd_");
1881 } else {
1882 result = ProfileAssistant::ProcessProfiles(
1883 profile_files_, reference_profile_files_, &info);
Calin Juravle998c2162015-12-21 15:39:33 +02001884 }
Calin Juravle877fd962016-01-05 14:29:29 +00001885
1886 profile_compilation_info_.reset(info);
1887
1888 return result;
Calin Juravle998c2162015-12-21 15:39:33 +02001889 }
1890
1891 bool ShouldCompileBasedOnProfiles() const {
1892 DCHECK(UseProfileGuidedCompilation());
1893 // If we are given profiles, compile only if we have new information.
1894 return profile_compilation_info_ != nullptr;
1895 }
1896
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001897 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001898 template <typename T>
1899 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1900 std::vector<T*> result;
1901 result.reserve(src.size());
1902 for (const std::unique_ptr<T>& t : src) {
1903 result.push_back(t.get());
1904 }
1905 return result;
1906 }
1907
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001908 std::string GetMultiImageBootClassPath() {
1909 DCHECK(IsBootImage());
1910 DCHECK_GT(oat_filenames_.size(), 1u);
1911 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1912 // too, but need to strip all path components (they will be re-established when loading).
1913 std::ostringstream bootcp_oss;
1914 bool first_bootcp = true;
1915 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1916 if (!first_bootcp) {
1917 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001918 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001919
1920 std::string dex_loc = dex_locations_[i];
1921 std::string image_filename = image_filenames_[i];
1922
1923 // Use the dex_loc path, but the image_filename name (without path elements).
1924 size_t dex_last_slash = dex_loc.rfind('/');
1925
1926 // npos is max(size_t). That makes this a bit ugly.
1927 size_t image_last_slash = image_filename.rfind('/');
1928 size_t image_last_at = image_filename.rfind('@');
1929 size_t image_last_sep = (image_last_slash == std::string::npos)
1930 ? image_last_at
1931 : (image_last_at == std::string::npos)
1932 ? std::string::npos
1933 : std::max(image_last_slash, image_last_at);
1934 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1935
1936 if (dex_last_slash == std::string::npos) {
1937 dex_loc = image_filename.substr(image_last_sep + 1);
1938 } else {
1939 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1940 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001941 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001942
1943 // Image filenames already end with .art, no need to replace.
1944
1945 bootcp_oss << dex_loc;
1946 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001947 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001948 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001949 }
1950
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001951 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1952 // This function is used only for apps and for an app we have exactly one oat file.
1953 DCHECK(!IsBootImage());
1954 DCHECK_EQ(oat_writers_.size(), 1u);
1955 std::vector<std::string> dex_files_canonical_locations;
1956 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1957 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001958 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001959
Vladimir Marko919f5532016-01-20 19:13:01 +00001960 std::vector<std::string> parsed;
1961 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001962 auto kept_it = std::remove_if(parsed.begin(),
1963 parsed.end(),
1964 [dex_files_canonical_locations](const std::string& location) {
1965 return ContainsElement(dex_files_canonical_locations,
1966 DexFile::GetDexCanonicalLocation(location.c_str()));
1967 });
1968 parsed.erase(kept_it, parsed.end());
1969 return parsed;
1970 }
1971
1972 // Opens requested class path files and appends them to opened_dex_files.
1973 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1974 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1975 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1976 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001977 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001978 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1979 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001980 }
1981 }
1982 }
1983
Vladimir Marko49b0f452015-12-10 13:49:19 +00001984 bool PrepareImageClasses() {
1985 // If --image-classes was specified, calculate the full list of classes to include in the image.
1986 if (image_classes_filename_ != nullptr) {
1987 image_classes_ =
1988 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1989 if (image_classes_ == nullptr) {
1990 return false;
1991 }
1992 } else if (IsBootImage()) {
1993 image_classes_.reset(new std::unordered_set<std::string>);
1994 }
1995 return true;
1996 }
1997
1998 bool PrepareCompiledClasses() {
1999 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2000 // image.
2001 if (compiled_classes_filename_ != nullptr) {
2002 compiled_classes_ =
2003 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2004 if (compiled_classes_ == nullptr) {
2005 return false;
2006 }
2007 } else {
2008 compiled_classes_.reset(nullptr); // By default compile everything.
2009 }
2010 return true;
2011 }
2012
2013 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2014 const char* classes_filename,
2015 const char* tag) {
2016 std::unique_ptr<std::unordered_set<std::string>> classes;
2017 std::string error_msg;
2018 if (zip_filename != nullptr) {
2019 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2020 } else {
2021 classes.reset(ReadImageClassesFromFile(classes_filename));
2022 }
2023 if (classes == nullptr) {
2024 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2025 << classes_filename << "': " << error_msg;
2026 }
2027 return classes;
2028 }
2029
2030 bool PrepareCompiledMethods() {
2031 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2032 if (compiled_methods_filename_ != nullptr) {
2033 std::string error_msg;
2034 if (compiled_methods_zip_filename_ != nullptr) {
2035 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2036 compiled_methods_filename_,
2037 nullptr, // No post-processing.
2038 &error_msg));
2039 } else {
2040 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2041 nullptr)); // No post-processing.
2042 }
2043 if (compiled_methods_.get() == nullptr) {
2044 LOG(ERROR) << "Failed to create list of compiled methods from '"
2045 << compiled_methods_filename_ << "': " << error_msg;
2046 return false;
2047 }
2048 } else {
2049 compiled_methods_.reset(nullptr); // By default compile everything.
2050 }
2051 return true;
2052 }
2053
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002054 void PruneNonExistentDexFiles() {
2055 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2056 size_t kept = 0u;
2057 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2058 if (!OS::FileExists(dex_filenames_[i])) {
2059 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2060 } else {
2061 dex_filenames_[kept] = dex_filenames_[i];
2062 dex_locations_[kept] = dex_locations_[i];
2063 ++kept;
2064 }
2065 }
2066 dex_filenames_.resize(kept);
2067 dex_locations_.resize(kept);
2068 }
2069
2070 bool AddDexFileSources() {
2071 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2072 if (zip_fd_ != -1) {
2073 DCHECK_EQ(oat_writers_.size(), 1u);
2074 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2075 return false;
2076 }
2077 } else if (oat_writers_.size() > 1u) {
2078 // Multi-image.
2079 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2080 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2081 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2082 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2083 return false;
2084 }
2085 }
2086 } else {
2087 DCHECK_EQ(oat_writers_.size(), 1u);
2088 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2089 DCHECK_NE(dex_filenames_.size(), 0u);
2090 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2091 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2092 return false;
2093 }
2094 }
2095 }
2096 return true;
2097 }
2098
2099 void CreateOatWriters() {
2100 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2101 elf_writers_.reserve(oat_files_.size());
2102 oat_writers_.reserve(oat_files_.size());
2103 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2104 elf_writers_.emplace_back(
2105 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2106 elf_writers_.back()->Start();
2107 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2108 }
2109 }
2110
Vladimir Marko49b0f452015-12-10 13:49:19 +00002111 void SaveDexInput() {
2112 for (size_t i = 0; i < dex_files_.size(); ++i) {
2113 const DexFile* dex_file = dex_files_[i];
2114 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2115 getpid(), i));
2116 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2117 if (tmp_file.get() == nullptr) {
2118 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2119 << ". Try: adb shell chmod 777 /data/local/tmp";
2120 continue;
2121 }
2122 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2123 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2124 UNUSED(tmp_file->Flush());
2125 UNUSED(tmp_file->Close());
2126 LOG(INFO) << "Wrote input to " << tmp_file_name;
2127 }
2128 }
2129
2130 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2131 RuntimeOptions raw_options;
2132 if (boot_image_filename_.empty()) {
2133 std::string boot_class_path = "-Xbootclasspath:";
2134 boot_class_path += Join(dex_filenames_, ':');
2135 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2136 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2137 boot_class_path_locations += Join(dex_locations_, ':');
2138 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2139 } else {
2140 std::string boot_image_option = "-Ximage:";
2141 boot_image_option += boot_image_filename_;
2142 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2143 }
2144 for (size_t i = 0; i < runtime_args_.size(); i++) {
2145 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2146 }
2147
2148 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2149 raw_options.push_back(
2150 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2151
2152 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2153 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2154 // have been stripped in preopting, anyways).
2155 if (!IsBootImage()) {
2156 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2157 }
2158 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2159 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2160 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002161 // Disable Hspace compaction to save heap size virtual space.
2162 // Only need disable Hspace for OOM becasue background collector is equal to
2163 // foreground collector by default for dex2oat.
2164 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002165
Andreas Gampeace0dc12016-01-20 13:33:13 -08002166 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2167 // force the free-list implementation for large objects.
2168 if (compiler_options_->IsForceDeterminism()) {
2169 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2170 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2171
2172 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2173 // compaction (done above) and ensure that neither foreground nor background collectors
2174 // are concurrent.
2175 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2176
2177 // To make identity hashcode deterministic, set a known seed.
2178 mirror::Object::SetHashCodeSeed(987654321U);
2179 }
2180
Vladimir Marko49b0f452015-12-10 13:49:19 +00002181 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2182 LOG(ERROR) << "Failed to parse runtime options";
2183 return false;
2184 }
2185 return true;
2186 }
2187
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002188 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2190 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002191 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002192 LOG(ERROR) << "Failed to create runtime";
2193 return false;
2194 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002195 runtime_.reset(Runtime::Current());
2196 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002197 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2198 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002199 if (!runtime_->HasCalleeSaveMethod(type)) {
2200 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002201 }
2202 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002203 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002204
2205 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2206 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002207 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002208
Vladimir Marko307dac92015-10-20 11:20:09 +01002209 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002210
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002211 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2212 // Runtime::Start, give it away now so that we don't starve GC.
2213 Thread* self = Thread::Current();
2214 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002215
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002216 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002217 }
2218
Jeff Haodcdc85b2015-12-04 14:06:18 -08002219 // 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 -08002220 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002221 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002222 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002223 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002224 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002225 image_filenames_.push_back(app_image_file_name_.c_str());
2226 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002227 if (!image_writer_->Write(app_image_fd_,
2228 image_filenames_,
2229 oat_fd_,
2230 oat_filenames_,
2231 oat_location_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002232 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002233 return false;
2234 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002235
Jeff Haodcdc85b2015-12-04 14:06:18 -08002236 // We need the OatDataBegin entries.
2237 std::map<const char*, uintptr_t> oat_data_begins;
2238 for (const char* oat_filename : oat_filenames_) {
2239 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2240 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002241 // Destroy ImageWriter before doing FixupElf.
2242 image_writer_.reset();
2243
Jeff Haodcdc85b2015-12-04 14:06:18 -08002244 for (const char* oat_filename : oat_filenames_) {
2245 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2246 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2247 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2248 if (oat_file.get() == nullptr) {
2249 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2250 return false;
2251 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002252
Jeff Haodcdc85b2015-12-04 14:06:18 -08002253 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002254
Jeff Haodcdc85b2015-12-04 14:06:18 -08002255 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2256 oat_file->Erase();
2257 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2258 return false;
2259 }
2260
2261 if (oat_file->FlushCloseOrErase()) {
2262 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2263 return false;
2264 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002265 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002266 }
2267
2268 return true;
2269 }
2270
2271 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002272 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2273 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002274 std::function<std::string(const char*)> process = DotToDescriptor;
2275 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002276 }
2277
2278 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002279 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002280 const char* zip_filename,
2281 const char* image_classes_filename,
2282 std::string* error_msg) {
2283 std::function<std::string(const char*)> process = DotToDescriptor;
2284 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2285 }
2286
2287 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2288 // the given function.
2289 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2290 const char* input_filename, std::function<std::string(const char*)>* process) {
2291 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2292 if (input_file.get() == nullptr) {
2293 LOG(ERROR) << "Failed to open input file " << input_filename;
2294 return nullptr;
2295 }
2296 std::unique_ptr<std::unordered_set<std::string>> result(
2297 ReadCommentedInputStream(*input_file, process));
2298 input_file->close();
2299 return result.release();
2300 }
2301
2302 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2303 // Post-process each line with the given function.
2304 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002305 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002306 const char* input_filename,
2307 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002308 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002309 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2310 if (zip_archive.get() == nullptr) {
2311 return nullptr;
2312 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002313 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002314 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002315 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002316 zip_filename, error_msg->c_str());
2317 return nullptr;
2318 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002319 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2320 input_filename,
2321 error_msg));
2322 if (input_file.get() == nullptr) {
2323 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002324 zip_filename, error_msg->c_str());
2325 return nullptr;
2326 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002327 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2328 input_file->Size());
2329 std::istringstream input_stream(input_string);
2330 return ReadCommentedInputStream(input_stream, process);
2331 }
2332
2333 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2334 // with the given function.
2335 static std::unordered_set<std::string>* ReadCommentedInputStream(
2336 std::istream& in_stream,
2337 std::function<std::string(const char*)>* process) {
2338 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2339 new std::unordered_set<std::string>);
2340 while (in_stream.good()) {
2341 std::string dot;
2342 std::getline(in_stream, dot);
2343 if (StartsWith(dot, "#") || dot.empty()) {
2344 continue;
2345 }
2346 if (process != nullptr) {
2347 std::string descriptor((*process)(dot.c_str()));
2348 image_classes->insert(descriptor);
2349 } else {
2350 image_classes->insert(dot);
2351 }
2352 }
2353 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002354 }
2355
Mathieu Chartier49285c52014-12-02 15:43:48 -08002356 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002357 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2358 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002359 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002360 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002361 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002362 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002363 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2364 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002365 }
2366
Jeff Haodcdc85b2015-12-04 14:06:18 -08002367 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2368 std::string res(image_filename);
2369 size_t last_slash = res.rfind('/');
2370 if (last_slash == std::string::npos || last_slash == 0) {
2371 return res;
2372 }
2373 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2374 if (penultimate_slash == std::string::npos) {
2375 return res;
2376 }
2377 // Check that the string in-between is the expected one.
2378 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2379 GetInstructionSetString(isa)) {
2380 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2381 return res;
2382 }
2383 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2384 }
2385
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002386 std::unique_ptr<CompilerOptions> compiler_options_;
2387 Compiler::Kind compiler_kind_;
2388
2389 InstructionSet instruction_set_;
2390 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2391
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002392 uint32_t image_file_location_oat_checksum_;
2393 uintptr_t image_file_location_oat_data_begin_;
2394 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002395 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2396
Vladimir Marko307dac92015-10-20 11:20:09 +01002397 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002398
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002399 DexFileToMethodInlinerMap method_inliner_map_;
2400 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2401
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402 std::unique_ptr<Runtime> runtime_;
2403
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002404 // Ownership for the class path files.
2405 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2406
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002407 size_t thread_count_;
2408 uint64_t start_ns_;
2409 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002410 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002412 std::vector<const char*> oat_filenames_;
2413 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002414 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002415 std::vector<const char*> dex_filenames_;
2416 std::vector<const char*> dex_locations_;
2417 int zip_fd_;
2418 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002419 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002420 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002421 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002422 uintptr_t image_base_;
2423 const char* image_classes_zip_filename_;
2424 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002425 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002426 const char* compiled_classes_zip_filename_;
2427 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002428 const char* compiled_methods_zip_filename_;
2429 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002430 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2431 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002432 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002433 bool app_image_;
2434 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002435 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002436 bool is_host_;
2437 std::string android_root_;
2438 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002439 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002440 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002441 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002442
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002443 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2444 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2445 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002446 std::unique_ptr<ImageWriter> image_writer_;
2447 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002448
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002449 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2450 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2451
Vladimir Marko47496c22016-01-27 16:15:08 +00002452 std::vector<const DexFile*> no_inline_from_dex_files_;
2453
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002454 std::vector<std::string> verbose_methods_;
2455 bool dump_stats_;
2456 bool dump_passes_;
2457 bool dump_timing_;
2458 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002459 std::string swap_file_name_;
2460 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002461 std::string app_image_file_name_;
2462 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002463 std::vector<std::string> profile_files_;
2464 std::vector<std::string> reference_profile_files_;
Calin Juravle877fd962016-01-05 14:29:29 +00002465 std::vector<uint32_t> profile_files_fd_;
2466 std::vector<uint32_t> reference_profile_files_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002467 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002468 TimingLogger* timings_;
2469 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002470 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2471 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2472
2473 // Backing storage.
2474 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002475
Andreas Gampeace0dc12016-01-20 13:33:13 -08002476 // See CompilerOptions.force_determinism_.
2477 bool force_determinism_;
2478
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002479 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2480};
2481
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002482static void b13564922() {
2483#if defined(__linux__) && defined(__arm__)
2484 int major, minor;
2485 struct utsname uts;
2486 if (uname(&uts) != -1 &&
2487 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2488 ((major < 3) || ((major == 3) && (minor < 4)))) {
2489 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2490 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2491 int old_personality = personality(0xffffffff);
2492 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2493 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2494 if (new_personality == -1) {
2495 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2496 }
2497 }
2498 }
2499#endif
2500}
2501
Andreas Gampe10e477d2014-11-19 12:57:42 -08002502static int CompileImage(Dex2Oat& dex2oat) {
2503 dex2oat.Compile();
2504
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002505 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002506 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002507 return EXIT_FAILURE;
2508 }
2509
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002510 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2511 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2512 // image writer will require this fd to generate the image.
2513 if (dex2oat.ShouldKeepOatFileOpen()) {
2514 if (!dex2oat.FlushOatFiles()) {
2515 return EXIT_FAILURE;
2516 }
2517 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002518 return EXIT_FAILURE;
2519 }
2520
Jeff Haodcdc85b2015-12-04 14:06:18 -08002521 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002522 if (!dex2oat.HandleImage()) {
2523 return EXIT_FAILURE;
2524 }
2525
2526 // When given --host, finish early without stripping.
2527 if (dex2oat.IsHost()) {
2528 dex2oat.DumpTiming();
2529 return EXIT_SUCCESS;
2530 }
2531
Jeff Haodcdc85b2015-12-04 14:06:18 -08002532 // Copy stripped to unstripped location, if necessary.
2533 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002534 return EXIT_FAILURE;
2535 }
2536
Jeff Haodcdc85b2015-12-04 14:06:18 -08002537 // FlushClose again, as stripping might have re-opened the oat files.
2538 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002539 return EXIT_FAILURE;
2540 }
2541
2542 dex2oat.DumpTiming();
2543 return EXIT_SUCCESS;
2544}
2545
2546static int CompileApp(Dex2Oat& dex2oat) {
2547 dex2oat.Compile();
2548
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002549 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002550 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002551 return EXIT_FAILURE;
2552 }
2553
Jeff Haodcdc85b2015-12-04 14:06:18 -08002554 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002555 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002556
2557 // When given --host, finish early without stripping.
2558 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002559 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002560 return EXIT_FAILURE;
2561 }
2562
2563 dex2oat.DumpTiming();
2564 return EXIT_SUCCESS;
2565 }
2566
Jeff Haodcdc85b2015-12-04 14:06:18 -08002567 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2568 // stripped versions. If this is given, we expect to be able to open writable files by name.
2569 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002570 return EXIT_FAILURE;
2571 }
2572
Jeff Haodcdc85b2015-12-04 14:06:18 -08002573 // Flush and close the files.
2574 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002575 return EXIT_FAILURE;
2576 }
2577
2578 dex2oat.DumpTiming();
2579 return EXIT_SUCCESS;
2580}
2581
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002582static int dex2oat(int argc, char** argv) {
2583 b13564922();
2584
2585 TimingLogger timings("compiler", false, false);
2586
2587 Dex2Oat dex2oat(&timings);
2588
2589 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2590 dex2oat.ParseArgs(argc, argv);
2591
Calin Juravle998c2162015-12-21 15:39:33 +02002592 // Process profile information and assess if we need to do a profile guided compilation.
2593 // This operation involves I/O.
2594 if (dex2oat.UseProfileGuidedCompilation()) {
2595 if (dex2oat.ProcessProfiles()) {
2596 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2597 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2598 return EXIT_SUCCESS;
2599 }
2600 } else {
2601 LOG(WARNING) << "Failed to process profile files";
2602 return EXIT_FAILURE;
2603 }
2604 }
2605
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002606 // Check early that the result of compilation can be written
2607 if (!dex2oat.OpenFile()) {
2608 return EXIT_FAILURE;
2609 }
2610
Andreas Gampe046c7062015-05-18 23:22:54 -07002611 // Print the complete line when any of the following is true:
2612 // 1) Debug build
2613 // 2) Compiling an image
2614 // 3) Compiling with --host
2615 // 4) Compiling on the host (not a target build)
2616 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002617 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002618 LOG(INFO) << CommandLine();
2619 } else {
2620 LOG(INFO) << StrippedCommandLine();
2621 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002622
2623 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002624 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002625 return EXIT_FAILURE;
2626 }
2627
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002628 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002629 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002630 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002631 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002632 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002633 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002634
2635 dex2oat.Shutdown();
2636 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002637}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002638} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002639
2640int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002641 int result = art::dex2oat(argc, argv);
2642 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2643 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2644 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002645 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002646 exit(result);
2647 }
2648 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002649}