blob: b3e3ba68a0c5b7e3db9e99c51ea0477a7dda9d04 [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
129 // This should leave any dex-file and oat-file options, describing what we compiled.
130
131 // However, we prefer to drop this when we saw --zip-fd.
132 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700133 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700134 if (StartsWith(original_argv[i], "--zip-") ||
135 StartsWith(original_argv[i], "--dex-") ||
136 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700137 StartsWith(original_argv[i], "--swap-") ||
138 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700139 continue;
140 }
141 }
142
143 command.push_back(original_argv[i]);
144 }
145
146 // Construct the final output.
147 if (command.size() <= 1U) {
148 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
149 return "Starting dex2oat.";
150 }
151 return Join(command, ' ');
152}
153
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154static void UsageErrorV(const char* fmt, va_list ap) {
155 std::string error;
156 StringAppendV(&error, fmt, ap);
157 LOG(ERROR) << error;
158}
159
160static void UsageError(const char* fmt, ...) {
161 va_list ap;
162 va_start(ap, fmt);
163 UsageErrorV(fmt, ap);
164 va_end(ap);
165}
166
Andreas Gampe794ad762015-02-23 08:12:24 -0800167NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 va_list ap;
169 va_start(ap, fmt);
170 UsageErrorV(fmt, ap);
171 va_end(ap);
172
Brian Carlstrom6449c622014-02-10 23:48:36 -0800173 UsageError("Command: %s", CommandLine().c_str());
174
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 UsageError("Usage: dex2oat [options]...");
176 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100177 UsageError(" -j<number>: specifies the number of threads used for compilation.");
178 UsageError(" Default is the number of detected hardware threads available on the");
179 UsageError(" host system.");
180 UsageError(" Example: -j12");
181 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700182 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 UsageError(" Example: --dex-file=/system/framework/core.jar");
184 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700185 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
186 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
187 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
188 UsageError(" --dex-location=/system/framework/core.jar");
189 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
191 UsageError(" containing a classes.dex file to compile.");
192 UsageError(" Example: --zip-fd=5");
193 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700194 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
195 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
197 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 UsageError(" Example: --oat-file=/system/framework/boot.oat");
200 UsageError("");
201 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900202 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError("");
204 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
205 UsageError(" to the file descriptor specified by --oat-fd.");
206 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
207 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
210 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 UsageError(" Example: --image=/system/framework/boot.art");
213 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800214 UsageError(" --image-format=(uncompressed|lz4):");
215 UsageError(" Which format to store the image.");
216 UsageError(" Example: --image-format=lz4");
217 UsageError(" Default: uncompressed");
218 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
220 UsageError(" Example: --image=frameworks/base/preloaded-classes");
221 UsageError("");
222 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
223 UsageError(" Example: --base=0x50000000");
224 UsageError("");
225 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000226 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000228 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000229 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError("");
231 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
232 UsageError(" Example: --android-root=out/host/linux-x86");
233 UsageError(" Default: $ANDROID_ROOT");
234 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800235 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700236 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError(" Example: --instruction-set=x86");
238 UsageError(" Default: arm");
239 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700240 UsageError(" --instruction-set-features=...,: Specify instruction set features");
241 UsageError(" Example: --instruction-set-features=div");
242 UsageError(" Default: default");
243 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700244 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
245 UsageError(" Default: disabled");
246 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800247 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800249 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100250 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100252 UsageError(" --compiler-filter="
253 "(verify-none"
254 "|interpret-only"
255 "|space"
256 "|balanced"
257 "|speed"
258 "|everything"
259 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700260 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800262 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800263 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800264 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
265 UsageError(" method for compiler filter tuning.");
266 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
267 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
268 UsageError("");
269 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
270 UsageError(" method for compiler filter tuning.");
271 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
272 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
273 UsageError("");
274 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
275 UsageError(" method for compiler filter tuning.");
276 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
278 UsageError("");
279 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
280 UsageError(" method for compiler filter tuning.");
281 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
282 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
283 UsageError("");
284 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
285 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700286 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
287 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800288 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
289 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
290 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100291 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
292 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100293 UsageError(" Has priority over the --compiler-filter option. Intended for ");
294 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100295 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
296 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
297 UsageError("");
298 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
299 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100300 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
301 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100302 UsageError(" Example: --inline-max-code-units=%d",
303 CompilerOptions::kDefaultInlineMaxCodeUnits);
304 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
305 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700306 UsageError(" --dump-timing: display a breakdown of where time was spent");
307 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700308 UsageError(" --include-patch-information: Include patching information so the generated code");
309 UsageError(" can have its base address moved without full recompilation.");
310 UsageError("");
311 UsageError(" --no-include-patch-information: Do not include patching information.");
312 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100313 UsageError(" -g");
314 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
315 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000316 UsageError(" If used without --native-debuggable, it will be best-effort only.");
317 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100320 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000321 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
322 UsageError(" debug information necessary to print backtraces. (disabled by default)");
323 UsageError("");
324 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
325 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000326 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000327 UsageError("");
328 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
329 UsageError(" Implies --debuggable.");
330 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
332 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
333 UsageError(" Use a separate --runtime-arg switch for each argument.");
334 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700335 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000336 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200337 UsageError(" Can be specified multiple time, in which case the data from the different");
338 UsageError(" profiles will be aggregated.");
339 UsageError("");
340 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
341 UsageError(" compiling. The data in this file will be compared with the data in the");
342 UsageError(" associated --profile-file and the compilation will proceed only if there is");
343 UsageError(" a significant difference (--reference-profile-file is paired with");
344 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
345 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
346 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000348 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
349 UsageError(" Cannot be used together with --profile-file.");
350 UsageError("");
351 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
352 UsageError(" accepts a file descriptor. Cannot be used together with");
353 UsageError(" --reference-profile-file.");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700354 UsageError(" --print-pass-names: print a list of pass names");
355 UsageError("");
356 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
357 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
358 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700359 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
360 "with the setting.");
361 UsageError(" Will print default if no overridden setting exists.");
362 UsageError("");
363 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
364 "Pass2Name:Pass2OptionName:Pass2Option#");
365 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
366 UsageError(" Separator used between options is a comma.");
367 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800368 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
369 UsageError(" Example: --swap-file=/data/tmp/swap.001");
370 UsageError("");
371 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
372 UsageError(" Example: --swap-fd=10");
373 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700374 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
375 UsageError(" Example: --app-image-fd=10");
376 UsageError("");
377 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
378 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
379 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800380 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
381 "input dex file.");
382 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000383 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
384 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
385 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
386 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 std::cerr << "See log for usage error information\n";
388 exit(EXIT_FAILURE);
389}
390
Brian Carlstrom7940e442013-07-12 13:46:57 -0700391// The primary goal of the watchdog is to prevent stuck build servers
392// during development when fatal aborts lead to a cascade of failures
393// that result in a deadlock.
394class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800395// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396#undef CHECK_PTHREAD_CALL
397#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
398 do { \
399 int rc = call args; \
400 if (rc != 0) { \
401 errno = rc; \
402 std::string message(# call); \
403 message += " failed for "; \
404 message += reason; \
405 Fatal(message); \
406 } \
407 } while (false)
408
409 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700410 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700411 is_watch_dog_enabled_ = is_watch_dog_enabled;
412 if (!is_watch_dog_enabled_) {
413 return;
414 }
415 shutting_down_ = false;
416 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700417 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
418 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
420 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
422 }
423 ~WatchDog() {
424 if (!is_watch_dog_enabled_) {
425 return;
426 }
427 const char* reason = "dex2oat watch dog thread shutdown";
428 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
429 shutting_down_ = true;
430 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
431 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
432
Kenny Root51316382014-05-13 14:59:37 -0700433 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700434
435 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
436 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
437 }
438
439 private:
440 static void* CallBack(void* arg) {
441 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
442 ::art::SetThreadName("dex2oat watch dog");
443 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700444 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 }
446
Andreas Gampe794ad762015-02-23 08:12:24 -0800447 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700448 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
449 // it's rather easy to hang in unwinding.
450 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
451 // logcat logging or stderr output.
452 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453 exit(1);
454 }
455
456 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
458 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700459 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 timespec timeout_ts;
461 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
462 const char* reason = "dex2oat watch dog thread waiting";
463 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
464 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800465 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700467 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
468 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 } else if (rc != 0) {
470 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
471 strerror(errno)));
472 Fatal(message.c_str());
473 }
474 }
475 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
476 }
477
478 // 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 -0700479 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700480 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800481
Andreas Gampe540138a2015-09-14 15:34:38 -0700482 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
483 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
484 // itself before that watchdog would take down the system server.
485 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486
487 bool is_watch_dog_enabled_;
488 bool shutting_down_;
489 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
490 pthread_mutex_t mutex_;
491 pthread_cond_t cond_;
492 pthread_attr_t attr_;
493 pthread_t pthread_;
494};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700495
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800496static constexpr size_t kMinDexFilesForSwap = 2;
497static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
498
499static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
500 if (is_image) {
501 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
502 return false;
503 }
504 if (dex_files.size() < kMinDexFilesForSwap) {
505 // If there are less dex files than the threshold, assume it's gonna be fine.
506 return false;
507 }
508 size_t dex_files_size = 0;
509 for (const auto* dex_file : dex_files) {
510 dex_files_size += dex_file->GetHeader().file_size_;
511 }
512 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
513}
514
Calin Juravle877fd962016-01-05 14:29:29 +0000515static void CloseAllFds(const std::vector<uint32_t>& fds, const char* descriptor) {
516 for (size_t i = 0; i < fds.size(); i++) {
517 if (close(fds[i]) < 0) {
518 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
519 }
520 }
521}
522
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800523class Dex2Oat FINAL {
524 public:
525 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100526 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800527 instruction_set_(kRuntimeISA),
528 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000529 image_file_location_oat_checksum_(0),
530 image_file_location_oat_data_begin_(0),
531 image_patch_delta_(0),
532 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700533 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800534 method_inliner_map_(),
535 runtime_(nullptr),
536 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
537 start_ns_(NanoTime()),
538 oat_fd_(-1),
539 zip_fd_(-1),
540 image_base_(0U),
541 image_classes_zip_filename_(nullptr),
542 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800543 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800544 compiled_classes_zip_filename_(nullptr),
545 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700546 compiled_methods_zip_filename_(nullptr),
547 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700548 app_image_(false),
549 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800550 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800551 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000552 class_loader_(nullptr),
553 elf_writers_(),
554 oat_writers_(),
555 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000556 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700557 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000558 opened_dex_files_maps_(),
559 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000560 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800561 dump_stats_(false),
562 dump_passes_(false),
563 dump_timing_(false),
564 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800565 swap_fd_(-1),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800566 app_image_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800567 timings_(timings),
568 force_determinism_(false) {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800569
570 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800571 // Log completion time before deleting the runtime_, because this accesses
572 // the runtime.
573 LogCompletionTime();
574
Vladimir Marko307dac92015-10-20 11:20:09 +0100575 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
576 // We want to just exit on non-debug builds, not bringing the runtime down
577 // in an orderly fashion. So release the following fields.
578 driver_.release();
579 image_writer_.release();
580 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
581 dex_file.release();
582 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000583 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
584 map.release();
585 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800586 for (std::unique_ptr<File>& oat_file : oat_files_) {
587 oat_file.release();
588 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100589 runtime_.release();
590 verification_results_.release();
591 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100592 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 }
594
Roland Levillain9ec5e222015-08-17 20:18:41 +0100595 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800596 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800597 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800598 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000599 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800600 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100601 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800602
Roland Levillain9ec5e222015-08-17 20:18:41 +0100603 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000604 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100605 }
606
607 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000608 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100609 }
610
Calin Juravle877fd962016-01-05 14:29:29 +0000611 void ParseFdForCollection(const StringPiece& option,
612 const char* arg_name,
613 std::vector<uint32_t>* fds) {
614 uint32_t fd;
615 ParseUintOption(option, arg_name, &fd, Usage);
616 fds->push_back(fd);
617 }
618
Roland Levillain9ec5e222015-08-17 20:18:41 +0100619 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000620 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100621 }
622
623 void ParseBase(const StringPiece& option) {
624 DCHECK(option.starts_with("--base="));
625 const char* image_base_str = option.substr(strlen("--base=")).data();
626 char* end;
627 image_base_ = strtoul(image_base_str, &end, 16);
628 if (end == image_base_str || *end != '\0') {
629 Usage("Failed to parse hexadecimal value for option %s", option.data());
630 }
631 }
632
633 void ParseInstructionSet(const StringPiece& option) {
634 DCHECK(option.starts_with("--instruction-set="));
635 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
636 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
637 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
638 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
639 buf.get()[instruction_set_str.length()] = 0;
640 instruction_set_ = GetInstructionSetFromString(buf.get());
641 // arm actually means thumb2.
642 if (instruction_set_ == InstructionSet::kArm) {
643 instruction_set_ = InstructionSet::kThumb2;
644 }
645 }
646
647 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
648 DCHECK(option.starts_with("--instruction-set-variant="));
649 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
650 instruction_set_features_.reset(
651 InstructionSetFeatures::FromVariant(
652 instruction_set_, str.as_string(), &parser_options->error_msg));
653 if (instruction_set_features_.get() == nullptr) {
654 Usage("%s", parser_options->error_msg.c_str());
655 }
656 }
657
658 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
659 DCHECK(option.starts_with("--instruction-set-features="));
660 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
661 if (instruction_set_features_.get() == nullptr) {
662 instruction_set_features_.reset(
663 InstructionSetFeatures::FromVariant(
664 instruction_set_, "default", &parser_options->error_msg));
665 if (instruction_set_features_.get() == nullptr) {
666 Usage("Problem initializing default instruction set features variant: %s",
667 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800669 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100670 instruction_set_features_.reset(
671 instruction_set_features_->AddFeaturesFromString(str.as_string(),
672 &parser_options->error_msg));
673 if (instruction_set_features_.get() == nullptr) {
674 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
675 }
676 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800677
Roland Levillain9ec5e222015-08-17 20:18:41 +0100678 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
679 DCHECK(option.starts_with("--compiler-backend="));
680 parser_options->requested_specific_compiler = true;
681 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
682 if (backend_str == "Quick") {
683 compiler_kind_ = Compiler::kQuick;
684 } else if (backend_str == "Optimizing") {
685 compiler_kind_ = Compiler::kOptimizing;
686 } else {
687 Usage("Unknown compiler backend: %s", backend_str.data());
688 }
689 }
690
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800691 void ParseImageFormat(const StringPiece& option) {
692 const StringPiece substr("--image-format=");
693 DCHECK(option.starts_with(substr));
694 const StringPiece format_str = option.substr(substr.length());
695 if (format_str == "lz4") {
696 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
697 } else if (format_str == "uncompressed") {
698 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
699 } else {
700 Usage("Unknown image format: %s", format_str.data());
701 }
702 }
703
Jeff Hao436183f2016-01-12 16:36:50 -0800704 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800705 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700706 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
707
708 if (IsAppImage() && IsBootImage()) {
709 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
710 }
711
712 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100713 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000714 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000715 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000716
Jeff Haodcdc85b2015-12-04 14:06:18 -0800717 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800718 Usage("Output must be supplied with either --oat-file or --oat-fd");
719 }
720
Jeff Haodcdc85b2015-12-04 14:06:18 -0800721 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 Usage("--oat-file should not be used with --oat-fd");
723 }
724
Roland Levillain9ec5e222015-08-17 20:18:41 +0100725 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800726 Usage("--oat-symbols should not be used with --oat-fd");
727 }
728
Roland Levillain9ec5e222015-08-17 20:18:41 +0100729 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800730 Usage("--oat-symbols should not be used with --host");
731 }
732
Jeff Haodcdc85b2015-12-04 14:06:18 -0800733 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 Usage("--oat-fd should not be used with --image");
735 }
736
Jeff Haodcdc85b2015-12-04 14:06:18 -0800737 if (!parser_options->oat_symbols.empty() &&
738 parser_options->oat_symbols.size() != oat_filenames_.size()) {
739 Usage("--oat-file arguments do not match --oat-symbols arguments");
740 }
741
742 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
743 Usage("--oat-file arguments do not match --image arguments");
744 }
745
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800746 if (android_root_.empty()) {
747 const char* android_root_env_var = getenv("ANDROID_ROOT");
748 if (android_root_env_var == nullptr) {
749 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 android_root_ += android_root_env_var;
752 }
753
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700754 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100755 parser_options->boot_image_filename += android_root_;
756 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800757 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100758 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000759 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800760 }
761
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700762 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800763 Usage("--image-classes should only be used with --image");
764 }
765
Vladimir Marko49b0f452015-12-10 13:49:19 +0000766 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800767 Usage("--image-classes should not be used with --boot-image");
768 }
769
770 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
771 Usage("--image-classes-zip should be used with --image-classes");
772 }
773
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700774 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800775 Usage("--compiled-classes should only be used with --image");
776 }
777
Vladimir Marko49b0f452015-12-10 13:49:19 +0000778 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800779 Usage("--compiled-classes should not be used with --boot-image");
780 }
781
782 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
783 Usage("--compiled-classes-zip should be used with --compiled-classes");
784 }
785
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800786 if (dex_filenames_.empty() && zip_fd_ == -1) {
787 Usage("Input must be supplied with either --dex-file or --zip-fd");
788 }
789
790 if (!dex_filenames_.empty() && zip_fd_ != -1) {
791 Usage("--dex-file should not be used with --zip-fd");
792 }
793
794 if (!dex_filenames_.empty() && !zip_location_.empty()) {
795 Usage("--dex-file should not be used with --zip-location");
796 }
797
798 if (dex_locations_.empty()) {
799 for (const char* dex_file_name : dex_filenames_) {
800 dex_locations_.push_back(dex_file_name);
801 }
802 } else if (dex_locations_.size() != dex_filenames_.size()) {
803 Usage("--dex-location arguments do not match --dex-file arguments");
804 }
805
Jeff Haodcdc85b2015-12-04 14:06:18 -0800806 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
807 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
808 Usage("--oat-file arguments must be singular or match --dex-file arguments");
809 }
810 }
811
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800812 if (zip_fd_ != -1 && zip_location_.empty()) {
813 Usage("--zip-location should be supplied with --zip-fd");
814 }
815
Vladimir Marko49b0f452015-12-10 13:49:19 +0000816 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800817 if (image_base_ == 0) {
818 Usage("Non-zero --base not specified");
819 }
820 }
821
Calin Juravle877fd962016-01-05 14:29:29 +0000822 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
823 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
824 }
Calin Juravle998c2162015-12-21 15:39:33 +0200825 if (!profile_files_.empty()) {
826 if (!reference_profile_files_.empty() &&
827 (reference_profile_files_.size() != profile_files_.size())) {
828 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
829 }
Calin Juravle877fd962016-01-05 14:29:29 +0000830 } else if (!reference_profile_files_.empty()) {
831 Usage("--reference-profile-file should only be supplied with --profile-file");
832 }
833 if (!profile_files_fd_.empty()) {
834 if (!reference_profile_files_fd_.empty() &&
835 (reference_profile_files_fd_.size() != profile_files_fd_.size())) {
836 Usage("If specified, --reference-profile-file-fd should match the number",
837 " of --profile-file-fd.");
838 }
839 } else if (!reference_profile_files_fd_.empty()) {
840 Usage("--reference-profile-file-fd should only be supplied with --profile-file-fd");
Calin Juravle998c2162015-12-21 15:39:33 +0200841 }
842
Roland Levillain9ec5e222015-08-17 20:18:41 +0100843 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800844 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800845 }
846
847 // If no instruction set feature was given, use the default one for the target
848 // instruction set.
849 if (instruction_set_features_.get() == nullptr) {
850 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100851 InstructionSetFeatures::FromVariant(
852 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800853 if (instruction_set_features_.get() == nullptr) {
854 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100855 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800856 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800857 }
858
859 if (instruction_set_ == kRuntimeISA) {
860 std::unique_ptr<const InstructionSetFeatures> runtime_features(
861 InstructionSetFeatures::FromCppDefines());
862 if (!instruction_set_features_->Equals(runtime_features.get())) {
863 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
864 << *instruction_set_features_ << ") and those of dex2oat executable ("
865 << *runtime_features <<") for the command line:\n"
866 << CommandLine();
867 }
868 }
869
Roland Levillaina215b952015-08-07 11:38:32 +0100870 // It they are not set, use default values for inlining settings.
871 // TODO: We should rethink the compiler filter. We mostly save
872 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000873 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
874 compiler_options_->inline_depth_limit_ =
875 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100876 // Implementation of the space filter: limit inlining depth.
877 ? CompilerOptions::kSpaceFilterInlineDepthLimit
878 : CompilerOptions::kDefaultInlineDepthLimit;
879 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000880 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
881 compiler_options_->inline_max_code_units_ =
882 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100883 // Implementation of the space filter: limit inlining max code units.
884 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
885 : CompilerOptions::kDefaultInlineMaxCodeUnits;
886 }
887
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800888 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800889 // Set the compilation target's implicit checks options.
890 switch (instruction_set_) {
891 case kArm:
892 case kThumb2:
893 case kArm64:
894 case kX86:
895 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700896 case kMips:
897 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000898 compiler_options_->implicit_null_checks_ = true;
899 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800900 break;
901
902 default:
903 // Defaults are correct.
904 break;
905 }
906
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000907 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800908
Jeff Hao436183f2016-01-12 16:36:50 -0800909 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800910 Usage("--multi-image can only be used when creating boot images");
911 }
Jeff Hao436183f2016-01-12 16:36:50 -0800912 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800913 Usage("--multi-image cannot be used with multiple image names");
914 }
915
916 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
917 if (!kIsTargetBuild && IsBootImage()) {
918 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800919 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800920 }
921 }
922
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800923 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100924 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800925 watchdog_.reset(new WatchDog(true));
926 }
927
928 // Fill some values into the key-value store for the oat header.
929 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800930
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800931 // Automatically force determinism for the boot image in a host build if the default GC is CMS
932 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
933 // one by passing the option `-Xgc:nonconcurrent` (see below).
934 if (!kIsTargetBuild && IsBootImage()) {
935 if (SupportsDeterministicCompilation()) {
936 force_determinism_ = true;
937 } else {
938 LOG(WARNING) << "Deterministic compilation is disabled.";
939 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800940 }
941 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100942 }
943
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800944 static bool SupportsDeterministicCompilation() {
945 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
946 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
947 !kEmitCompilerReadBarrier;
948 }
949
Jeff Hao436183f2016-01-12 16:36:50 -0800950 void ExpandOatAndImageFilenames() {
951 std::string base_oat = oat_filenames_[0];
952 size_t last_oat_slash = base_oat.rfind('/');
953 if (last_oat_slash == std::string::npos) {
954 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
955 }
956 // We also need to honor path components that were encoded through '@'. Otherwise the loading
957 // code won't be able to find the images.
958 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
959 last_oat_slash = base_oat.rfind('@');
960 }
961 base_oat = base_oat.substr(0, last_oat_slash + 1);
962
963 std::string base_img = image_filenames_[0];
964 size_t last_img_slash = base_img.rfind('/');
965 if (last_img_slash == std::string::npos) {
966 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
967 }
968 // We also need to honor path components that were encoded through '@'. Otherwise the loading
969 // code won't be able to find the images.
970 if (base_img.find('@', last_img_slash) != std::string::npos) {
971 last_img_slash = base_img.rfind('@');
972 }
973
974 // Get the prefix, which is the primary image name (without path components). Strip the
975 // extension.
976 std::string prefix = base_img.substr(last_img_slash + 1);
977 if (prefix.rfind('.') != std::string::npos) {
978 prefix = prefix.substr(0, prefix.rfind('.'));
979 }
980 if (!prefix.empty()) {
981 prefix = prefix + "-";
982 }
983
984 base_img = base_img.substr(0, last_img_slash + 1);
985
986 // Note: we have some special case here for our testing. We have to inject the differentiating
987 // parts for the different core images.
988 std::string infix; // Empty infix by default.
989 {
990 // Check the first name.
991 std::string dex_file = oat_filenames_[0];
992 size_t last_dex_slash = dex_file.rfind('/');
993 if (last_dex_slash != std::string::npos) {
994 dex_file = dex_file.substr(last_dex_slash + 1);
995 }
996 size_t last_dex_dot = dex_file.rfind('.');
997 if (last_dex_dot != std::string::npos) {
998 dex_file = dex_file.substr(0, last_dex_dot);
999 }
1000 if (StartsWith(dex_file, "core-")) {
1001 infix = dex_file.substr(strlen("core"));
1002 }
1003 }
1004
1005 // Now create the other names. Use a counted loop to skip the first one.
1006 for (size_t i = 1; i < dex_locations_.size(); ++i) {
1007 // TODO: Make everything properly std::string.
1008 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
1009 char_backing_storage_.push_back(base_img + image_name);
1010 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1011
1012 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
1013 char_backing_storage_.push_back(base_oat + oat_name);
1014 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1015 }
1016 }
1017
Andreas Gampe8994a042015-12-30 19:03:17 +00001018 // Modify the input string in the following way:
1019 // 0) Assume input is /a/b/c.d
1020 // 1) Strip the path -> c.d
1021 // 2) Inject prefix p -> pc.d
1022 // 3) Inject infix i -> pci.d
1023 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001025 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001026 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001027 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001028 size_t last_dex_slash = in.rfind('/');
1029 if (last_dex_slash != std::string::npos) {
1030 in = in.substr(last_dex_slash + 1);
1031 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001032 if (!prefix.empty()) {
1033 in = prefix + in;
1034 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001035 if (!infix.empty()) {
1036 // Inject infix.
1037 size_t last_dot = in.rfind('.');
1038 if (last_dot != std::string::npos) {
1039 in.insert(last_dot, infix);
1040 }
1041 }
1042 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001043 in = in.substr(0, in.length() - strlen(".jar")) +
1044 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001045 }
1046 return in;
1047 }
1048
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001049 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001050 std::ostringstream oss;
1051 for (int i = 0; i < argc; ++i) {
1052 if (i > 0) {
1053 oss << ' ';
1054 }
1055 oss << argv[i];
1056 }
1057 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1058 oss.str(""); // Reset.
1059 oss << kRuntimeISA;
1060 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1061 key_value_store_->Put(
1062 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001063 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001064 key_value_store_->Put(
1065 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001066 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdilce4b0ba2016-01-28 15:05:49 +00001067 key_value_store_->Put(
1068 OatHeader::kExtractOnlyKey,
1069 compiler_options_->IsExtractOnly() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001070 }
1071
1072 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1073 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1074 // returns, arguments have been successfully parsed.
1075 void ParseArgs(int argc, char** argv) {
1076 original_argc = argc;
1077 original_argv = argv;
1078
1079 InitLogging(argv);
1080
1081 // Skip over argv[0].
1082 argv++;
1083 argc--;
1084
1085 if (argc == 0) {
1086 Usage("No arguments specified");
1087 }
1088
1089 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001090 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001091
1092 for (int i = 0; i < argc; i++) {
1093 const StringPiece option(argv[i]);
1094 const bool log_options = false;
1095 if (log_options) {
1096 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1097 }
1098 if (option.starts_with("--dex-file=")) {
1099 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1100 } else if (option.starts_with("--dex-location=")) {
1101 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1102 } else if (option.starts_with("--zip-fd=")) {
1103 ParseZipFd(option);
1104 } else if (option.starts_with("--zip-location=")) {
1105 zip_location_ = option.substr(strlen("--zip-location=")).data();
1106 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001107 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001108 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001109 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001110 } else if (option.starts_with("--oat-fd=")) {
1111 ParseOatFd(option);
1112 } else if (option == "--watch-dog") {
1113 parser_options->watch_dog_enabled = true;
1114 } else if (option == "--no-watch-dog") {
1115 parser_options->watch_dog_enabled = false;
1116 } else if (option.starts_with("-j")) {
1117 ParseJ(option);
1118 } else if (option.starts_with("--oat-location=")) {
1119 oat_location_ = option.substr(strlen("--oat-location=")).data();
1120 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001121 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001122 } else if (option.starts_with("--image-classes=")) {
1123 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1124 } else if (option.starts_with("--image-classes-zip=")) {
1125 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001126 } else if (option.starts_with("--image-format=")) {
1127 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001128 } else if (option.starts_with("--compiled-classes=")) {
1129 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1130 } else if (option.starts_with("--compiled-classes-zip=")) {
1131 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1132 } else if (option.starts_with("--compiled-methods=")) {
1133 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1134 } else if (option.starts_with("--compiled-methods-zip=")) {
1135 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1136 } else if (option.starts_with("--base=")) {
1137 ParseBase(option);
1138 } else if (option.starts_with("--boot-image=")) {
1139 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1140 } else if (option.starts_with("--android-root=")) {
1141 android_root_ = option.substr(strlen("--android-root=")).data();
1142 } else if (option.starts_with("--instruction-set=")) {
1143 ParseInstructionSet(option);
1144 } else if (option.starts_with("--instruction-set-variant=")) {
1145 ParseInstructionSetVariant(option, parser_options.get());
1146 } else if (option.starts_with("--instruction-set-features=")) {
1147 ParseInstructionSetFeatures(option, parser_options.get());
1148 } else if (option.starts_with("--compiler-backend=")) {
1149 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001150 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001151 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1152 } else if (option.starts_with("--reference-profile-file=")) {
1153 reference_profile_files_.push_back(
1154 option.substr(strlen("--reference-profile-file=")).ToString());
Calin Juravle877fd962016-01-05 14:29:29 +00001155 } else if (option.starts_with("--profile-file-fd=")) {
1156 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
1157 } else if (option.starts_with("--reference-profile-file-fd=")) {
1158 ParseFdForCollection(option, "--reference_profile-file-fd", &reference_profile_files_fd_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001159 } else if (option == "--no-profile-file") {
1160 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001161 } else if (option == "--host") {
1162 is_host_ = true;
1163 } else if (option == "--runtime-arg") {
1164 if (++i >= argc) {
1165 Usage("Missing required argument for --runtime-arg");
1166 }
1167 if (log_options) {
1168 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1169 }
1170 runtime_args_.push_back(argv[i]);
1171 } else if (option == "--dump-timing") {
1172 dump_timing_ = true;
1173 } else if (option == "--dump-passes") {
1174 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001175 } else if (option == "--dump-stats") {
1176 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001177 } else if (option.starts_with("--swap-file=")) {
1178 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1179 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001180 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1181 } else if (option.starts_with("--app-image-file=")) {
1182 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1183 } else if (option.starts_with("--app-image-fd=")) {
1184 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001185 } else if (option.starts_with("--verbose-methods=")) {
1186 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1187 // conditional on having verbost methods.
1188 gLogVerbosity.compiler = false;
1189 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001190 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001191 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001192 } else if (option.starts_with("--no-inline-from=")) {
1193 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001194 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001195 if (!SupportsDeterministicCompilation()) {
1196 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001197 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001198 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001199 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001200 Usage("Unknown argument %s", option.data());
1201 }
1202 }
1203
Jeff Hao436183f2016-01-12 16:36:50 -08001204 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001205
1206 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001207 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 }
1209
Jeff Haodcdc85b2015-12-04 14:06:18 -08001210 // Check whether the oat output files are writable, and open them for later. Also open a swap
1211 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001213 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1214 PruneNonExistentDexFiles();
1215
Jeff Hao436183f2016-01-12 16:36:50 -08001216 // Expand oat and image filenames for multi image.
1217 if (IsBootImage() && multi_image_) {
1218 ExpandOatAndImageFilenames();
1219 }
1220
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001222 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001223 for (const char* oat_filename : oat_filenames_) {
1224 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1225 if (oat_file.get() == nullptr) {
1226 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1227 return false;
1228 }
1229 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1230 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1231 oat_file->Erase();
1232 return false;
1233 }
1234 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 }
1236 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001237 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1238 oat_file->DisableAutoClose();
1239 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001240 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1241 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001242 if (oat_file.get() == nullptr) {
1243 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1244 return false;
1245 }
1246 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1247 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1248 oat_file->Erase();
1249 return false;
1250 }
1251 oat_filenames_.push_back(oat_location_.c_str());
1252 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001254
1255 // Swap file handling.
1256 //
1257 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1258 // that we can use for swap.
1259 //
1260 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1261 // will immediately unlink to satisfy the swap fd assumption.
1262 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1263 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1264 if (swap_file.get() == nullptr) {
1265 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1266 return false;
1267 }
1268 swap_fd_ = swap_file->Fd();
1269 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1270 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1271 // released immediately.
1272 unlink(swap_file_name_.c_str());
1273 }
Jeff Hao436183f2016-01-12 16:36:50 -08001274
1275 // If we use a swap file, ensure we are above the threshold to make it necessary.
1276 if (swap_fd_ != -1) {
1277 if (!UseSwap(IsBootImage(), dex_files_)) {
1278 close(swap_fd_);
1279 swap_fd_ = -1;
1280 VLOG(compiler) << "Decided to run without swap.";
1281 } else {
1282 LOG(INFO) << "Large app, accepted running with swap.";
1283 }
1284 }
1285 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1286
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001287 return true;
1288 }
1289
Jeff Haodcdc85b2015-12-04 14:06:18 -08001290 void EraseOatFiles() {
1291 for (size_t i = 0; i < oat_files_.size(); ++i) {
1292 DCHECK(oat_files_[i].get() != nullptr);
1293 oat_files_[i]->Erase();
1294 oat_files_[i].reset();
1295 }
Andreas Gampea650e702014-12-03 14:28:02 -08001296 }
1297
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001298 void Shutdown() {
1299 ScopedObjectAccess soa(Thread::Current());
1300 for (jobject dex_cache : dex_caches_) {
1301 soa.Env()->DeleteLocalRef(dex_cache);
1302 }
1303 dex_caches_.clear();
1304 }
1305
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001306 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1307 // boot class path.
1308 bool Setup() {
1309 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001310 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001311
1312 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1313 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001314 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001315
Vladimir Marko307dac92015-10-20 11:20:09 +01001316 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001317 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001318 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001319 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001320 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001321 CompilerCallbacks::CallbackMode::kCompileBootImage :
1322 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001323
Vladimir Marko49b0f452015-12-10 13:49:19 +00001324 RuntimeArgumentMap runtime_options;
1325 if (!PrepareRuntimeOptions(&runtime_options)) {
1326 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001327 }
1328
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001329 CreateOatWriters();
1330 if (!AddDexFileSources()) {
1331 return false;
1332 }
1333
1334 if (IsBootImage() && image_filenames_.size() > 1) {
1335 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1336 // We need this for the multi-image case.
1337 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1338 }
1339
1340 if (!IsBootImage()) {
1341 // When compiling an app, create the runtime early to retrieve
1342 // the image location key needed for the oat header.
1343 if (!CreateRuntime(std::move(runtime_options))) {
1344 return false;
1345 }
1346
David Brazdilce4b0ba2016-01-28 15:05:49 +00001347 if (compiler_options_->IsExtractOnly()) {
1348 // ExtractOnly oat files only contain non-quickened DEX code and are
1349 // therefore independent of the image file.
1350 image_file_location_oat_checksum_ = 0u;
1351 image_file_location_oat_data_begin_ = 0u;
1352 image_patch_delta_ = 0;
1353 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001354 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1355 std::vector<gc::space::ImageSpace*> image_spaces =
1356 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1357 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1358 image_file_location_oat_data_begin_ =
1359 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1360 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1361 // Store the boot image filename(s).
1362 std::vector<std::string> image_filenames;
1363 for (const gc::space::ImageSpace* image_space : image_spaces) {
1364 image_filenames.push_back(image_space->GetImageFilename());
1365 }
1366 std::string image_file_location = Join(image_filenames, ':');
1367 if (!image_file_location.empty()) {
1368 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1369 }
1370 }
1371
1372 // Open dex files for class path.
1373 const std::vector<std::string> class_path_locations =
1374 GetClassPathLocations(runtime_->GetClassPathString());
1375 OpenClassPathFiles(class_path_locations, &class_path_files_);
1376
1377 // Store the classpath we have right now.
1378 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1379 key_value_store_->Put(OatHeader::kClassPathKey,
1380 OatFile::EncodeDexFileDependencies(class_path_files));
1381 }
1382
1383 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001384 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001385 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1386 rodata_.reserve(oat_writers_.size());
1387 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1388 rodata_.push_back(elf_writers_[i]->StartRoData());
1389 // Unzip or copy dex files straight to the oat file.
1390 std::unique_ptr<MemMap> opened_dex_files_map;
1391 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1392 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1393 oat_files_[i].get(),
1394 instruction_set_,
1395 instruction_set_features_.get(),
1396 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001397 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001398 &opened_dex_files_map,
1399 &opened_dex_files)) {
1400 return false;
1401 }
1402 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1403 if (opened_dex_files_map != nullptr) {
1404 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1405 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
1406 dex_file_oat_filename_map_.emplace(dex_file.get(), oat_filenames_[i]);
1407 opened_dex_files_.push_back(std::move(dex_file));
1408 }
1409 } else {
1410 DCHECK(opened_dex_files.empty());
1411 }
1412 }
1413 }
1414
1415 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1416 if (IsBootImage()) {
1417 // For boot image, pass opened dex files to the Runtime::Create().
1418 // Note: Runtime acquires ownership of these dex files.
1419 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001420 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001421 return false;
1422 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001423 }
1424
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001425 // If we're doing the image, override the compiler filter to force full compilation. Must be
1426 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1427 // compilation of class initializers.
1428 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001429 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001430 WellKnownClasses::Init(self->GetJniEnv());
1431
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001432 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001433 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001434 constexpr bool kSaveDexInput = false;
1435 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001436 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001437 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001438
1439 // Handle and ClassLoader creation needs to come after Runtime::Create.
1440 ScopedObjectAccess soa(self);
1441
1442 // Classpath: first the class-path given.
1443 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1444
1445 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1446 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1447
1448 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001449 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001450
1451 // Ensure opened dex files are writable for dex-to-dex transformations.
1452 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1453 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1454 PLOG(ERROR) << "Failed to make .dex files writeable.";
1455 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001456 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001457 }
1458
1459 // Ensure that the dex caches stay live since we don't want class unloading
1460 // to occur during compilation.
1461 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001462 ScopedObjectAccess soa(self);
1463 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001464 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001465 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001466
1467 /*
1468 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1469 * Don't bother to check if we're doing the image.
1470 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001471 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001472 compiler_options_->IsCompilationEnabled() &&
1473 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001474 size_t num_methods = 0;
1475 for (size_t i = 0; i != dex_files_.size(); ++i) {
1476 const DexFile* dex_file = dex_files_[i];
1477 CHECK(dex_file != nullptr);
1478 num_methods += dex_file->NumMethodIds();
1479 }
1480 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1481 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1482 VLOG(compiler) << "Below method threshold, compiling anyways";
1483 }
1484 }
1485
1486 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001487 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001488
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001489 // If we need to keep the oat file open for the image writer.
1490 bool ShouldKeepOatFileOpen() const {
1491 return IsImage() && oat_fd_ != kInvalidFd;
1492 }
1493
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 // Create and invoke the compiler driver. This will compile all the dex files.
1495 void Compile() {
1496 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1497 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001498
Vladimir Marko47496c22016-01-27 16:15:08 +00001499 // Find the dex files we should not inline from.
1500
1501 std::vector<std::string> no_inline_filters;
1502 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001503
1504 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001505 const std::string core_oj = "core-oj";
1506 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1507 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001508 }
1509
Vladimir Marko47496c22016-01-27 16:15:08 +00001510 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001511 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1512 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1513 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1514 &class_linker->GetBootClassPath(),
1515 &class_path_files,
1516 &dex_files_
1517 };
1518 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001519 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001520 for (const std::string& filter : no_inline_filters) {
1521 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1522 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1523 // base location passes the StartsWith() test, so do all extra locations.
1524 std::string dex_location = dex_file->GetLocation();
1525 if (filter.find('/') == std::string::npos) {
1526 // The filter does not contain the path. Remove the path from dex_location as well.
1527 size_t last_slash = dex_file->GetLocation().rfind('/');
1528 if (last_slash != std::string::npos) {
1529 dex_location = dex_location.substr(last_slash + 1);
1530 }
1531 }
1532
1533 if (StartsWith(dex_location, filter.c_str())) {
1534 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1535 no_inline_from_dex_files_.push_back(dex_file);
1536 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 }
1538 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001540 }
1541 if (!no_inline_from_dex_files_.empty()) {
1542 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001543 }
1544 }
1545
Vladimir Marko307dac92015-10-20 11:20:09 +01001546 driver_.reset(new CompilerDriver(compiler_options_.get(),
1547 verification_results_.get(),
1548 &method_inliner_map_,
1549 compiler_kind_,
1550 instruction_set_,
1551 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001552 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001553 image_classes_.release(),
1554 compiled_classes_.release(),
1555 nullptr,
1556 thread_count_,
1557 dump_stats_,
1558 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001559 compiler_phases_timings_.get(),
1560 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001561 &dex_file_oat_filename_map_,
1562 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001563 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001564 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001565 }
1566
Jeff Hao436183f2016-01-12 16:36:50 -08001567 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 // ensure the references between the two are correct.
1569 //
1570 // Currently we have a memory layout that looks something like this:
1571 //
1572 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001573 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001574 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001575 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001576 // +--------------+
1577 // | alloc spaces |
1578 // +--------------+
1579 //
Jeff Hao436183f2016-01-12 16:36:50 -08001580 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001581 //
Jeff Hao436183f2016-01-12 16:36:50 -08001582 // 1. The images are expected to be loaded at an absolute address and
1583 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001584 //
Jeff Hao436183f2016-01-12 16:36:50 -08001585 // 2. There are absolute pointers from Methods in the images to their
1586 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001587 //
Jeff Hao436183f2016-01-12 16:36:50 -08001588 // 3. There are absolute pointers from the code in the oat files to Methods
1589 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001590 //
Jeff Hao436183f2016-01-12 16:36:50 -08001591 // 4. There are absolute pointers from code in the oat files to other code
1592 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001593 //
1594 // To get this all correct, we go through several steps.
1595 //
Jeff Hao436183f2016-01-12 16:36:50 -08001596 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001597 // the oat data size and code size. During this stage, we also set
1598 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001599 //
Jeff Hao436183f2016-01-12 16:36:50 -08001600 // 2. We prepare offsets for the objects in the images and calculate
1601 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001602 //
Jeff Hao436183f2016-01-12 16:36:50 -08001603 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001604 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001605 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 // can prepare the ELF headers and we then know the ELF memory segment
1607 // layout and we can now resolve all references. The compiler provides
1608 // LinkerPatch information in each CompiledMethod and we resolve these,
1609 // using the layout information and image object locations provided by
1610 // image writer, as we're writing the method code.
1611 //
Jeff Hao436183f2016-01-12 16:36:50 -08001612 // 4. We create the image files. They need to know where the oat files
1613 // will be loaded after itself. Originally oat files were simply
1614 // memory mapped so we could predict where their contents were based
1615 // on the file size. Now that they are ELF files, we need to inspect
1616 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 // where the oat header is located within.
1618 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001619 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001620 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001621 // load the .so at the desired location at runtime by offsetting the
1622 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001623 // TODO: Do this in step 3. We already know the layout there.
1624 //
1625 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1626 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001627
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001628 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1629 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001630 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1631 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001632 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1634
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001635 // Sync the data to the file, in case we did dex2dex transformations.
1636 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1637 if (!map->Sync()) {
1638 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1639 return false;
1640 }
1641 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001642
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001643 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001644 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001645 gc::Heap* const heap = Runtime::Current()->GetHeap();
1646 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001647 image_base_ = std::max(image_base_, RoundUp(
1648 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1649 kPageSize));
1650 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001651 // The non moving space is right after the oat file. Put the preferred app image location
1652 // right after the non moving space so that we ideally get a continuous immune region for
1653 // the GC.
1654 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1655 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001656 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1657 }
1658
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001659 image_writer_.reset(new ImageWriter(*driver_,
1660 image_base_,
1661 compiler_options_->GetCompilePic(),
1662 IsAppImage(),
1663 image_storage_mode_,
1664 oat_filenames_,
1665 dex_file_oat_filename_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001666
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001667 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001668 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1669 if (!image_writer_->PrepareImageAddressSpace()) {
1670 LOG(ERROR) << "Failed to prepare image address space.";
1671 return false;
1672 }
1673 }
1674
1675 {
1676 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001677 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001678 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001679 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1680 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001681
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1683 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files);
Vladimir Marko10c13562015-11-25 14:33:36 +00001684
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685 OutputStream*& rodata = rodata_[i];
1686 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001687 if (!oat_writer->WriteRodata(rodata)) {
1688 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1689 return false;
1690 }
1691 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001693
Jeff Haodcdc85b2015-12-04 14:06:18 -08001694 OutputStream* text = elf_writer->StartText();
1695 if (!oat_writer->WriteCode(text)) {
1696 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1697 return false;
1698 }
1699 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001700
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001701 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1702 image_file_location_oat_checksum_,
1703 image_file_location_oat_data_begin_,
1704 image_patch_delta_)) {
1705 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1706 return false;
1707 }
1708
Jeff Haodcdc85b2015-12-04 14:06:18 -08001709 elf_writer->SetBssSize(oat_writer->GetBssSize());
1710 elf_writer->WriteDynamicSection();
1711 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1712 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001713
Jeff Haodcdc85b2015-12-04 14:06:18 -08001714 if (!elf_writer->End()) {
1715 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1716 return false;
1717 }
1718
1719 // Flush the oat file.
1720 if (oat_files_[i] != nullptr) {
1721 if (oat_files_[i]->Flush() != 0) {
1722 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1723 oat_files_[i]->Erase();
1724 return false;
1725 }
1726 }
1727
1728 if (IsImage()) {
1729 // Update oat estimates.
Vladimir Markod8904a52016-01-29 16:27:27 +00001730 DCHECK(image_writer_ != nullptr);
1731 DCHECK_LT(i, oat_filenames_.size());
1732
1733 image_writer_->UpdateOatFile(oat_file.get(), oat_filenames_[i]);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001734 }
1735
1736 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001737
1738 oat_writer.reset();
1739 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001740 }
1741 }
1742
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001743 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001744 }
1745
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001746 // If we are compiling an image, invoke the image creation routine. Else just skip.
1747 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001748 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001749 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1750 if (!CreateImageFile()) {
1751 return false;
1752 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001753 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001754 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001755 return true;
1756 }
1757
Jeff Haodcdc85b2015-12-04 14:06:18 -08001758 // Create a copy from stripped to unstripped.
1759 bool CopyStrippedToUnstripped() {
1760 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1761 // If we don't want to strip in place, copy from stripped location to unstripped location.
1762 // We need to strip after image creation because FixupElf needs to use .strtab.
1763 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1764 // If the oat file is still open, flush it.
1765 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1766 if (!FlushCloseOatFile(i)) {
1767 return false;
1768 }
1769 }
1770
1771 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1772 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1773 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1774 size_t buffer_size = 8192;
1775 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1776 while (true) {
1777 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1778 if (bytes_read <= 0) {
1779 break;
1780 }
1781 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1782 CHECK(write_ok);
1783 }
1784 if (out->FlushCloseOrErase() != 0) {
1785 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1786 return false;
1787 }
1788 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1789 }
1790 }
1791 return true;
1792 }
1793
1794 bool FlushOatFiles() {
1795 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1796 for (size_t i = 0; i < oat_files_.size(); ++i) {
1797 if (oat_files_[i].get() != nullptr) {
1798 if (oat_files_[i]->Flush() != 0) {
1799 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1800 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001801 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001802 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001803 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001804 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001805 return true;
1806 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001807
Jeff Haodcdc85b2015-12-04 14:06:18 -08001808 bool FlushCloseOatFile(size_t i) {
1809 if (oat_files_[i].get() != nullptr) {
1810 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001811 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001812 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001813 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001814 }
1815 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001816 return true;
1817 }
1818
Jeff Haodcdc85b2015-12-04 14:06:18 -08001819 bool FlushCloseOatFiles() {
1820 bool result = true;
1821 for (size_t i = 0; i < oat_files_.size(); ++i) {
1822 result &= FlushCloseOatFile(i);
1823 }
1824 return result;
1825 }
1826
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001827 void DumpTiming() {
1828 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1829 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1830 }
1831 if (dump_passes_) {
1832 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1833 }
1834 }
1835
1836 CompilerOptions* GetCompilerOptions() const {
1837 return compiler_options_.get();
1838 }
1839
Andreas Gampe10e477d2014-11-19 12:57:42 -08001840 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001841 return IsAppImage() || IsBootImage();
1842 }
1843
1844 bool IsAppImage() const {
1845 return app_image_;
1846 }
1847
1848 bool IsBootImage() const {
1849 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001850 }
1851
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001852 bool IsHost() const {
1853 return is_host_;
1854 }
1855
Calin Juravle998c2162015-12-21 15:39:33 +02001856 bool UseProfileGuidedCompilation() const {
Calin Juravle877fd962016-01-05 14:29:29 +00001857 return !profile_files_.empty() || !profile_files_fd_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02001858 }
1859
1860 bool ProcessProfiles() {
1861 DCHECK(UseProfileGuidedCompilation());
1862 ProfileCompilationInfo* info = nullptr;
Calin Juravle877fd962016-01-05 14:29:29 +00001863 bool result = false;
1864 if (profile_files_.empty()) {
1865 DCHECK(!profile_files_fd_.empty());
1866 result = ProfileAssistant::ProcessProfiles(
1867 profile_files_fd_, reference_profile_files_fd_, &info);
1868 CloseAllFds(profile_files_fd_, "profile_files_fd_");
1869 CloseAllFds(reference_profile_files_fd_, "reference_profile_files_fd_");
1870 } else {
1871 result = ProfileAssistant::ProcessProfiles(
1872 profile_files_, reference_profile_files_, &info);
Calin Juravle998c2162015-12-21 15:39:33 +02001873 }
Calin Juravle877fd962016-01-05 14:29:29 +00001874
1875 profile_compilation_info_.reset(info);
1876
1877 return result;
Calin Juravle998c2162015-12-21 15:39:33 +02001878 }
1879
1880 bool ShouldCompileBasedOnProfiles() const {
1881 DCHECK(UseProfileGuidedCompilation());
1882 // If we are given profiles, compile only if we have new information.
1883 return profile_compilation_info_ != nullptr;
1884 }
1885
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001886 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001887 template <typename T>
1888 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1889 std::vector<T*> result;
1890 result.reserve(src.size());
1891 for (const std::unique_ptr<T>& t : src) {
1892 result.push_back(t.get());
1893 }
1894 return result;
1895 }
1896
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001897 std::string GetMultiImageBootClassPath() {
1898 DCHECK(IsBootImage());
1899 DCHECK_GT(oat_filenames_.size(), 1u);
1900 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1901 // too, but need to strip all path components (they will be re-established when loading).
1902 std::ostringstream bootcp_oss;
1903 bool first_bootcp = true;
1904 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1905 if (!first_bootcp) {
1906 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001907 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001908
1909 std::string dex_loc = dex_locations_[i];
1910 std::string image_filename = image_filenames_[i];
1911
1912 // Use the dex_loc path, but the image_filename name (without path elements).
1913 size_t dex_last_slash = dex_loc.rfind('/');
1914
1915 // npos is max(size_t). That makes this a bit ugly.
1916 size_t image_last_slash = image_filename.rfind('/');
1917 size_t image_last_at = image_filename.rfind('@');
1918 size_t image_last_sep = (image_last_slash == std::string::npos)
1919 ? image_last_at
1920 : (image_last_at == std::string::npos)
1921 ? std::string::npos
1922 : std::max(image_last_slash, image_last_at);
1923 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1924
1925 if (dex_last_slash == std::string::npos) {
1926 dex_loc = image_filename.substr(image_last_sep + 1);
1927 } else {
1928 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1929 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001930 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001931
1932 // Image filenames already end with .art, no need to replace.
1933
1934 bootcp_oss << dex_loc;
1935 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001936 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001937 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001938 }
1939
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001940 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1941 // This function is used only for apps and for an app we have exactly one oat file.
1942 DCHECK(!IsBootImage());
1943 DCHECK_EQ(oat_writers_.size(), 1u);
1944 std::vector<std::string> dex_files_canonical_locations;
1945 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1946 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001947 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001948
Vladimir Marko919f5532016-01-20 19:13:01 +00001949 std::vector<std::string> parsed;
1950 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001951 auto kept_it = std::remove_if(parsed.begin(),
1952 parsed.end(),
1953 [dex_files_canonical_locations](const std::string& location) {
1954 return ContainsElement(dex_files_canonical_locations,
1955 DexFile::GetDexCanonicalLocation(location.c_str()));
1956 });
1957 parsed.erase(kept_it, parsed.end());
1958 return parsed;
1959 }
1960
1961 // Opens requested class path files and appends them to opened_dex_files.
1962 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1963 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1964 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1965 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001966 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001967 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1968 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001969 }
1970 }
1971 }
1972
Vladimir Marko49b0f452015-12-10 13:49:19 +00001973 bool PrepareImageClasses() {
1974 // If --image-classes was specified, calculate the full list of classes to include in the image.
1975 if (image_classes_filename_ != nullptr) {
1976 image_classes_ =
1977 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1978 if (image_classes_ == nullptr) {
1979 return false;
1980 }
1981 } else if (IsBootImage()) {
1982 image_classes_.reset(new std::unordered_set<std::string>);
1983 }
1984 return true;
1985 }
1986
1987 bool PrepareCompiledClasses() {
1988 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1989 // image.
1990 if (compiled_classes_filename_ != nullptr) {
1991 compiled_classes_ =
1992 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1993 if (compiled_classes_ == nullptr) {
1994 return false;
1995 }
1996 } else {
1997 compiled_classes_.reset(nullptr); // By default compile everything.
1998 }
1999 return true;
2000 }
2001
2002 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2003 const char* classes_filename,
2004 const char* tag) {
2005 std::unique_ptr<std::unordered_set<std::string>> classes;
2006 std::string error_msg;
2007 if (zip_filename != nullptr) {
2008 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2009 } else {
2010 classes.reset(ReadImageClassesFromFile(classes_filename));
2011 }
2012 if (classes == nullptr) {
2013 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2014 << classes_filename << "': " << error_msg;
2015 }
2016 return classes;
2017 }
2018
2019 bool PrepareCompiledMethods() {
2020 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2021 if (compiled_methods_filename_ != nullptr) {
2022 std::string error_msg;
2023 if (compiled_methods_zip_filename_ != nullptr) {
2024 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2025 compiled_methods_filename_,
2026 nullptr, // No post-processing.
2027 &error_msg));
2028 } else {
2029 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2030 nullptr)); // No post-processing.
2031 }
2032 if (compiled_methods_.get() == nullptr) {
2033 LOG(ERROR) << "Failed to create list of compiled methods from '"
2034 << compiled_methods_filename_ << "': " << error_msg;
2035 return false;
2036 }
2037 } else {
2038 compiled_methods_.reset(nullptr); // By default compile everything.
2039 }
2040 return true;
2041 }
2042
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002043 void PruneNonExistentDexFiles() {
2044 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2045 size_t kept = 0u;
2046 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2047 if (!OS::FileExists(dex_filenames_[i])) {
2048 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2049 } else {
2050 dex_filenames_[kept] = dex_filenames_[i];
2051 dex_locations_[kept] = dex_locations_[i];
2052 ++kept;
2053 }
2054 }
2055 dex_filenames_.resize(kept);
2056 dex_locations_.resize(kept);
2057 }
2058
2059 bool AddDexFileSources() {
2060 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2061 if (zip_fd_ != -1) {
2062 DCHECK_EQ(oat_writers_.size(), 1u);
2063 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2064 return false;
2065 }
2066 } else if (oat_writers_.size() > 1u) {
2067 // Multi-image.
2068 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2069 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2070 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2071 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2072 return false;
2073 }
2074 }
2075 } else {
2076 DCHECK_EQ(oat_writers_.size(), 1u);
2077 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2078 DCHECK_NE(dex_filenames_.size(), 0u);
2079 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2080 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2081 return false;
2082 }
2083 }
2084 }
2085 return true;
2086 }
2087
2088 void CreateOatWriters() {
2089 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2090 elf_writers_.reserve(oat_files_.size());
2091 oat_writers_.reserve(oat_files_.size());
2092 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2093 elf_writers_.emplace_back(
2094 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2095 elf_writers_.back()->Start();
2096 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2097 }
2098 }
2099
Vladimir Marko49b0f452015-12-10 13:49:19 +00002100 void SaveDexInput() {
2101 for (size_t i = 0; i < dex_files_.size(); ++i) {
2102 const DexFile* dex_file = dex_files_[i];
2103 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2104 getpid(), i));
2105 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2106 if (tmp_file.get() == nullptr) {
2107 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2108 << ". Try: adb shell chmod 777 /data/local/tmp";
2109 continue;
2110 }
2111 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2112 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2113 UNUSED(tmp_file->Flush());
2114 UNUSED(tmp_file->Close());
2115 LOG(INFO) << "Wrote input to " << tmp_file_name;
2116 }
2117 }
2118
2119 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2120 RuntimeOptions raw_options;
2121 if (boot_image_filename_.empty()) {
2122 std::string boot_class_path = "-Xbootclasspath:";
2123 boot_class_path += Join(dex_filenames_, ':');
2124 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2125 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2126 boot_class_path_locations += Join(dex_locations_, ':');
2127 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2128 } else {
2129 std::string boot_image_option = "-Ximage:";
2130 boot_image_option += boot_image_filename_;
2131 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2132 }
2133 for (size_t i = 0; i < runtime_args_.size(); i++) {
2134 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2135 }
2136
2137 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2138 raw_options.push_back(
2139 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2140
2141 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2142 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2143 // have been stripped in preopting, anyways).
2144 if (!IsBootImage()) {
2145 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2146 }
2147 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2148 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2149 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002150 // Disable Hspace compaction to save heap size virtual space.
2151 // Only need disable Hspace for OOM becasue background collector is equal to
2152 // foreground collector by default for dex2oat.
2153 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002154
Andreas Gampeace0dc12016-01-20 13:33:13 -08002155 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2156 // force the free-list implementation for large objects.
2157 if (compiler_options_->IsForceDeterminism()) {
2158 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2159 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2160
2161 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2162 // compaction (done above) and ensure that neither foreground nor background collectors
2163 // are concurrent.
2164 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2165
2166 // To make identity hashcode deterministic, set a known seed.
2167 mirror::Object::SetHashCodeSeed(987654321U);
2168 }
2169
Vladimir Marko49b0f452015-12-10 13:49:19 +00002170 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2171 LOG(ERROR) << "Failed to parse runtime options";
2172 return false;
2173 }
2174 return true;
2175 }
2176
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002177 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002178 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2179 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002180 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002181 LOG(ERROR) << "Failed to create runtime";
2182 return false;
2183 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002184 runtime_.reset(Runtime::Current());
2185 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002186 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2187 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002188 if (!runtime_->HasCalleeSaveMethod(type)) {
2189 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002190 }
2191 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002192 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002193
2194 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2195 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002196 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002197
Vladimir Marko307dac92015-10-20 11:20:09 +01002198 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002199
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002200 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2201 // Runtime::Start, give it away now so that we don't starve GC.
2202 Thread* self = Thread::Current();
2203 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002204
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002206 }
2207
Jeff Haodcdc85b2015-12-04 14:06:18 -08002208 // 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 -08002209 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002210 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002211 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002212 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002213 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002214 image_filenames_.push_back(app_image_file_name_.c_str());
2215 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002216 if (!image_writer_->Write(app_image_fd_,
2217 image_filenames_,
2218 oat_fd_,
2219 oat_filenames_,
2220 oat_location_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002221 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002222 return false;
2223 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002224
Jeff Haodcdc85b2015-12-04 14:06:18 -08002225 // We need the OatDataBegin entries.
2226 std::map<const char*, uintptr_t> oat_data_begins;
2227 for (const char* oat_filename : oat_filenames_) {
2228 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2229 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002230 // Destroy ImageWriter before doing FixupElf.
2231 image_writer_.reset();
2232
Jeff Haodcdc85b2015-12-04 14:06:18 -08002233 for (const char* oat_filename : oat_filenames_) {
2234 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2235 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2236 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2237 if (oat_file.get() == nullptr) {
2238 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2239 return false;
2240 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002241
Jeff Haodcdc85b2015-12-04 14:06:18 -08002242 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002243
Jeff Haodcdc85b2015-12-04 14:06:18 -08002244 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2245 oat_file->Erase();
2246 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2247 return false;
2248 }
2249
2250 if (oat_file->FlushCloseOrErase()) {
2251 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2252 return false;
2253 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002254 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002255 }
2256
2257 return true;
2258 }
2259
2260 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002261 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2262 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002263 std::function<std::string(const char*)> process = DotToDescriptor;
2264 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265 }
2266
2267 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002268 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002269 const char* zip_filename,
2270 const char* image_classes_filename,
2271 std::string* error_msg) {
2272 std::function<std::string(const char*)> process = DotToDescriptor;
2273 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2274 }
2275
2276 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2277 // the given function.
2278 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2279 const char* input_filename, std::function<std::string(const char*)>* process) {
2280 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2281 if (input_file.get() == nullptr) {
2282 LOG(ERROR) << "Failed to open input file " << input_filename;
2283 return nullptr;
2284 }
2285 std::unique_ptr<std::unordered_set<std::string>> result(
2286 ReadCommentedInputStream(*input_file, process));
2287 input_file->close();
2288 return result.release();
2289 }
2290
2291 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2292 // Post-process each line with the given function.
2293 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002294 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002295 const char* input_filename,
2296 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002297 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002298 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2299 if (zip_archive.get() == nullptr) {
2300 return nullptr;
2301 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002302 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002303 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002304 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002305 zip_filename, error_msg->c_str());
2306 return nullptr;
2307 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002308 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2309 input_filename,
2310 error_msg));
2311 if (input_file.get() == nullptr) {
2312 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002313 zip_filename, error_msg->c_str());
2314 return nullptr;
2315 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002316 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2317 input_file->Size());
2318 std::istringstream input_stream(input_string);
2319 return ReadCommentedInputStream(input_stream, process);
2320 }
2321
2322 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2323 // with the given function.
2324 static std::unordered_set<std::string>* ReadCommentedInputStream(
2325 std::istream& in_stream,
2326 std::function<std::string(const char*)>* process) {
2327 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2328 new std::unordered_set<std::string>);
2329 while (in_stream.good()) {
2330 std::string dot;
2331 std::getline(in_stream, dot);
2332 if (StartsWith(dot, "#") || dot.empty()) {
2333 continue;
2334 }
2335 if (process != nullptr) {
2336 std::string descriptor((*process)(dot.c_str()));
2337 image_classes->insert(descriptor);
2338 } else {
2339 image_classes->insert(dot);
2340 }
2341 }
2342 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002343 }
2344
Mathieu Chartier49285c52014-12-02 15:43:48 -08002345 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002346 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2347 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002348 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002349 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002350 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002351 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002352 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2353 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002354 }
2355
Jeff Haodcdc85b2015-12-04 14:06:18 -08002356 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2357 std::string res(image_filename);
2358 size_t last_slash = res.rfind('/');
2359 if (last_slash == std::string::npos || last_slash == 0) {
2360 return res;
2361 }
2362 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2363 if (penultimate_slash == std::string::npos) {
2364 return res;
2365 }
2366 // Check that the string in-between is the expected one.
2367 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2368 GetInstructionSetString(isa)) {
2369 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2370 return res;
2371 }
2372 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2373 }
2374
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002375 std::unique_ptr<CompilerOptions> compiler_options_;
2376 Compiler::Kind compiler_kind_;
2377
2378 InstructionSet instruction_set_;
2379 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2380
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002381 uint32_t image_file_location_oat_checksum_;
2382 uintptr_t image_file_location_oat_data_begin_;
2383 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002384 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2385
Vladimir Marko307dac92015-10-20 11:20:09 +01002386 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002387
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002388 DexFileToMethodInlinerMap method_inliner_map_;
2389 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2390
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002391 std::unique_ptr<Runtime> runtime_;
2392
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002393 // Ownership for the class path files.
2394 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2395
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002396 size_t thread_count_;
2397 uint64_t start_ns_;
2398 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002399 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002400 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002401 std::vector<const char*> oat_filenames_;
2402 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002403 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002404 std::vector<const char*> dex_filenames_;
2405 std::vector<const char*> dex_locations_;
2406 int zip_fd_;
2407 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002408 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002409 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002410 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 uintptr_t image_base_;
2412 const char* image_classes_zip_filename_;
2413 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002414 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002415 const char* compiled_classes_zip_filename_;
2416 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002417 const char* compiled_methods_zip_filename_;
2418 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002419 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2420 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002421 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002422 bool app_image_;
2423 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002424 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002425 bool is_host_;
2426 std::string android_root_;
2427 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002428 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002429 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002430 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002431
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002432 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2433 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2434 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002435 std::unique_ptr<ImageWriter> image_writer_;
2436 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002437
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002438 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2439 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2440
Vladimir Marko47496c22016-01-27 16:15:08 +00002441 std::vector<const DexFile*> no_inline_from_dex_files_;
2442
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002443 std::vector<std::string> verbose_methods_;
2444 bool dump_stats_;
2445 bool dump_passes_;
2446 bool dump_timing_;
2447 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002448 std::string swap_file_name_;
2449 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002450 std::string app_image_file_name_;
2451 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002452 std::vector<std::string> profile_files_;
2453 std::vector<std::string> reference_profile_files_;
Calin Juravle877fd962016-01-05 14:29:29 +00002454 std::vector<uint32_t> profile_files_fd_;
2455 std::vector<uint32_t> reference_profile_files_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002456 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002457 TimingLogger* timings_;
2458 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002459 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2460 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2461
2462 // Backing storage.
2463 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002464
Andreas Gampeace0dc12016-01-20 13:33:13 -08002465 // See CompilerOptions.force_determinism_.
2466 bool force_determinism_;
2467
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002468 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2469};
2470
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002471static void b13564922() {
2472#if defined(__linux__) && defined(__arm__)
2473 int major, minor;
2474 struct utsname uts;
2475 if (uname(&uts) != -1 &&
2476 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2477 ((major < 3) || ((major == 3) && (minor < 4)))) {
2478 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2479 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2480 int old_personality = personality(0xffffffff);
2481 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2482 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2483 if (new_personality == -1) {
2484 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2485 }
2486 }
2487 }
2488#endif
2489}
2490
Andreas Gampe10e477d2014-11-19 12:57:42 -08002491static int CompileImage(Dex2Oat& dex2oat) {
2492 dex2oat.Compile();
2493
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002494 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002495 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002496 return EXIT_FAILURE;
2497 }
2498
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002499 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2500 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2501 // image writer will require this fd to generate the image.
2502 if (dex2oat.ShouldKeepOatFileOpen()) {
2503 if (!dex2oat.FlushOatFiles()) {
2504 return EXIT_FAILURE;
2505 }
2506 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002507 return EXIT_FAILURE;
2508 }
2509
Jeff Haodcdc85b2015-12-04 14:06:18 -08002510 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002511 if (!dex2oat.HandleImage()) {
2512 return EXIT_FAILURE;
2513 }
2514
2515 // When given --host, finish early without stripping.
2516 if (dex2oat.IsHost()) {
2517 dex2oat.DumpTiming();
2518 return EXIT_SUCCESS;
2519 }
2520
Jeff Haodcdc85b2015-12-04 14:06:18 -08002521 // Copy stripped to unstripped location, if necessary.
2522 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002523 return EXIT_FAILURE;
2524 }
2525
Jeff Haodcdc85b2015-12-04 14:06:18 -08002526 // FlushClose again, as stripping might have re-opened the oat files.
2527 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002528 return EXIT_FAILURE;
2529 }
2530
2531 dex2oat.DumpTiming();
2532 return EXIT_SUCCESS;
2533}
2534
2535static int CompileApp(Dex2Oat& dex2oat) {
2536 dex2oat.Compile();
2537
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002538 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002539 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002540 return EXIT_FAILURE;
2541 }
2542
Jeff Haodcdc85b2015-12-04 14:06:18 -08002543 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002544 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002545
2546 // When given --host, finish early without stripping.
2547 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002548 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002549 return EXIT_FAILURE;
2550 }
2551
2552 dex2oat.DumpTiming();
2553 return EXIT_SUCCESS;
2554 }
2555
Jeff Haodcdc85b2015-12-04 14:06:18 -08002556 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2557 // stripped versions. If this is given, we expect to be able to open writable files by name.
2558 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002559 return EXIT_FAILURE;
2560 }
2561
Jeff Haodcdc85b2015-12-04 14:06:18 -08002562 // Flush and close the files.
2563 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002564 return EXIT_FAILURE;
2565 }
2566
2567 dex2oat.DumpTiming();
2568 return EXIT_SUCCESS;
2569}
2570
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002571static int dex2oat(int argc, char** argv) {
2572 b13564922();
2573
2574 TimingLogger timings("compiler", false, false);
2575
2576 Dex2Oat dex2oat(&timings);
2577
2578 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2579 dex2oat.ParseArgs(argc, argv);
2580
Calin Juravle998c2162015-12-21 15:39:33 +02002581 // Process profile information and assess if we need to do a profile guided compilation.
2582 // This operation involves I/O.
2583 if (dex2oat.UseProfileGuidedCompilation()) {
2584 if (dex2oat.ProcessProfiles()) {
2585 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2586 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2587 return EXIT_SUCCESS;
2588 }
2589 } else {
2590 LOG(WARNING) << "Failed to process profile files";
2591 return EXIT_FAILURE;
2592 }
2593 }
2594
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002595 // Check early that the result of compilation can be written
2596 if (!dex2oat.OpenFile()) {
2597 return EXIT_FAILURE;
2598 }
2599
Andreas Gampe046c7062015-05-18 23:22:54 -07002600 // Print the complete line when any of the following is true:
2601 // 1) Debug build
2602 // 2) Compiling an image
2603 // 3) Compiling with --host
2604 // 4) Compiling on the host (not a target build)
2605 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002606 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002607 LOG(INFO) << CommandLine();
2608 } else {
2609 LOG(INFO) << StrippedCommandLine();
2610 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002611
2612 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002613 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002614 return EXIT_FAILURE;
2615 }
2616
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002617 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002618 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002619 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002620 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002621 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002622 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002623
2624 dex2oat.Shutdown();
2625 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002626}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002627} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002628
2629int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002630 int result = art::dex2oat(argc, argv);
2631 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2632 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2633 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002634 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002635 exit(result);
2636 }
2637 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002638}