blob: 9427eaf3d824e0ebb3c17103cab93d0fc88d31e2 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Ian Rogersd582fa42014-11-05 23:46:43 -080038#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080039#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000040#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000051#include "debug/method_debug_info.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Ian Rogerse63db272014-07-15 15:36:11 -070053#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000054#include "dex/quick_compiler_callbacks.h"
55#include "dex/verification_results.h"
56#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080058#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020066#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "leb128.h"
Vladimir Marko944da602016-02-19 12:27:55 +000068#include "linker/multi_oat_relative_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "mirror/class-inl.h"
70#include "mirror/class_loader.h"
71#include "mirror/object-inl.h"
72#include "mirror/object_array-inl.h"
73#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070074#include "os.h"
Calin Juravle998c2162015-12-21 15:39:33 +020075#include "profile_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000077#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "ScopedLocalRef.h"
79#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070080#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070081#include "well_known_classes.h"
82#include "zip_archive.h"
83
84namespace art {
85
Brian Carlstrom6449c622014-02-10 23:48:36 -080086static int original_argc;
87static char** original_argv;
88
89static std::string CommandLine() {
90 std::vector<std::string> command;
91 for (int i = 0; i < original_argc; ++i) {
92 command.push_back(original_argv[i]);
93 }
94 return Join(command, ' ');
95}
96
Andreas Gampe046c7062015-05-18 23:22:54 -070097// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
98// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
99// locations are all staged).
100static std::string StrippedCommandLine() {
101 std::vector<std::string> command;
102
103 // Do a pre-pass to look for zip-fd.
104 bool saw_zip_fd = false;
105 for (int i = 0; i < original_argc; ++i) {
106 if (StartsWith(original_argv[i], "--zip-fd=")) {
107 saw_zip_fd = true;
108 break;
109 }
110 }
111
112 // Now filter out things.
113 for (int i = 0; i < original_argc; ++i) {
114 // All runtime-arg parameters are dropped.
115 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
116 i++; // Drop the next part, too.
117 continue;
118 }
119
120 // Any instruction-setXXX is dropped.
121 if (StartsWith(original_argv[i], "--instruction-set")) {
122 continue;
123 }
124
125 // The boot image is dropped.
126 if (StartsWith(original_argv[i], "--boot-image=")) {
127 continue;
128 }
129
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800130 // The image format is dropped.
131 if (StartsWith(original_argv[i], "--image-format=")) {
132 continue;
133 }
134
Andreas Gampe046c7062015-05-18 23:22:54 -0700135 // This should leave any dex-file and oat-file options, describing what we compiled.
136
137 // However, we prefer to drop this when we saw --zip-fd.
138 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700139 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700140 if (StartsWith(original_argv[i], "--zip-") ||
141 StartsWith(original_argv[i], "--dex-") ||
142 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700143 StartsWith(original_argv[i], "--swap-") ||
144 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700145 continue;
146 }
147 }
148
149 command.push_back(original_argv[i]);
150 }
151
152 // Construct the final output.
153 if (command.size() <= 1U) {
154 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
155 return "Starting dex2oat.";
156 }
157 return Join(command, ' ');
158}
159
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160static void UsageErrorV(const char* fmt, va_list ap) {
161 std::string error;
162 StringAppendV(&error, fmt, ap);
163 LOG(ERROR) << error;
164}
165
166static void UsageError(const char* fmt, ...) {
167 va_list ap;
168 va_start(ap, fmt);
169 UsageErrorV(fmt, ap);
170 va_end(ap);
171}
172
Andreas Gampe794ad762015-02-23 08:12:24 -0800173NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 va_list ap;
175 va_start(ap, fmt);
176 UsageErrorV(fmt, ap);
177 va_end(ap);
178
Brian Carlstrom6449c622014-02-10 23:48:36 -0800179 UsageError("Command: %s", CommandLine().c_str());
180
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 UsageError("Usage: dex2oat [options]...");
182 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100183 UsageError(" -j<number>: specifies the number of threads used for compilation.");
184 UsageError(" Default is the number of detected hardware threads available on the");
185 UsageError(" host system.");
186 UsageError(" Example: -j12");
187 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700188 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 UsageError(" Example: --dex-file=/system/framework/core.jar");
190 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700191 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
192 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
193 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
194 UsageError(" --dex-location=/system/framework/core.jar");
195 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
197 UsageError(" containing a classes.dex file to compile.");
198 UsageError(" Example: --zip-fd=5");
199 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700200 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
201 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
203 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800204 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 UsageError(" Example: --oat-file=/system/framework/boot.oat");
206 UsageError("");
207 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900208 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError("");
210 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
211 UsageError(" to the file descriptor specified by --oat-fd.");
212 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
213 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
216 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 UsageError(" Example: --image=/system/framework/boot.art");
219 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220 UsageError(" --image-format=(uncompressed|lz4):");
221 UsageError(" Which format to store the image.");
222 UsageError(" Example: --image-format=lz4");
223 UsageError(" Default: uncompressed");
224 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
226 UsageError(" Example: --image=frameworks/base/preloaded-classes");
227 UsageError("");
228 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
229 UsageError(" Example: --base=0x50000000");
230 UsageError("");
231 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000232 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000234 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000235 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError("");
237 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
238 UsageError(" Example: --android-root=out/host/linux-x86");
239 UsageError(" Default: $ANDROID_ROOT");
240 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800241 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700242 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 UsageError(" Example: --instruction-set=x86");
244 UsageError(" Default: arm");
245 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700246 UsageError(" --instruction-set-features=...,: Specify instruction set features");
247 UsageError(" Example: --instruction-set-features=div");
248 UsageError(" Default: default");
249 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700250 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
251 UsageError(" Default: disabled");
252 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800253 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800255 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100256 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100258 UsageError(" --compiler-filter="
259 "(verify-none"
260 "|interpret-only"
261 "|space"
262 "|balanced"
263 "|speed"
264 "|everything"
265 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700266 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800268 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800269 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800270 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
271 UsageError(" method for compiler filter tuning.");
272 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
273 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
274 UsageError("");
275 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
276 UsageError(" method for compiler filter tuning.");
277 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
278 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
279 UsageError("");
280 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
281 UsageError(" method for compiler filter tuning.");
282 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
283 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
284 UsageError("");
285 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
286 UsageError(" method for compiler filter tuning.");
287 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
288 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
289 UsageError("");
290 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
291 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700292 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
293 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800294 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
295 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
296 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100297 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
298 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100299 UsageError(" Has priority over the --compiler-filter option. Intended for ");
300 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100301 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
302 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
303 UsageError("");
304 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
305 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100306 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
307 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100308 UsageError(" Example: --inline-max-code-units=%d",
309 CompilerOptions::kDefaultInlineMaxCodeUnits);
310 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
311 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700312 UsageError(" --dump-timing: display a breakdown of where time was spent");
313 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700314 UsageError(" --include-patch-information: Include patching information so the generated code");
315 UsageError(" can have its base address moved without full recompilation.");
316 UsageError("");
317 UsageError(" --no-include-patch-information: Do not include patching information.");
318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" -g");
320 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
321 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000322 UsageError(" If used without --native-debuggable, it will be best-effort only.");
323 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700324 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100325 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100326 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000327 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
328 UsageError(" debug information necessary to print backtraces. (disabled by default)");
329 UsageError("");
330 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
331 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000332 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000333 UsageError("");
334 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
335 UsageError(" Implies --debuggable.");
336 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
338 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
339 UsageError(" Use a separate --runtime-arg switch for each argument.");
340 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700341 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000342 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200343 UsageError(" Can be specified multiple time, in which case the data from the different");
344 UsageError(" profiles will be aggregated.");
345 UsageError("");
346 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
347 UsageError(" compiling. The data in this file will be compared with the data in the");
348 UsageError(" associated --profile-file and the compilation will proceed only if there is");
349 UsageError(" a significant difference (--reference-profile-file is paired with");
350 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
351 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
352 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700353 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000354 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
355 UsageError(" Cannot be used together with --profile-file.");
356 UsageError("");
357 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
358 UsageError(" accepts a file descriptor. Cannot be used together with");
359 UsageError(" --reference-profile-file.");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700360 UsageError(" --print-pass-names: print a list of pass names");
361 UsageError("");
362 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
363 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
364 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700365 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
366 "with the setting.");
367 UsageError(" Will print default if no overridden setting exists.");
368 UsageError("");
369 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
370 "Pass2Name:Pass2OptionName:Pass2Option#");
371 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
372 UsageError(" Separator used between options is a comma.");
373 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800374 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
375 UsageError(" Example: --swap-file=/data/tmp/swap.001");
376 UsageError("");
377 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
378 UsageError(" Example: --swap-fd=10");
379 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700380 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
381 UsageError(" Example: --app-image-fd=10");
382 UsageError("");
383 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
384 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
385 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800386 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
387 "input dex file.");
388 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000389 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
390 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
391 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
392 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393 std::cerr << "See log for usage error information\n";
394 exit(EXIT_FAILURE);
395}
396
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397// The primary goal of the watchdog is to prevent stuck build servers
398// during development when fatal aborts lead to a cascade of failures
399// that result in a deadlock.
400class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800401// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402#undef CHECK_PTHREAD_CALL
403#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
404 do { \
405 int rc = call args; \
406 if (rc != 0) { \
407 errno = rc; \
408 std::string message(# call); \
409 message += " failed for "; \
410 message += reason; \
411 Fatal(message); \
412 } \
413 } while (false)
414
415 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700416 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700417 is_watch_dog_enabled_ = is_watch_dog_enabled;
418 if (!is_watch_dog_enabled_) {
419 return;
420 }
421 shutting_down_ = false;
422 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
427 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
428 }
429 ~WatchDog() {
430 if (!is_watch_dog_enabled_) {
431 return;
432 }
433 const char* reason = "dex2oat watch dog thread shutdown";
434 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
435 shutting_down_ = true;
436 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
437 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
438
Kenny Root51316382014-05-13 14:59:37 -0700439 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440
441 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
442 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
443 }
444
445 private:
446 static void* CallBack(void* arg) {
447 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
448 ::art::SetThreadName("dex2oat watch dog");
449 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700450 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 }
452
Andreas Gampe794ad762015-02-23 08:12:24 -0800453 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700454 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
455 // it's rather easy to hang in unwinding.
456 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
457 // logcat logging or stderr output.
458 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 exit(1);
460 }
461
462 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
464 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700465 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466 timespec timeout_ts;
467 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
468 const char* reason = "dex2oat watch dog thread waiting";
469 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
470 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800471 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700472 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700473 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
474 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 } else if (rc != 0) {
476 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
477 strerror(errno)));
478 Fatal(message.c_str());
479 }
480 }
481 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
482 }
483
484 // 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 -0700485 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700486 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800487
Andreas Gampe540138a2015-09-14 15:34:38 -0700488 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
489 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
490 // itself before that watchdog would take down the system server.
491 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700492
493 bool is_watch_dog_enabled_;
494 bool shutting_down_;
495 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
496 pthread_mutex_t mutex_;
497 pthread_cond_t cond_;
498 pthread_attr_t attr_;
499 pthread_t pthread_;
500};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800502static constexpr size_t kMinDexFilesForSwap = 2;
503static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
504
505static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
506 if (is_image) {
507 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
508 return false;
509 }
510 if (dex_files.size() < kMinDexFilesForSwap) {
511 // If there are less dex files than the threshold, assume it's gonna be fine.
512 return false;
513 }
514 size_t dex_files_size = 0;
515 for (const auto* dex_file : dex_files) {
516 dex_files_size += dex_file->GetHeader().file_size_;
517 }
518 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
519}
520
Calin Juravle877fd962016-01-05 14:29:29 +0000521static void CloseAllFds(const std::vector<uint32_t>& fds, const char* descriptor) {
522 for (size_t i = 0; i < fds.size(); i++) {
523 if (close(fds[i]) < 0) {
524 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
525 }
526 }
527}
528
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800529class Dex2Oat FINAL {
530 public:
531 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100532 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800533 instruction_set_(kRuntimeISA),
534 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 image_file_location_oat_checksum_(0),
536 image_file_location_oat_data_begin_(0),
537 image_patch_delta_(0),
538 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700539 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800540 method_inliner_map_(),
541 runtime_(nullptr),
542 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
543 start_ns_(NanoTime()),
544 oat_fd_(-1),
545 zip_fd_(-1),
546 image_base_(0U),
547 image_classes_zip_filename_(nullptr),
548 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800549 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800550 compiled_classes_zip_filename_(nullptr),
551 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700552 compiled_methods_zip_filename_(nullptr),
553 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700554 app_image_(false),
555 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800556 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800557 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000558 class_loader_(nullptr),
559 elf_writers_(),
560 oat_writers_(),
561 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000562 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700563 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000564 opened_dex_files_maps_(),
565 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000566 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800567 dump_stats_(false),
568 dump_passes_(false),
569 dump_timing_(false),
570 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800571 swap_fd_(-1),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800572 app_image_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800573 timings_(timings),
574 force_determinism_(false) {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800575
576 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800577 // Log completion time before deleting the runtime_, because this accesses
578 // the runtime.
579 LogCompletionTime();
580
Vladimir Marko307dac92015-10-20 11:20:09 +0100581 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
582 // We want to just exit on non-debug builds, not bringing the runtime down
583 // in an orderly fashion. So release the following fields.
584 driver_.release();
585 image_writer_.release();
586 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
587 dex_file.release();
588 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000589 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
590 map.release();
591 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800592 for (std::unique_ptr<File>& oat_file : oat_files_) {
593 oat_file.release();
594 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100595 runtime_.release();
596 verification_results_.release();
597 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100598 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700599 }
600
Roland Levillain9ec5e222015-08-17 20:18:41 +0100601 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800602 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800603 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800604 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000605 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800606 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100607 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800608
Roland Levillain9ec5e222015-08-17 20:18:41 +0100609 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000610 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100611 }
612
613 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000614 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100615 }
616
Calin Juravle877fd962016-01-05 14:29:29 +0000617 void ParseFdForCollection(const StringPiece& option,
618 const char* arg_name,
619 std::vector<uint32_t>* fds) {
620 uint32_t fd;
621 ParseUintOption(option, arg_name, &fd, Usage);
622 fds->push_back(fd);
623 }
624
Roland Levillain9ec5e222015-08-17 20:18:41 +0100625 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000626 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100627 }
628
629 void ParseBase(const StringPiece& option) {
630 DCHECK(option.starts_with("--base="));
631 const char* image_base_str = option.substr(strlen("--base=")).data();
632 char* end;
633 image_base_ = strtoul(image_base_str, &end, 16);
634 if (end == image_base_str || *end != '\0') {
635 Usage("Failed to parse hexadecimal value for option %s", option.data());
636 }
637 }
638
639 void ParseInstructionSet(const StringPiece& option) {
640 DCHECK(option.starts_with("--instruction-set="));
641 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
642 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
643 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
644 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
645 buf.get()[instruction_set_str.length()] = 0;
646 instruction_set_ = GetInstructionSetFromString(buf.get());
647 // arm actually means thumb2.
648 if (instruction_set_ == InstructionSet::kArm) {
649 instruction_set_ = InstructionSet::kThumb2;
650 }
651 }
652
653 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
654 DCHECK(option.starts_with("--instruction-set-variant="));
655 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
656 instruction_set_features_.reset(
657 InstructionSetFeatures::FromVariant(
658 instruction_set_, str.as_string(), &parser_options->error_msg));
659 if (instruction_set_features_.get() == nullptr) {
660 Usage("%s", parser_options->error_msg.c_str());
661 }
662 }
663
664 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
665 DCHECK(option.starts_with("--instruction-set-features="));
666 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
667 if (instruction_set_features_.get() == nullptr) {
668 instruction_set_features_.reset(
669 InstructionSetFeatures::FromVariant(
670 instruction_set_, "default", &parser_options->error_msg));
671 if (instruction_set_features_.get() == nullptr) {
672 Usage("Problem initializing default instruction set features variant: %s",
673 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800675 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100676 instruction_set_features_.reset(
677 instruction_set_features_->AddFeaturesFromString(str.as_string(),
678 &parser_options->error_msg));
679 if (instruction_set_features_.get() == nullptr) {
680 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
681 }
682 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800683
Roland Levillain9ec5e222015-08-17 20:18:41 +0100684 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
685 DCHECK(option.starts_with("--compiler-backend="));
686 parser_options->requested_specific_compiler = true;
687 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
688 if (backend_str == "Quick") {
689 compiler_kind_ = Compiler::kQuick;
690 } else if (backend_str == "Optimizing") {
691 compiler_kind_ = Compiler::kOptimizing;
692 } else {
693 Usage("Unknown compiler backend: %s", backend_str.data());
694 }
695 }
696
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800697 void ParseImageFormat(const StringPiece& option) {
698 const StringPiece substr("--image-format=");
699 DCHECK(option.starts_with(substr));
700 const StringPiece format_str = option.substr(substr.length());
701 if (format_str == "lz4") {
702 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
703 } else if (format_str == "uncompressed") {
704 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
705 } else {
706 Usage("Unknown image format: %s", format_str.data());
707 }
708 }
709
Jeff Hao436183f2016-01-12 16:36:50 -0800710 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800711 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700712 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
713
714 if (IsAppImage() && IsBootImage()) {
715 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
716 }
717
718 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100719 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000720 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000721 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000722
Jeff Haodcdc85b2015-12-04 14:06:18 -0800723 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800724 Usage("Output must be supplied with either --oat-file or --oat-fd");
725 }
726
Jeff Haodcdc85b2015-12-04 14:06:18 -0800727 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 Usage("--oat-file should not be used with --oat-fd");
729 }
730
Roland Levillain9ec5e222015-08-17 20:18:41 +0100731 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800732 Usage("--oat-symbols should not be used with --oat-fd");
733 }
734
Roland Levillain9ec5e222015-08-17 20:18:41 +0100735 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800736 Usage("--oat-symbols should not be used with --host");
737 }
738
Jeff Haodcdc85b2015-12-04 14:06:18 -0800739 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800740 Usage("--oat-fd should not be used with --image");
741 }
742
Jeff Haodcdc85b2015-12-04 14:06:18 -0800743 if (!parser_options->oat_symbols.empty() &&
744 parser_options->oat_symbols.size() != oat_filenames_.size()) {
745 Usage("--oat-file arguments do not match --oat-symbols arguments");
746 }
747
748 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
749 Usage("--oat-file arguments do not match --image arguments");
750 }
751
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800752 if (android_root_.empty()) {
753 const char* android_root_env_var = getenv("ANDROID_ROOT");
754 if (android_root_env_var == nullptr) {
755 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700756 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800757 android_root_ += android_root_env_var;
758 }
759
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700760 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100761 parser_options->boot_image_filename += android_root_;
762 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800763 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100764 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000765 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800766 }
767
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700768 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800769 Usage("--image-classes should only be used with --image");
770 }
771
Vladimir Marko49b0f452015-12-10 13:49:19 +0000772 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800773 Usage("--image-classes should not be used with --boot-image");
774 }
775
776 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
777 Usage("--image-classes-zip should be used with --image-classes");
778 }
779
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700780 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800781 Usage("--compiled-classes should only be used with --image");
782 }
783
Vladimir Marko49b0f452015-12-10 13:49:19 +0000784 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800785 Usage("--compiled-classes should not be used with --boot-image");
786 }
787
788 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
789 Usage("--compiled-classes-zip should be used with --compiled-classes");
790 }
791
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800792 if (dex_filenames_.empty() && zip_fd_ == -1) {
793 Usage("Input must be supplied with either --dex-file or --zip-fd");
794 }
795
796 if (!dex_filenames_.empty() && zip_fd_ != -1) {
797 Usage("--dex-file should not be used with --zip-fd");
798 }
799
800 if (!dex_filenames_.empty() && !zip_location_.empty()) {
801 Usage("--dex-file should not be used with --zip-location");
802 }
803
804 if (dex_locations_.empty()) {
805 for (const char* dex_file_name : dex_filenames_) {
806 dex_locations_.push_back(dex_file_name);
807 }
808 } else if (dex_locations_.size() != dex_filenames_.size()) {
809 Usage("--dex-location arguments do not match --dex-file arguments");
810 }
811
Jeff Haodcdc85b2015-12-04 14:06:18 -0800812 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
813 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
814 Usage("--oat-file arguments must be singular or match --dex-file arguments");
815 }
816 }
817
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800818 if (zip_fd_ != -1 && zip_location_.empty()) {
819 Usage("--zip-location should be supplied with --zip-fd");
820 }
821
Vladimir Marko49b0f452015-12-10 13:49:19 +0000822 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800823 if (image_base_ == 0) {
824 Usage("Non-zero --base not specified");
825 }
826 }
827
Calin Juravle877fd962016-01-05 14:29:29 +0000828 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
829 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
830 }
Calin Juravle998c2162015-12-21 15:39:33 +0200831 if (!profile_files_.empty()) {
832 if (!reference_profile_files_.empty() &&
833 (reference_profile_files_.size() != profile_files_.size())) {
834 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
835 }
Calin Juravle877fd962016-01-05 14:29:29 +0000836 } else if (!reference_profile_files_.empty()) {
837 Usage("--reference-profile-file should only be supplied with --profile-file");
838 }
839 if (!profile_files_fd_.empty()) {
840 if (!reference_profile_files_fd_.empty() &&
841 (reference_profile_files_fd_.size() != profile_files_fd_.size())) {
842 Usage("If specified, --reference-profile-file-fd should match the number",
843 " of --profile-file-fd.");
844 }
845 } else if (!reference_profile_files_fd_.empty()) {
846 Usage("--reference-profile-file-fd should only be supplied with --profile-file-fd");
Calin Juravle998c2162015-12-21 15:39:33 +0200847 }
848
Roland Levillain9ec5e222015-08-17 20:18:41 +0100849 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800850 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800851 }
852
853 // If no instruction set feature was given, use the default one for the target
854 // instruction set.
855 if (instruction_set_features_.get() == nullptr) {
856 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100857 InstructionSetFeatures::FromVariant(
858 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800859 if (instruction_set_features_.get() == nullptr) {
860 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100861 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800862 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800863 }
864
865 if (instruction_set_ == kRuntimeISA) {
866 std::unique_ptr<const InstructionSetFeatures> runtime_features(
867 InstructionSetFeatures::FromCppDefines());
868 if (!instruction_set_features_->Equals(runtime_features.get())) {
869 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
870 << *instruction_set_features_ << ") and those of dex2oat executable ("
871 << *runtime_features <<") for the command line:\n"
872 << CommandLine();
873 }
874 }
875
Roland Levillaina215b952015-08-07 11:38:32 +0100876 // It they are not set, use default values for inlining settings.
877 // TODO: We should rethink the compiler filter. We mostly save
878 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000879 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
880 compiler_options_->inline_depth_limit_ =
881 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100882 // Implementation of the space filter: limit inlining depth.
883 ? CompilerOptions::kSpaceFilterInlineDepthLimit
884 : CompilerOptions::kDefaultInlineDepthLimit;
885 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000886 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
887 compiler_options_->inline_max_code_units_ =
888 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100889 // Implementation of the space filter: limit inlining max code units.
890 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
891 : CompilerOptions::kDefaultInlineMaxCodeUnits;
892 }
893
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800894 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800895 // Set the compilation target's implicit checks options.
896 switch (instruction_set_) {
897 case kArm:
898 case kThumb2:
899 case kArm64:
900 case kX86:
901 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700902 case kMips:
903 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000904 compiler_options_->implicit_null_checks_ = true;
905 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800906 break;
907
908 default:
909 // Defaults are correct.
910 break;
911 }
912
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000913 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800914
Jeff Hao436183f2016-01-12 16:36:50 -0800915 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800916 Usage("--multi-image can only be used when creating boot images");
917 }
Jeff Hao436183f2016-01-12 16:36:50 -0800918 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800919 Usage("--multi-image cannot be used with multiple image names");
920 }
921
922 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
923 if (!kIsTargetBuild && IsBootImage()) {
924 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800925 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800926 }
927 }
928
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800929 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100930 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800931 watchdog_.reset(new WatchDog(true));
932 }
933
934 // Fill some values into the key-value store for the oat header.
935 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800936
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800937 // Automatically force determinism for the boot image in a host build if the default GC is CMS
938 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
939 // one by passing the option `-Xgc:nonconcurrent` (see below).
940 if (!kIsTargetBuild && IsBootImage()) {
941 if (SupportsDeterministicCompilation()) {
942 force_determinism_ = true;
943 } else {
944 LOG(WARNING) << "Deterministic compilation is disabled.";
945 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800946 }
947 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100948 }
949
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800950 static bool SupportsDeterministicCompilation() {
951 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
952 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
953 !kEmitCompilerReadBarrier;
954 }
955
Jeff Hao436183f2016-01-12 16:36:50 -0800956 void ExpandOatAndImageFilenames() {
957 std::string base_oat = oat_filenames_[0];
958 size_t last_oat_slash = base_oat.rfind('/');
959 if (last_oat_slash == std::string::npos) {
960 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
961 }
962 // We also need to honor path components that were encoded through '@'. Otherwise the loading
963 // code won't be able to find the images.
964 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
965 last_oat_slash = base_oat.rfind('@');
966 }
967 base_oat = base_oat.substr(0, last_oat_slash + 1);
968
969 std::string base_img = image_filenames_[0];
970 size_t last_img_slash = base_img.rfind('/');
971 if (last_img_slash == std::string::npos) {
972 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
973 }
974 // We also need to honor path components that were encoded through '@'. Otherwise the loading
975 // code won't be able to find the images.
976 if (base_img.find('@', last_img_slash) != std::string::npos) {
977 last_img_slash = base_img.rfind('@');
978 }
979
980 // Get the prefix, which is the primary image name (without path components). Strip the
981 // extension.
982 std::string prefix = base_img.substr(last_img_slash + 1);
983 if (prefix.rfind('.') != std::string::npos) {
984 prefix = prefix.substr(0, prefix.rfind('.'));
985 }
986 if (!prefix.empty()) {
987 prefix = prefix + "-";
988 }
989
990 base_img = base_img.substr(0, last_img_slash + 1);
991
992 // Note: we have some special case here for our testing. We have to inject the differentiating
993 // parts for the different core images.
994 std::string infix; // Empty infix by default.
995 {
996 // Check the first name.
997 std::string dex_file = oat_filenames_[0];
998 size_t last_dex_slash = dex_file.rfind('/');
999 if (last_dex_slash != std::string::npos) {
1000 dex_file = dex_file.substr(last_dex_slash + 1);
1001 }
1002 size_t last_dex_dot = dex_file.rfind('.');
1003 if (last_dex_dot != std::string::npos) {
1004 dex_file = dex_file.substr(0, last_dex_dot);
1005 }
1006 if (StartsWith(dex_file, "core-")) {
1007 infix = dex_file.substr(strlen("core"));
1008 }
1009 }
1010
1011 // Now create the other names. Use a counted loop to skip the first one.
1012 for (size_t i = 1; i < dex_locations_.size(); ++i) {
1013 // TODO: Make everything properly std::string.
1014 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
1015 char_backing_storage_.push_back(base_img + image_name);
1016 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1017
1018 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
1019 char_backing_storage_.push_back(base_oat + oat_name);
1020 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
1021 }
1022 }
1023
Andreas Gampe8994a042015-12-30 19:03:17 +00001024 // Modify the input string in the following way:
1025 // 0) Assume input is /a/b/c.d
1026 // 1) Strip the path -> c.d
1027 // 2) Inject prefix p -> pc.d
1028 // 3) Inject infix i -> pci.d
1029 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001030 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001031 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001032 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001033 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 size_t last_dex_slash = in.rfind('/');
1035 if (last_dex_slash != std::string::npos) {
1036 in = in.substr(last_dex_slash + 1);
1037 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001038 if (!prefix.empty()) {
1039 in = prefix + in;
1040 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001041 if (!infix.empty()) {
1042 // Inject infix.
1043 size_t last_dot = in.rfind('.');
1044 if (last_dot != std::string::npos) {
1045 in.insert(last_dot, infix);
1046 }
1047 }
1048 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001049 in = in.substr(0, in.length() - strlen(".jar")) +
1050 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001051 }
1052 return in;
1053 }
1054
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001055 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001056 std::ostringstream oss;
1057 for (int i = 0; i < argc; ++i) {
1058 if (i > 0) {
1059 oss << ' ';
1060 }
1061 oss << argv[i];
1062 }
1063 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1064 oss.str(""); // Reset.
1065 oss << kRuntimeISA;
1066 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1067 key_value_store_->Put(
1068 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001069 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001070 key_value_store_->Put(
1071 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001072 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdilce4b0ba2016-01-28 15:05:49 +00001073 key_value_store_->Put(
1074 OatHeader::kExtractOnlyKey,
1075 compiler_options_->IsExtractOnly() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001076 }
1077
1078 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1079 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1080 // returns, arguments have been successfully parsed.
1081 void ParseArgs(int argc, char** argv) {
1082 original_argc = argc;
1083 original_argv = argv;
1084
1085 InitLogging(argv);
1086
1087 // Skip over argv[0].
1088 argv++;
1089 argc--;
1090
1091 if (argc == 0) {
1092 Usage("No arguments specified");
1093 }
1094
1095 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001096 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001097
1098 for (int i = 0; i < argc; i++) {
1099 const StringPiece option(argv[i]);
1100 const bool log_options = false;
1101 if (log_options) {
1102 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1103 }
1104 if (option.starts_with("--dex-file=")) {
1105 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1106 } else if (option.starts_with("--dex-location=")) {
1107 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1108 } else if (option.starts_with("--zip-fd=")) {
1109 ParseZipFd(option);
1110 } else if (option.starts_with("--zip-location=")) {
1111 zip_location_ = option.substr(strlen("--zip-location=")).data();
1112 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001113 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001114 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001115 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001116 } else if (option.starts_with("--oat-fd=")) {
1117 ParseOatFd(option);
1118 } else if (option == "--watch-dog") {
1119 parser_options->watch_dog_enabled = true;
1120 } else if (option == "--no-watch-dog") {
1121 parser_options->watch_dog_enabled = false;
1122 } else if (option.starts_with("-j")) {
1123 ParseJ(option);
1124 } else if (option.starts_with("--oat-location=")) {
1125 oat_location_ = option.substr(strlen("--oat-location=")).data();
1126 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001127 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001128 } else if (option.starts_with("--image-classes=")) {
1129 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1130 } else if (option.starts_with("--image-classes-zip=")) {
1131 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001132 } else if (option.starts_with("--image-format=")) {
1133 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001134 } else if (option.starts_with("--compiled-classes=")) {
1135 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1136 } else if (option.starts_with("--compiled-classes-zip=")) {
1137 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1138 } else if (option.starts_with("--compiled-methods=")) {
1139 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1140 } else if (option.starts_with("--compiled-methods-zip=")) {
1141 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1142 } else if (option.starts_with("--base=")) {
1143 ParseBase(option);
1144 } else if (option.starts_with("--boot-image=")) {
1145 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1146 } else if (option.starts_with("--android-root=")) {
1147 android_root_ = option.substr(strlen("--android-root=")).data();
1148 } else if (option.starts_with("--instruction-set=")) {
1149 ParseInstructionSet(option);
1150 } else if (option.starts_with("--instruction-set-variant=")) {
1151 ParseInstructionSetVariant(option, parser_options.get());
1152 } else if (option.starts_with("--instruction-set-features=")) {
1153 ParseInstructionSetFeatures(option, parser_options.get());
1154 } else if (option.starts_with("--compiler-backend=")) {
1155 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001156 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001157 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1158 } else if (option.starts_with("--reference-profile-file=")) {
1159 reference_profile_files_.push_back(
1160 option.substr(strlen("--reference-profile-file=")).ToString());
Calin Juravle877fd962016-01-05 14:29:29 +00001161 } else if (option.starts_with("--profile-file-fd=")) {
1162 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
1163 } else if (option.starts_with("--reference-profile-file-fd=")) {
1164 ParseFdForCollection(option, "--reference_profile-file-fd", &reference_profile_files_fd_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001165 } else if (option == "--no-profile-file") {
1166 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001167 } else if (option == "--host") {
1168 is_host_ = true;
1169 } else if (option == "--runtime-arg") {
1170 if (++i >= argc) {
1171 Usage("Missing required argument for --runtime-arg");
1172 }
1173 if (log_options) {
1174 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1175 }
1176 runtime_args_.push_back(argv[i]);
1177 } else if (option == "--dump-timing") {
1178 dump_timing_ = true;
1179 } else if (option == "--dump-passes") {
1180 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001181 } else if (option == "--dump-stats") {
1182 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001183 } else if (option.starts_with("--swap-file=")) {
1184 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1185 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001186 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1187 } else if (option.starts_with("--app-image-file=")) {
1188 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1189 } else if (option.starts_with("--app-image-fd=")) {
1190 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001191 } else if (option.starts_with("--verbose-methods=")) {
1192 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1193 // conditional on having verbost methods.
1194 gLogVerbosity.compiler = false;
1195 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001196 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001197 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001198 } else if (option.starts_with("--no-inline-from=")) {
1199 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001200 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001201 if (!SupportsDeterministicCompilation()) {
1202 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001203 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001204 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001205 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001206 Usage("Unknown argument %s", option.data());
1207 }
1208 }
1209
Jeff Hao436183f2016-01-12 16:36:50 -08001210 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211
1212 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001213 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001214 }
1215
Jeff Haodcdc85b2015-12-04 14:06:18 -08001216 // Check whether the oat output files are writable, and open them for later. Also open a swap
1217 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001218 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001219 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1220 PruneNonExistentDexFiles();
1221
Jeff Hao436183f2016-01-12 16:36:50 -08001222 // Expand oat and image filenames for multi image.
1223 if (IsBootImage() && multi_image_) {
1224 ExpandOatAndImageFilenames();
1225 }
1226
Jeff Haodcdc85b2015-12-04 14:06:18 -08001227 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001228 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001229 for (const char* oat_filename : oat_filenames_) {
1230 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1231 if (oat_file.get() == nullptr) {
1232 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1233 return false;
1234 }
1235 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1236 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1237 oat_file->Erase();
1238 return false;
1239 }
1240 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001241 }
1242 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001243 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1244 oat_file->DisableAutoClose();
1245 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001246 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1247 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001248 if (oat_file.get() == nullptr) {
1249 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1250 return false;
1251 }
1252 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1253 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1254 oat_file->Erase();
1255 return false;
1256 }
1257 oat_filenames_.push_back(oat_location_.c_str());
1258 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001259 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001260
1261 // Swap file handling.
1262 //
1263 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1264 // that we can use for swap.
1265 //
1266 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1267 // will immediately unlink to satisfy the swap fd assumption.
1268 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1269 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1270 if (swap_file.get() == nullptr) {
1271 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1272 return false;
1273 }
1274 swap_fd_ = swap_file->Fd();
1275 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1276 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1277 // released immediately.
1278 unlink(swap_file_name_.c_str());
1279 }
Jeff Hao436183f2016-01-12 16:36:50 -08001280
1281 // If we use a swap file, ensure we are above the threshold to make it necessary.
1282 if (swap_fd_ != -1) {
1283 if (!UseSwap(IsBootImage(), dex_files_)) {
1284 close(swap_fd_);
1285 swap_fd_ = -1;
1286 VLOG(compiler) << "Decided to run without swap.";
1287 } else {
1288 LOG(INFO) << "Large app, accepted running with swap.";
1289 }
1290 }
1291 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1292
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001293 return true;
1294 }
1295
Jeff Haodcdc85b2015-12-04 14:06:18 -08001296 void EraseOatFiles() {
1297 for (size_t i = 0; i < oat_files_.size(); ++i) {
1298 DCHECK(oat_files_[i].get() != nullptr);
1299 oat_files_[i]->Erase();
1300 oat_files_[i].reset();
1301 }
Andreas Gampea650e702014-12-03 14:28:02 -08001302 }
1303
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001304 void Shutdown() {
1305 ScopedObjectAccess soa(Thread::Current());
1306 for (jobject dex_cache : dex_caches_) {
1307 soa.Env()->DeleteLocalRef(dex_cache);
1308 }
1309 dex_caches_.clear();
1310 }
1311
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001312 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1313 // boot class path.
1314 bool Setup() {
1315 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001316 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001317
1318 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1319 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001320 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001321
Vladimir Marko307dac92015-10-20 11:20:09 +01001322 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001323 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001324 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001325 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001326 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001327 CompilerCallbacks::CallbackMode::kCompileBootImage :
1328 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001329
Vladimir Marko49b0f452015-12-10 13:49:19 +00001330 RuntimeArgumentMap runtime_options;
1331 if (!PrepareRuntimeOptions(&runtime_options)) {
1332 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001333 }
1334
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001335 CreateOatWriters();
1336 if (!AddDexFileSources()) {
1337 return false;
1338 }
1339
1340 if (IsBootImage() && image_filenames_.size() > 1) {
1341 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1342 // We need this for the multi-image case.
1343 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1344 }
1345
1346 if (!IsBootImage()) {
1347 // When compiling an app, create the runtime early to retrieve
1348 // the image location key needed for the oat header.
1349 if (!CreateRuntime(std::move(runtime_options))) {
1350 return false;
1351 }
1352
David Brazdilce4b0ba2016-01-28 15:05:49 +00001353 if (compiler_options_->IsExtractOnly()) {
1354 // ExtractOnly oat files only contain non-quickened DEX code and are
1355 // therefore independent of the image file.
1356 image_file_location_oat_checksum_ = 0u;
1357 image_file_location_oat_data_begin_ = 0u;
1358 image_patch_delta_ = 0;
1359 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001360 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1361 std::vector<gc::space::ImageSpace*> image_spaces =
1362 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1363 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1364 image_file_location_oat_data_begin_ =
1365 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1366 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1367 // Store the boot image filename(s).
1368 std::vector<std::string> image_filenames;
1369 for (const gc::space::ImageSpace* image_space : image_spaces) {
1370 image_filenames.push_back(image_space->GetImageFilename());
1371 }
1372 std::string image_file_location = Join(image_filenames, ':');
1373 if (!image_file_location.empty()) {
1374 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1375 }
1376 }
1377
1378 // Open dex files for class path.
1379 const std::vector<std::string> class_path_locations =
1380 GetClassPathLocations(runtime_->GetClassPathString());
1381 OpenClassPathFiles(class_path_locations, &class_path_files_);
1382
1383 // Store the classpath we have right now.
1384 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1385 key_value_store_->Put(OatHeader::kClassPathKey,
1386 OatFile::EncodeDexFileDependencies(class_path_files));
1387 }
1388
1389 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001390 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001391 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1392 rodata_.reserve(oat_writers_.size());
1393 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1394 rodata_.push_back(elf_writers_[i]->StartRoData());
1395 // Unzip or copy dex files straight to the oat file.
1396 std::unique_ptr<MemMap> opened_dex_files_map;
1397 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1398 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1399 oat_files_[i].get(),
1400 instruction_set_,
1401 instruction_set_features_.get(),
1402 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001403 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001404 &opened_dex_files_map,
1405 &opened_dex_files)) {
1406 return false;
1407 }
1408 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1409 if (opened_dex_files_map != nullptr) {
1410 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1411 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001412 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001413 opened_dex_files_.push_back(std::move(dex_file));
1414 }
1415 } else {
1416 DCHECK(opened_dex_files.empty());
1417 }
1418 }
1419 }
1420
1421 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1422 if (IsBootImage()) {
1423 // For boot image, pass opened dex files to the Runtime::Create().
1424 // Note: Runtime acquires ownership of these dex files.
1425 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001426 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001427 return false;
1428 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001429 }
1430
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001431 // If we're doing the image, override the compiler filter to force full compilation. Must be
1432 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1433 // compilation of class initializers.
1434 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001435 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001436 WellKnownClasses::Init(self->GetJniEnv());
1437
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001438 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001439 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001440 constexpr bool kSaveDexInput = false;
1441 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001442 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001443 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001444
1445 // Handle and ClassLoader creation needs to come after Runtime::Create.
1446 ScopedObjectAccess soa(self);
1447
1448 // Classpath: first the class-path given.
1449 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1450
1451 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1452 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1453
1454 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001455 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001456
1457 // Ensure opened dex files are writable for dex-to-dex transformations.
1458 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1459 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1460 PLOG(ERROR) << "Failed to make .dex files writeable.";
1461 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001462 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001463 }
1464
1465 // Ensure that the dex caches stay live since we don't want class unloading
1466 // to occur during compilation.
1467 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001468 ScopedObjectAccess soa(self);
1469 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001470 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001471 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001472
1473 /*
1474 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1475 * Don't bother to check if we're doing the image.
1476 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001477 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001478 compiler_options_->IsCompilationEnabled() &&
1479 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001480 size_t num_methods = 0;
1481 for (size_t i = 0; i != dex_files_.size(); ++i) {
1482 const DexFile* dex_file = dex_files_[i];
1483 CHECK(dex_file != nullptr);
1484 num_methods += dex_file->NumMethodIds();
1485 }
1486 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1487 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1488 VLOG(compiler) << "Below method threshold, compiling anyways";
1489 }
1490 }
1491
1492 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001493 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001494
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001495 // If we need to keep the oat file open for the image writer.
1496 bool ShouldKeepOatFileOpen() const {
1497 return IsImage() && oat_fd_ != kInvalidFd;
1498 }
1499
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001500 // Create and invoke the compiler driver. This will compile all the dex files.
1501 void Compile() {
1502 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1503 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001504
Vladimir Marko47496c22016-01-27 16:15:08 +00001505 // Find the dex files we should not inline from.
1506
1507 std::vector<std::string> no_inline_filters;
1508 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001509
1510 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001511 const std::string core_oj = "core-oj";
1512 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1513 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001514 }
1515
Vladimir Marko47496c22016-01-27 16:15:08 +00001516 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001517 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1518 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1519 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1520 &class_linker->GetBootClassPath(),
1521 &class_path_files,
1522 &dex_files_
1523 };
1524 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001525 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001526 for (const std::string& filter : no_inline_filters) {
1527 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1528 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1529 // base location passes the StartsWith() test, so do all extra locations.
1530 std::string dex_location = dex_file->GetLocation();
1531 if (filter.find('/') == std::string::npos) {
1532 // The filter does not contain the path. Remove the path from dex_location as well.
1533 size_t last_slash = dex_file->GetLocation().rfind('/');
1534 if (last_slash != std::string::npos) {
1535 dex_location = dex_location.substr(last_slash + 1);
1536 }
1537 }
1538
1539 if (StartsWith(dex_location, filter.c_str())) {
1540 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1541 no_inline_from_dex_files_.push_back(dex_file);
1542 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001543 }
1544 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001546 }
1547 if (!no_inline_from_dex_files_.empty()) {
1548 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001549 }
1550 }
1551
Vladimir Marko307dac92015-10-20 11:20:09 +01001552 driver_.reset(new CompilerDriver(compiler_options_.get(),
1553 verification_results_.get(),
1554 &method_inliner_map_,
1555 compiler_kind_,
1556 instruction_set_,
1557 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001558 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001559 image_classes_.release(),
1560 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001561 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001562 thread_count_,
1563 dump_stats_,
1564 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001565 compiler_phases_timings_.get(),
1566 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001567 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001568 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001569 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001570 }
1571
Jeff Hao436183f2016-01-12 16:36:50 -08001572 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001573 // ensure the references between the two are correct.
1574 //
1575 // Currently we have a memory layout that looks something like this:
1576 //
1577 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001578 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001579 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001580 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001581 // +--------------+
1582 // | alloc spaces |
1583 // +--------------+
1584 //
Jeff Hao436183f2016-01-12 16:36:50 -08001585 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586 //
Jeff Hao436183f2016-01-12 16:36:50 -08001587 // 1. The images are expected to be loaded at an absolute address and
1588 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589 //
Jeff Hao436183f2016-01-12 16:36:50 -08001590 // 2. There are absolute pointers from Methods in the images to their
1591 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001592 //
Jeff Hao436183f2016-01-12 16:36:50 -08001593 // 3. There are absolute pointers from the code in the oat files to Methods
1594 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001595 //
Jeff Hao436183f2016-01-12 16:36:50 -08001596 // 4. There are absolute pointers from code in the oat files to other code
1597 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001598 //
1599 // To get this all correct, we go through several steps.
1600 //
Jeff Hao436183f2016-01-12 16:36:50 -08001601 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001602 // the oat data size and code size. During this stage, we also set
1603 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001604 //
Jeff Hao436183f2016-01-12 16:36:50 -08001605 // 2. We prepare offsets for the objects in the images and calculate
1606 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001607 //
Jeff Hao436183f2016-01-12 16:36:50 -08001608 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001609 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001610 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001611 // can prepare the ELF headers and we then know the ELF memory segment
1612 // layout and we can now resolve all references. The compiler provides
1613 // LinkerPatch information in each CompiledMethod and we resolve these,
1614 // using the layout information and image object locations provided by
1615 // image writer, as we're writing the method code.
1616 //
Jeff Hao436183f2016-01-12 16:36:50 -08001617 // 4. We create the image files. They need to know where the oat files
1618 // will be loaded after itself. Originally oat files were simply
1619 // memory mapped so we could predict where their contents were based
1620 // on the file size. Now that they are ELF files, we need to inspect
1621 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001622 // where the oat header is located within.
1623 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001624 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001625 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001626 // load the .so at the desired location at runtime by offsetting the
1627 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001628 // TODO: Do this in step 3. We already know the layout there.
1629 //
1630 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1631 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1634 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001635 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1636 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001638 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1639
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001640 // Sync the data to the file, in case we did dex2dex transformations.
1641 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1642 if (!map->Sync()) {
1643 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1644 return false;
1645 }
1646 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001647
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001648 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001650 gc::Heap* const heap = Runtime::Current()->GetHeap();
1651 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001652 image_base_ = std::max(image_base_, RoundUp(
1653 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1654 kPageSize));
1655 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001656 // The non moving space is right after the oat file. Put the preferred app image location
1657 // right after the non moving space so that we ideally get a continuous immune region for
1658 // the GC.
1659 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1660 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001661 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1662 }
1663
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001664 image_writer_.reset(new ImageWriter(*driver_,
1665 image_base_,
1666 compiler_options_->GetCompilePic(),
1667 IsAppImage(),
1668 image_storage_mode_,
1669 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001670 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001672 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001673 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1674 if (!image_writer_->PrepareImageAddressSpace()) {
1675 LOG(ERROR) << "Failed to prepare image address space.";
1676 return false;
1677 }
1678 }
1679
Vladimir Marko944da602016-02-19 12:27:55 +00001680 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001681 {
1682 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001683 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001684 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1685 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1686
1687 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1688 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1689
1690 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1691 size_t text_size = oat_writer->GetSize() - rodata_size;
1692 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1693
1694 if (IsImage()) {
1695 // Update oat layout.
1696 DCHECK(image_writer_ != nullptr);
1697 DCHECK_LT(i, oat_filenames_.size());
1698 image_writer_->UpdateOatFileLayout(i,
1699 elf_writer->GetLoadedSize(),
1700 oat_writer->GetOatDataOffset(),
1701 oat_writer->GetSize());
1702 }
1703 }
1704
1705 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko45724f92016-02-17 17:46:10 +00001706 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001707 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1708 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001709
Vladimir Marko60654022016-02-16 12:50:23 +00001710 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001711 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1712 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001713
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001714 OutputStream*& rodata = rodata_[i];
1715 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001716 if (!oat_writer->WriteRodata(rodata)) {
1717 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1718 return false;
1719 }
1720 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001721 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001722
Jeff Haodcdc85b2015-12-04 14:06:18 -08001723 OutputStream* text = elf_writer->StartText();
1724 if (!oat_writer->WriteCode(text)) {
1725 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1726 return false;
1727 }
1728 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001729
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001730 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1731 image_file_location_oat_checksum_,
1732 image_file_location_oat_data_begin_,
1733 image_patch_delta_)) {
1734 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1735 return false;
1736 }
1737
Vladimir Marko944da602016-02-19 12:27:55 +00001738 if (IsImage()) {
1739 // Update oat header information.
1740 DCHECK(image_writer_ != nullptr);
1741 DCHECK_LT(i, oat_filenames_.size());
1742 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1743 }
1744
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 elf_writer->WriteDynamicSection();
1746 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1747 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001748
Jeff Haodcdc85b2015-12-04 14:06:18 -08001749 if (!elf_writer->End()) {
1750 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1751 return false;
1752 }
1753
1754 // Flush the oat file.
1755 if (oat_files_[i] != nullptr) {
1756 if (oat_files_[i]->Flush() != 0) {
1757 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001758 return false;
1759 }
1760 }
1761
Jeff Haodcdc85b2015-12-04 14:06:18 -08001762 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001763
1764 oat_writer.reset();
1765 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001766 }
1767 }
1768
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001769 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001770 }
1771
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001772 // If we are compiling an image, invoke the image creation routine. Else just skip.
1773 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001774 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001775 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1776 if (!CreateImageFile()) {
1777 return false;
1778 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001779 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001780 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001781 return true;
1782 }
1783
Jeff Haodcdc85b2015-12-04 14:06:18 -08001784 // Create a copy from stripped to unstripped.
1785 bool CopyStrippedToUnstripped() {
1786 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1787 // If we don't want to strip in place, copy from stripped location to unstripped location.
1788 // We need to strip after image creation because FixupElf needs to use .strtab.
1789 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1790 // If the oat file is still open, flush it.
1791 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1792 if (!FlushCloseOatFile(i)) {
1793 return false;
1794 }
1795 }
1796
1797 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1798 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1799 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1800 size_t buffer_size = 8192;
1801 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1802 while (true) {
1803 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1804 if (bytes_read <= 0) {
1805 break;
1806 }
1807 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1808 CHECK(write_ok);
1809 }
1810 if (out->FlushCloseOrErase() != 0) {
1811 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1812 return false;
1813 }
1814 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1815 }
1816 }
1817 return true;
1818 }
1819
1820 bool FlushOatFiles() {
1821 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1822 for (size_t i = 0; i < oat_files_.size(); ++i) {
1823 if (oat_files_[i].get() != nullptr) {
1824 if (oat_files_[i]->Flush() != 0) {
1825 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1826 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001827 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001828 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001829 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001830 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001831 return true;
1832 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001833
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 bool FlushCloseOatFile(size_t i) {
1835 if (oat_files_[i].get() != nullptr) {
1836 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001837 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001838 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001839 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001840 }
1841 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001842 return true;
1843 }
1844
Jeff Haodcdc85b2015-12-04 14:06:18 -08001845 bool FlushCloseOatFiles() {
1846 bool result = true;
1847 for (size_t i = 0; i < oat_files_.size(); ++i) {
1848 result &= FlushCloseOatFile(i);
1849 }
1850 return result;
1851 }
1852
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001853 void DumpTiming() {
1854 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1855 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1856 }
1857 if (dump_passes_) {
1858 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1859 }
1860 }
1861
1862 CompilerOptions* GetCompilerOptions() const {
1863 return compiler_options_.get();
1864 }
1865
Andreas Gampe10e477d2014-11-19 12:57:42 -08001866 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001867 return IsAppImage() || IsBootImage();
1868 }
1869
1870 bool IsAppImage() const {
1871 return app_image_;
1872 }
1873
1874 bool IsBootImage() const {
1875 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001876 }
1877
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001878 bool IsHost() const {
1879 return is_host_;
1880 }
1881
Calin Juravle998c2162015-12-21 15:39:33 +02001882 bool UseProfileGuidedCompilation() const {
Calin Juravle877fd962016-01-05 14:29:29 +00001883 return !profile_files_.empty() || !profile_files_fd_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02001884 }
1885
1886 bool ProcessProfiles() {
1887 DCHECK(UseProfileGuidedCompilation());
1888 ProfileCompilationInfo* info = nullptr;
Calin Juravle877fd962016-01-05 14:29:29 +00001889 bool result = false;
1890 if (profile_files_.empty()) {
1891 DCHECK(!profile_files_fd_.empty());
1892 result = ProfileAssistant::ProcessProfiles(
1893 profile_files_fd_, reference_profile_files_fd_, &info);
1894 CloseAllFds(profile_files_fd_, "profile_files_fd_");
1895 CloseAllFds(reference_profile_files_fd_, "reference_profile_files_fd_");
1896 } else {
1897 result = ProfileAssistant::ProcessProfiles(
1898 profile_files_, reference_profile_files_, &info);
Calin Juravle998c2162015-12-21 15:39:33 +02001899 }
Calin Juravle877fd962016-01-05 14:29:29 +00001900
1901 profile_compilation_info_.reset(info);
1902
1903 return result;
Calin Juravle998c2162015-12-21 15:39:33 +02001904 }
1905
1906 bool ShouldCompileBasedOnProfiles() const {
1907 DCHECK(UseProfileGuidedCompilation());
1908 // If we are given profiles, compile only if we have new information.
1909 return profile_compilation_info_ != nullptr;
1910 }
1911
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001912 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001913 template <typename T>
1914 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1915 std::vector<T*> result;
1916 result.reserve(src.size());
1917 for (const std::unique_ptr<T>& t : src) {
1918 result.push_back(t.get());
1919 }
1920 return result;
1921 }
1922
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001923 std::string GetMultiImageBootClassPath() {
1924 DCHECK(IsBootImage());
1925 DCHECK_GT(oat_filenames_.size(), 1u);
1926 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1927 // too, but need to strip all path components (they will be re-established when loading).
1928 std::ostringstream bootcp_oss;
1929 bool first_bootcp = true;
1930 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1931 if (!first_bootcp) {
1932 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001933 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001934
1935 std::string dex_loc = dex_locations_[i];
1936 std::string image_filename = image_filenames_[i];
1937
1938 // Use the dex_loc path, but the image_filename name (without path elements).
1939 size_t dex_last_slash = dex_loc.rfind('/');
1940
1941 // npos is max(size_t). That makes this a bit ugly.
1942 size_t image_last_slash = image_filename.rfind('/');
1943 size_t image_last_at = image_filename.rfind('@');
1944 size_t image_last_sep = (image_last_slash == std::string::npos)
1945 ? image_last_at
1946 : (image_last_at == std::string::npos)
1947 ? std::string::npos
1948 : std::max(image_last_slash, image_last_at);
1949 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1950
1951 if (dex_last_slash == std::string::npos) {
1952 dex_loc = image_filename.substr(image_last_sep + 1);
1953 } else {
1954 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1955 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001956 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001957
1958 // Image filenames already end with .art, no need to replace.
1959
1960 bootcp_oss << dex_loc;
1961 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001962 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001963 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001964 }
1965
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001966 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1967 // This function is used only for apps and for an app we have exactly one oat file.
1968 DCHECK(!IsBootImage());
1969 DCHECK_EQ(oat_writers_.size(), 1u);
1970 std::vector<std::string> dex_files_canonical_locations;
1971 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1972 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001973 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001974
Vladimir Marko919f5532016-01-20 19:13:01 +00001975 std::vector<std::string> parsed;
1976 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001977 auto kept_it = std::remove_if(parsed.begin(),
1978 parsed.end(),
1979 [dex_files_canonical_locations](const std::string& location) {
1980 return ContainsElement(dex_files_canonical_locations,
1981 DexFile::GetDexCanonicalLocation(location.c_str()));
1982 });
1983 parsed.erase(kept_it, parsed.end());
1984 return parsed;
1985 }
1986
1987 // Opens requested class path files and appends them to opened_dex_files.
1988 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1989 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1990 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1991 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001992 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001993 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1994 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001995 }
1996 }
1997 }
1998
Vladimir Marko49b0f452015-12-10 13:49:19 +00001999 bool PrepareImageClasses() {
2000 // If --image-classes was specified, calculate the full list of classes to include in the image.
2001 if (image_classes_filename_ != nullptr) {
2002 image_classes_ =
2003 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
2004 if (image_classes_ == nullptr) {
2005 return false;
2006 }
2007 } else if (IsBootImage()) {
2008 image_classes_.reset(new std::unordered_set<std::string>);
2009 }
2010 return true;
2011 }
2012
2013 bool PrepareCompiledClasses() {
2014 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2015 // image.
2016 if (compiled_classes_filename_ != nullptr) {
2017 compiled_classes_ =
2018 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2019 if (compiled_classes_ == nullptr) {
2020 return false;
2021 }
2022 } else {
2023 compiled_classes_.reset(nullptr); // By default compile everything.
2024 }
2025 return true;
2026 }
2027
2028 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2029 const char* classes_filename,
2030 const char* tag) {
2031 std::unique_ptr<std::unordered_set<std::string>> classes;
2032 std::string error_msg;
2033 if (zip_filename != nullptr) {
2034 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2035 } else {
2036 classes.reset(ReadImageClassesFromFile(classes_filename));
2037 }
2038 if (classes == nullptr) {
2039 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2040 << classes_filename << "': " << error_msg;
2041 }
2042 return classes;
2043 }
2044
2045 bool PrepareCompiledMethods() {
2046 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2047 if (compiled_methods_filename_ != nullptr) {
2048 std::string error_msg;
2049 if (compiled_methods_zip_filename_ != nullptr) {
2050 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2051 compiled_methods_filename_,
2052 nullptr, // No post-processing.
2053 &error_msg));
2054 } else {
2055 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2056 nullptr)); // No post-processing.
2057 }
2058 if (compiled_methods_.get() == nullptr) {
2059 LOG(ERROR) << "Failed to create list of compiled methods from '"
2060 << compiled_methods_filename_ << "': " << error_msg;
2061 return false;
2062 }
2063 } else {
2064 compiled_methods_.reset(nullptr); // By default compile everything.
2065 }
2066 return true;
2067 }
2068
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002069 void PruneNonExistentDexFiles() {
2070 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2071 size_t kept = 0u;
2072 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2073 if (!OS::FileExists(dex_filenames_[i])) {
2074 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2075 } else {
2076 dex_filenames_[kept] = dex_filenames_[i];
2077 dex_locations_[kept] = dex_locations_[i];
2078 ++kept;
2079 }
2080 }
2081 dex_filenames_.resize(kept);
2082 dex_locations_.resize(kept);
2083 }
2084
2085 bool AddDexFileSources() {
2086 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2087 if (zip_fd_ != -1) {
2088 DCHECK_EQ(oat_writers_.size(), 1u);
2089 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2090 return false;
2091 }
2092 } else if (oat_writers_.size() > 1u) {
2093 // Multi-image.
2094 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2095 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2096 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2097 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2098 return false;
2099 }
2100 }
2101 } else {
2102 DCHECK_EQ(oat_writers_.size(), 1u);
2103 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2104 DCHECK_NE(dex_filenames_.size(), 0u);
2105 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2106 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2107 return false;
2108 }
2109 }
2110 }
2111 return true;
2112 }
2113
2114 void CreateOatWriters() {
2115 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2116 elf_writers_.reserve(oat_files_.size());
2117 oat_writers_.reserve(oat_files_.size());
2118 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2119 elf_writers_.emplace_back(
2120 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2121 elf_writers_.back()->Start();
2122 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2123 }
2124 }
2125
Vladimir Marko49b0f452015-12-10 13:49:19 +00002126 void SaveDexInput() {
2127 for (size_t i = 0; i < dex_files_.size(); ++i) {
2128 const DexFile* dex_file = dex_files_[i];
2129 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2130 getpid(), i));
2131 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2132 if (tmp_file.get() == nullptr) {
2133 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2134 << ". Try: adb shell chmod 777 /data/local/tmp";
2135 continue;
2136 }
2137 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2138 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2139 UNUSED(tmp_file->Flush());
2140 UNUSED(tmp_file->Close());
2141 LOG(INFO) << "Wrote input to " << tmp_file_name;
2142 }
2143 }
2144
2145 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2146 RuntimeOptions raw_options;
2147 if (boot_image_filename_.empty()) {
2148 std::string boot_class_path = "-Xbootclasspath:";
2149 boot_class_path += Join(dex_filenames_, ':');
2150 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2151 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2152 boot_class_path_locations += Join(dex_locations_, ':');
2153 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2154 } else {
2155 std::string boot_image_option = "-Ximage:";
2156 boot_image_option += boot_image_filename_;
2157 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2158 }
2159 for (size_t i = 0; i < runtime_args_.size(); i++) {
2160 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2161 }
2162
2163 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2164 raw_options.push_back(
2165 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2166
2167 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2168 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2169 // have been stripped in preopting, anyways).
2170 if (!IsBootImage()) {
2171 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2172 }
2173 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2174 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2175 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002176 // Disable Hspace compaction to save heap size virtual space.
2177 // Only need disable Hspace for OOM becasue background collector is equal to
2178 // foreground collector by default for dex2oat.
2179 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002180
Andreas Gampeace0dc12016-01-20 13:33:13 -08002181 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2182 // force the free-list implementation for large objects.
2183 if (compiler_options_->IsForceDeterminism()) {
2184 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2185 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2186
2187 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2188 // compaction (done above) and ensure that neither foreground nor background collectors
2189 // are concurrent.
2190 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2191
2192 // To make identity hashcode deterministic, set a known seed.
2193 mirror::Object::SetHashCodeSeed(987654321U);
2194 }
2195
Vladimir Marko49b0f452015-12-10 13:49:19 +00002196 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2197 LOG(ERROR) << "Failed to parse runtime options";
2198 return false;
2199 }
2200 return true;
2201 }
2202
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002203 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002204 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2205 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002206 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002207 LOG(ERROR) << "Failed to create runtime";
2208 return false;
2209 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002210 runtime_.reset(Runtime::Current());
2211 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002212 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2213 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002214 if (!runtime_->HasCalleeSaveMethod(type)) {
2215 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002216 }
2217 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002218 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002219
2220 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2221 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002222 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002223
Vladimir Marko307dac92015-10-20 11:20:09 +01002224 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002225
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002226 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2227 // Runtime::Start, give it away now so that we don't starve GC.
2228 Thread* self = Thread::Current();
2229 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002230
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002231 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002232 }
2233
Jeff Haodcdc85b2015-12-04 14:06:18 -08002234 // 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 -08002235 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002236 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002237 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002238 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002239 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002240 image_filenames_.push_back(app_image_file_name_.c_str());
2241 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002242 if (!image_writer_->Write(app_image_fd_,
2243 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002244 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002245 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002246 return false;
2247 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002248
Jeff Haodcdc85b2015-12-04 14:06:18 -08002249 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002250 dchecked_vector<uintptr_t> oat_data_begins;
2251 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2252 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002253 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002254 // Destroy ImageWriter before doing FixupElf.
2255 image_writer_.reset();
2256
Vladimir Marko944da602016-02-19 12:27:55 +00002257 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2258 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002259 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2260 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2261 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2262 if (oat_file.get() == nullptr) {
2263 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2264 return false;
2265 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002266
Vladimir Marko944da602016-02-19 12:27:55 +00002267 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002268 oat_file->Erase();
2269 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2270 return false;
2271 }
2272
2273 if (oat_file->FlushCloseOrErase()) {
2274 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2275 return false;
2276 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002277 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002278 }
2279
2280 return true;
2281 }
2282
2283 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002284 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2285 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002286 std::function<std::string(const char*)> process = DotToDescriptor;
2287 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002288 }
2289
2290 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002291 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002292 const char* zip_filename,
2293 const char* image_classes_filename,
2294 std::string* error_msg) {
2295 std::function<std::string(const char*)> process = DotToDescriptor;
2296 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2297 }
2298
2299 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2300 // the given function.
2301 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2302 const char* input_filename, std::function<std::string(const char*)>* process) {
2303 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2304 if (input_file.get() == nullptr) {
2305 LOG(ERROR) << "Failed to open input file " << input_filename;
2306 return nullptr;
2307 }
2308 std::unique_ptr<std::unordered_set<std::string>> result(
2309 ReadCommentedInputStream(*input_file, process));
2310 input_file->close();
2311 return result.release();
2312 }
2313
2314 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2315 // Post-process each line with the given function.
2316 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002317 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002318 const char* input_filename,
2319 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002320 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002321 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2322 if (zip_archive.get() == nullptr) {
2323 return nullptr;
2324 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002325 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002326 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002327 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002328 zip_filename, error_msg->c_str());
2329 return nullptr;
2330 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002331 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2332 input_filename,
2333 error_msg));
2334 if (input_file.get() == nullptr) {
2335 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002336 zip_filename, error_msg->c_str());
2337 return nullptr;
2338 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002339 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2340 input_file->Size());
2341 std::istringstream input_stream(input_string);
2342 return ReadCommentedInputStream(input_stream, process);
2343 }
2344
2345 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2346 // with the given function.
2347 static std::unordered_set<std::string>* ReadCommentedInputStream(
2348 std::istream& in_stream,
2349 std::function<std::string(const char*)>* process) {
2350 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2351 new std::unordered_set<std::string>);
2352 while (in_stream.good()) {
2353 std::string dot;
2354 std::getline(in_stream, dot);
2355 if (StartsWith(dot, "#") || dot.empty()) {
2356 continue;
2357 }
2358 if (process != nullptr) {
2359 std::string descriptor((*process)(dot.c_str()));
2360 image_classes->insert(descriptor);
2361 } else {
2362 image_classes->insert(dot);
2363 }
2364 }
2365 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002366 }
2367
Mathieu Chartier49285c52014-12-02 15:43:48 -08002368 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002369 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2370 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002371 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002372 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002373 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002374 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002375 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2376 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002377 }
2378
Jeff Haodcdc85b2015-12-04 14:06:18 -08002379 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2380 std::string res(image_filename);
2381 size_t last_slash = res.rfind('/');
2382 if (last_slash == std::string::npos || last_slash == 0) {
2383 return res;
2384 }
2385 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2386 if (penultimate_slash == std::string::npos) {
2387 return res;
2388 }
2389 // Check that the string in-between is the expected one.
2390 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2391 GetInstructionSetString(isa)) {
2392 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2393 return res;
2394 }
2395 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2396 }
2397
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002398 std::unique_ptr<CompilerOptions> compiler_options_;
2399 Compiler::Kind compiler_kind_;
2400
2401 InstructionSet instruction_set_;
2402 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2403
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002404 uint32_t image_file_location_oat_checksum_;
2405 uintptr_t image_file_location_oat_data_begin_;
2406 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002407 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2408
Vladimir Marko307dac92015-10-20 11:20:09 +01002409 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002410
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 DexFileToMethodInlinerMap method_inliner_map_;
2412 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2413
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002414 std::unique_ptr<Runtime> runtime_;
2415
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002416 // Ownership for the class path files.
2417 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2418
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002419 size_t thread_count_;
2420 uint64_t start_ns_;
2421 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002422 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002423 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002424 std::vector<const char*> oat_filenames_;
2425 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002426 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002427 std::vector<const char*> dex_filenames_;
2428 std::vector<const char*> dex_locations_;
2429 int zip_fd_;
2430 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002431 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002432 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002433 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002434 uintptr_t image_base_;
2435 const char* image_classes_zip_filename_;
2436 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002437 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002438 const char* compiled_classes_zip_filename_;
2439 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002440 const char* compiled_methods_zip_filename_;
2441 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002442 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2443 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002444 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002445 bool app_image_;
2446 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002447 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002448 bool is_host_;
2449 std::string android_root_;
2450 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002451 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002452 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002453 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002454
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002455 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2456 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2457 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002458 std::unique_ptr<ImageWriter> image_writer_;
2459 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002460
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002461 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2462 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2463
Vladimir Marko47496c22016-01-27 16:15:08 +00002464 std::vector<const DexFile*> no_inline_from_dex_files_;
2465
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002466 std::vector<std::string> verbose_methods_;
2467 bool dump_stats_;
2468 bool dump_passes_;
2469 bool dump_timing_;
2470 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002471 std::string swap_file_name_;
2472 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002473 std::string app_image_file_name_;
2474 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002475 std::vector<std::string> profile_files_;
2476 std::vector<std::string> reference_profile_files_;
Calin Juravle877fd962016-01-05 14:29:29 +00002477 std::vector<uint32_t> profile_files_fd_;
2478 std::vector<uint32_t> reference_profile_files_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002479 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002480 TimingLogger* timings_;
2481 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002482 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002483 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002484
2485 // Backing storage.
2486 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002487
Andreas Gampeace0dc12016-01-20 13:33:13 -08002488 // See CompilerOptions.force_determinism_.
2489 bool force_determinism_;
2490
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002491 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2492};
2493
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002494static void b13564922() {
2495#if defined(__linux__) && defined(__arm__)
2496 int major, minor;
2497 struct utsname uts;
2498 if (uname(&uts) != -1 &&
2499 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2500 ((major < 3) || ((major == 3) && (minor < 4)))) {
2501 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2502 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2503 int old_personality = personality(0xffffffff);
2504 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2505 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2506 if (new_personality == -1) {
2507 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2508 }
2509 }
2510 }
2511#endif
2512}
2513
Andreas Gampe10e477d2014-11-19 12:57:42 -08002514static int CompileImage(Dex2Oat& dex2oat) {
2515 dex2oat.Compile();
2516
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002517 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002518 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002519 return EXIT_FAILURE;
2520 }
2521
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002522 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2523 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2524 // image writer will require this fd to generate the image.
2525 if (dex2oat.ShouldKeepOatFileOpen()) {
2526 if (!dex2oat.FlushOatFiles()) {
2527 return EXIT_FAILURE;
2528 }
2529 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002530 return EXIT_FAILURE;
2531 }
2532
Jeff Haodcdc85b2015-12-04 14:06:18 -08002533 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002534 if (!dex2oat.HandleImage()) {
2535 return EXIT_FAILURE;
2536 }
2537
2538 // When given --host, finish early without stripping.
2539 if (dex2oat.IsHost()) {
2540 dex2oat.DumpTiming();
2541 return EXIT_SUCCESS;
2542 }
2543
Jeff Haodcdc85b2015-12-04 14:06:18 -08002544 // Copy stripped to unstripped location, if necessary.
2545 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002546 return EXIT_FAILURE;
2547 }
2548
Jeff Haodcdc85b2015-12-04 14:06:18 -08002549 // FlushClose again, as stripping might have re-opened the oat files.
2550 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002551 return EXIT_FAILURE;
2552 }
2553
2554 dex2oat.DumpTiming();
2555 return EXIT_SUCCESS;
2556}
2557
2558static int CompileApp(Dex2Oat& dex2oat) {
2559 dex2oat.Compile();
2560
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002561 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002562 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002563 return EXIT_FAILURE;
2564 }
2565
Jeff Haodcdc85b2015-12-04 14:06:18 -08002566 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002567 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002568
2569 // When given --host, finish early without stripping.
2570 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002571 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002572 return EXIT_FAILURE;
2573 }
2574
2575 dex2oat.DumpTiming();
2576 return EXIT_SUCCESS;
2577 }
2578
Jeff Haodcdc85b2015-12-04 14:06:18 -08002579 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2580 // stripped versions. If this is given, we expect to be able to open writable files by name.
2581 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002582 return EXIT_FAILURE;
2583 }
2584
Jeff Haodcdc85b2015-12-04 14:06:18 -08002585 // Flush and close the files.
2586 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002587 return EXIT_FAILURE;
2588 }
2589
2590 dex2oat.DumpTiming();
2591 return EXIT_SUCCESS;
2592}
2593
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002594static int dex2oat(int argc, char** argv) {
2595 b13564922();
2596
2597 TimingLogger timings("compiler", false, false);
2598
2599 Dex2Oat dex2oat(&timings);
2600
2601 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2602 dex2oat.ParseArgs(argc, argv);
2603
Calin Juravle998c2162015-12-21 15:39:33 +02002604 // Process profile information and assess if we need to do a profile guided compilation.
2605 // This operation involves I/O.
2606 if (dex2oat.UseProfileGuidedCompilation()) {
2607 if (dex2oat.ProcessProfiles()) {
2608 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2609 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2610 return EXIT_SUCCESS;
2611 }
2612 } else {
2613 LOG(WARNING) << "Failed to process profile files";
2614 return EXIT_FAILURE;
2615 }
2616 }
2617
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002618 // Check early that the result of compilation can be written
2619 if (!dex2oat.OpenFile()) {
2620 return EXIT_FAILURE;
2621 }
2622
Andreas Gampe046c7062015-05-18 23:22:54 -07002623 // Print the complete line when any of the following is true:
2624 // 1) Debug build
2625 // 2) Compiling an image
2626 // 3) Compiling with --host
2627 // 4) Compiling on the host (not a target build)
2628 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002629 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002630 LOG(INFO) << CommandLine();
2631 } else {
2632 LOG(INFO) << StrippedCommandLine();
2633 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002634
2635 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002636 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002637 return EXIT_FAILURE;
2638 }
2639
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002640 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002641 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002642 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002643 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002644 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002645 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002646
2647 dex2oat.Shutdown();
2648 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002649}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002650} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002651
2652int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002653 int result = art::dex2oat(argc, argv);
2654 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2655 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2656 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002657 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002658 exit(result);
2659 }
2660 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002661}