blob: 6c4c994d5d9da44f557200ce7643e43e83067936 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000053#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick_compiler_callbacks.h"
55#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000058#include "dwarf/method_debug_info.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020066#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/class-inl.h"
69#include "mirror/class_loader.h"
70#include "mirror/object-inl.h"
71#include "mirror/object_array-inl.h"
72#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "os.h"
Calin Juravle998c2162015-12-21 15:39:33 +020074#include "profile_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000076#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "ScopedLocalRef.h"
78#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070079#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070080#include "well_known_classes.h"
81#include "zip_archive.h"
82
83namespace art {
84
Brian Carlstrom6449c622014-02-10 23:48:36 -080085static int original_argc;
86static char** original_argv;
87
88static std::string CommandLine() {
89 std::vector<std::string> command;
90 for (int i = 0; i < original_argc; ++i) {
91 command.push_back(original_argv[i]);
92 }
93 return Join(command, ' ');
94}
95
Andreas Gampe046c7062015-05-18 23:22:54 -070096// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
97// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
98// locations are all staged).
99static std::string StrippedCommandLine() {
100 std::vector<std::string> command;
101
102 // Do a pre-pass to look for zip-fd.
103 bool saw_zip_fd = false;
104 for (int i = 0; i < original_argc; ++i) {
105 if (StartsWith(original_argv[i], "--zip-fd=")) {
106 saw_zip_fd = true;
107 break;
108 }
109 }
110
111 // Now filter out things.
112 for (int i = 0; i < original_argc; ++i) {
113 // All runtime-arg parameters are dropped.
114 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
115 i++; // Drop the next part, too.
116 continue;
117 }
118
119 // Any instruction-setXXX is dropped.
120 if (StartsWith(original_argv[i], "--instruction-set")) {
121 continue;
122 }
123
124 // The boot image is dropped.
125 if (StartsWith(original_argv[i], "--boot-image=")) {
126 continue;
127 }
128
129 // This should leave any dex-file and oat-file options, describing what we compiled.
130
131 // However, we prefer to drop this when we saw --zip-fd.
132 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700133 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700134 if (StartsWith(original_argv[i], "--zip-") ||
135 StartsWith(original_argv[i], "--dex-") ||
136 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700137 StartsWith(original_argv[i], "--swap-") ||
138 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700139 continue;
140 }
141 }
142
143 command.push_back(original_argv[i]);
144 }
145
146 // Construct the final output.
147 if (command.size() <= 1U) {
148 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
149 return "Starting dex2oat.";
150 }
151 return Join(command, ' ');
152}
153
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154static void UsageErrorV(const char* fmt, va_list ap) {
155 std::string error;
156 StringAppendV(&error, fmt, ap);
157 LOG(ERROR) << error;
158}
159
160static void UsageError(const char* fmt, ...) {
161 va_list ap;
162 va_start(ap, fmt);
163 UsageErrorV(fmt, ap);
164 va_end(ap);
165}
166
Andreas Gampe794ad762015-02-23 08:12:24 -0800167NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 va_list ap;
169 va_start(ap, fmt);
170 UsageErrorV(fmt, ap);
171 va_end(ap);
172
Brian Carlstrom6449c622014-02-10 23:48:36 -0800173 UsageError("Command: %s", CommandLine().c_str());
174
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 UsageError("Usage: dex2oat [options]...");
176 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100177 UsageError(" -j<number>: specifies the number of threads used for compilation.");
178 UsageError(" Default is the number of detected hardware threads available on the");
179 UsageError(" host system.");
180 UsageError(" Example: -j12");
181 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700182 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 UsageError(" Example: --dex-file=/system/framework/core.jar");
184 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700185 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
186 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
187 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
188 UsageError(" --dex-location=/system/framework/core.jar");
189 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
191 UsageError(" containing a classes.dex file to compile.");
192 UsageError(" Example: --zip-fd=5");
193 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700194 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
195 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
197 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 UsageError(" Example: --oat-file=/system/framework/boot.oat");
200 UsageError("");
201 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900202 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError("");
204 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
205 UsageError(" to the file descriptor specified by --oat-fd.");
206 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
207 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
210 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 UsageError(" Example: --image=/system/framework/boot.art");
213 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800214 UsageError(" --image-format=(uncompressed|lz4):");
215 UsageError(" Which format to store the image.");
216 UsageError(" Example: --image-format=lz4");
217 UsageError(" Default: uncompressed");
218 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
220 UsageError(" Example: --image=frameworks/base/preloaded-classes");
221 UsageError("");
222 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
223 UsageError(" Example: --base=0x50000000");
224 UsageError("");
225 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000226 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000228 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000229 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError("");
231 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
232 UsageError(" Example: --android-root=out/host/linux-x86");
233 UsageError(" Default: $ANDROID_ROOT");
234 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800235 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700236 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError(" Example: --instruction-set=x86");
238 UsageError(" Default: arm");
239 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700240 UsageError(" --instruction-set-features=...,: Specify instruction set features");
241 UsageError(" Example: --instruction-set-features=div");
242 UsageError(" Default: default");
243 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700244 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
245 UsageError(" Default: disabled");
246 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800247 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800249 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100250 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100252 UsageError(" --compiler-filter="
253 "(verify-none"
254 "|interpret-only"
255 "|space"
256 "|balanced"
257 "|speed"
258 "|everything"
259 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700260 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800262 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800263 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800264 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
265 UsageError(" method for compiler filter tuning.");
266 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
267 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
268 UsageError("");
269 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
270 UsageError(" method for compiler filter tuning.");
271 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
272 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
273 UsageError("");
274 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
275 UsageError(" method for compiler filter tuning.");
276 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
278 UsageError("");
279 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
280 UsageError(" method for compiler filter tuning.");
281 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
282 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
283 UsageError("");
284 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
285 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700286 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
287 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800288 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
289 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
290 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100291 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
292 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100293 UsageError(" Has priority over the --compiler-filter option. Intended for ");
294 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100295 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
296 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
297 UsageError("");
298 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
299 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100300 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
301 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100302 UsageError(" Example: --inline-max-code-units=%d",
303 CompilerOptions::kDefaultInlineMaxCodeUnits);
304 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
305 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700306 UsageError(" --dump-timing: display a breakdown of where time was spent");
307 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700308 UsageError(" --include-patch-information: Include patching information so the generated code");
309 UsageError(" can have its base address moved without full recompilation.");
310 UsageError("");
311 UsageError(" --no-include-patch-information: Do not include patching information.");
312 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100313 UsageError(" -g");
314 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
315 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000316 UsageError(" If used without --native-debuggable, it will be best-effort only.");
317 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100320 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000321 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000322 UsageError("");
323 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
324 UsageError(" Implies --debuggable.");
325 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
327 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
328 UsageError(" Use a separate --runtime-arg switch for each argument.");
329 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700330 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000331 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200332 UsageError(" Can be specified multiple time, in which case the data from the different");
333 UsageError(" profiles will be aggregated.");
334 UsageError("");
335 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
336 UsageError(" compiling. The data in this file will be compared with the data in the");
337 UsageError(" associated --profile-file and the compilation will proceed only if there is");
338 UsageError(" a significant difference (--reference-profile-file is paired with");
339 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
340 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
341 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000343 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
344 UsageError(" Cannot be used together with --profile-file.");
345 UsageError("");
346 UsageError(" --reference-profile-file-fd=<number>: same as --reference-profile-file but");
347 UsageError(" accepts a file descriptor. Cannot be used together with");
348 UsageError(" --reference-profile-file.");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700349 UsageError(" --print-pass-names: print a list of pass names");
350 UsageError("");
351 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
352 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
353 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700354 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
355 "with the setting.");
356 UsageError(" Will print default if no overridden setting exists.");
357 UsageError("");
358 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
359 "Pass2Name:Pass2OptionName:Pass2Option#");
360 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
361 UsageError(" Separator used between options is a comma.");
362 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800363 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
364 UsageError(" Example: --swap-file=/data/tmp/swap.001");
365 UsageError("");
366 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
367 UsageError(" Example: --swap-fd=10");
368 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700369 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
370 UsageError(" Example: --app-image-fd=10");
371 UsageError("");
372 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
373 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
374 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800375 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
376 "input dex file.");
377 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 std::cerr << "See log for usage error information\n";
379 exit(EXIT_FAILURE);
380}
381
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382// The primary goal of the watchdog is to prevent stuck build servers
383// during development when fatal aborts lead to a cascade of failures
384// that result in a deadlock.
385class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800386// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387#undef CHECK_PTHREAD_CALL
388#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
389 do { \
390 int rc = call args; \
391 if (rc != 0) { \
392 errno = rc; \
393 std::string message(# call); \
394 message += " failed for "; \
395 message += reason; \
396 Fatal(message); \
397 } \
398 } while (false)
399
400 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700401 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402 is_watch_dog_enabled_ = is_watch_dog_enabled;
403 if (!is_watch_dog_enabled_) {
404 return;
405 }
406 shutting_down_ = false;
407 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700408 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
409 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
412 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
413 }
414 ~WatchDog() {
415 if (!is_watch_dog_enabled_) {
416 return;
417 }
418 const char* reason = "dex2oat watch dog thread shutdown";
419 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
420 shutting_down_ = true;
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
423
Kenny Root51316382014-05-13 14:59:37 -0700424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
427 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
428 }
429
430 private:
431 static void* CallBack(void* arg) {
432 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
433 ::art::SetThreadName("dex2oat watch dog");
434 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700435 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 }
437
Andreas Gampe794ad762015-02-23 08:12:24 -0800438 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700439 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
440 // it's rather easy to hang in unwinding.
441 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
442 // logcat logging or stderr output.
443 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444 exit(1);
445 }
446
447 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
449 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700450 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 timespec timeout_ts;
452 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
453 const char* reason = "dex2oat watch dog thread waiting";
454 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
455 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800456 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700458 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
459 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 } else if (rc != 0) {
461 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
462 strerror(errno)));
463 Fatal(message.c_str());
464 }
465 }
466 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
467 }
468
469 // 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 -0700470 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700471 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472
Andreas Gampe540138a2015-09-14 15:34:38 -0700473 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
474 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
475 // itself before that watchdog would take down the system server.
476 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700477
478 bool is_watch_dog_enabled_;
479 bool shutting_down_;
480 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
481 pthread_mutex_t mutex_;
482 pthread_cond_t cond_;
483 pthread_attr_t attr_;
484 pthread_t pthread_;
485};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800487static constexpr size_t kMinDexFilesForSwap = 2;
488static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
489
490static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
491 if (is_image) {
492 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
493 return false;
494 }
495 if (dex_files.size() < kMinDexFilesForSwap) {
496 // If there are less dex files than the threshold, assume it's gonna be fine.
497 return false;
498 }
499 size_t dex_files_size = 0;
500 for (const auto* dex_file : dex_files) {
501 dex_files_size += dex_file->GetHeader().file_size_;
502 }
503 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
504}
505
Calin Juravle877fd962016-01-05 14:29:29 +0000506static void CloseAllFds(const std::vector<uint32_t>& fds, const char* descriptor) {
507 for (size_t i = 0; i < fds.size(); i++) {
508 if (close(fds[i]) < 0) {
509 PLOG(WARNING) << "Failed to close descriptor for " << descriptor << " at index " << i;
510 }
511 }
512}
513
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800514class Dex2Oat FINAL {
515 public:
516 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100517 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800518 instruction_set_(kRuntimeISA),
519 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000520 image_file_location_oat_checksum_(0),
521 image_file_location_oat_data_begin_(0),
522 image_patch_delta_(0),
523 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700524 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800525 method_inliner_map_(),
526 runtime_(nullptr),
527 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
528 start_ns_(NanoTime()),
529 oat_fd_(-1),
530 zip_fd_(-1),
531 image_base_(0U),
532 image_classes_zip_filename_(nullptr),
533 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800534 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800535 compiled_classes_zip_filename_(nullptr),
536 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700537 compiled_methods_zip_filename_(nullptr),
538 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700539 app_image_(false),
540 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800541 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800542 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 class_loader_(nullptr),
544 elf_writers_(),
545 oat_writers_(),
546 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000547 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700548 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000549 opened_dex_files_maps_(),
550 opened_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800551 dump_stats_(false),
552 dump_passes_(false),
553 dump_timing_(false),
554 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800555 swap_fd_(-1),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800556 app_image_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800557 timings_(timings),
558 force_determinism_(false) {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800559
560 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800561 // Log completion time before deleting the runtime_, because this accesses
562 // the runtime.
563 LogCompletionTime();
564
Vladimir Marko307dac92015-10-20 11:20:09 +0100565 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
566 // We want to just exit on non-debug builds, not bringing the runtime down
567 // in an orderly fashion. So release the following fields.
568 driver_.release();
569 image_writer_.release();
570 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
571 dex_file.release();
572 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000573 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
574 map.release();
575 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800576 for (std::unique_ptr<File>& oat_file : oat_files_) {
577 oat_file.release();
578 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100579 runtime_.release();
580 verification_results_.release();
581 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100582 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700583 }
584
Roland Levillain9ec5e222015-08-17 20:18:41 +0100585 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800586 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800588 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000589 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800590 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100591 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800592
Roland Levillain9ec5e222015-08-17 20:18:41 +0100593 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000594 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100595 }
596
597 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000598 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100599 }
600
Calin Juravle877fd962016-01-05 14:29:29 +0000601 void ParseFdForCollection(const StringPiece& option,
602 const char* arg_name,
603 std::vector<uint32_t>* fds) {
604 uint32_t fd;
605 ParseUintOption(option, arg_name, &fd, Usage);
606 fds->push_back(fd);
607 }
608
Roland Levillain9ec5e222015-08-17 20:18:41 +0100609 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000610 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100611 }
612
613 void ParseBase(const StringPiece& option) {
614 DCHECK(option.starts_with("--base="));
615 const char* image_base_str = option.substr(strlen("--base=")).data();
616 char* end;
617 image_base_ = strtoul(image_base_str, &end, 16);
618 if (end == image_base_str || *end != '\0') {
619 Usage("Failed to parse hexadecimal value for option %s", option.data());
620 }
621 }
622
623 void ParseInstructionSet(const StringPiece& option) {
624 DCHECK(option.starts_with("--instruction-set="));
625 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
626 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
627 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
628 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
629 buf.get()[instruction_set_str.length()] = 0;
630 instruction_set_ = GetInstructionSetFromString(buf.get());
631 // arm actually means thumb2.
632 if (instruction_set_ == InstructionSet::kArm) {
633 instruction_set_ = InstructionSet::kThumb2;
634 }
635 }
636
637 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
638 DCHECK(option.starts_with("--instruction-set-variant="));
639 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
640 instruction_set_features_.reset(
641 InstructionSetFeatures::FromVariant(
642 instruction_set_, str.as_string(), &parser_options->error_msg));
643 if (instruction_set_features_.get() == nullptr) {
644 Usage("%s", parser_options->error_msg.c_str());
645 }
646 }
647
648 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
649 DCHECK(option.starts_with("--instruction-set-features="));
650 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
651 if (instruction_set_features_.get() == nullptr) {
652 instruction_set_features_.reset(
653 InstructionSetFeatures::FromVariant(
654 instruction_set_, "default", &parser_options->error_msg));
655 if (instruction_set_features_.get() == nullptr) {
656 Usage("Problem initializing default instruction set features variant: %s",
657 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800659 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100660 instruction_set_features_.reset(
661 instruction_set_features_->AddFeaturesFromString(str.as_string(),
662 &parser_options->error_msg));
663 if (instruction_set_features_.get() == nullptr) {
664 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
665 }
666 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800667
Roland Levillain9ec5e222015-08-17 20:18:41 +0100668 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
669 DCHECK(option.starts_with("--compiler-backend="));
670 parser_options->requested_specific_compiler = true;
671 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
672 if (backend_str == "Quick") {
673 compiler_kind_ = Compiler::kQuick;
674 } else if (backend_str == "Optimizing") {
675 compiler_kind_ = Compiler::kOptimizing;
676 } else {
677 Usage("Unknown compiler backend: %s", backend_str.data());
678 }
679 }
680
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800681 void ParseImageFormat(const StringPiece& option) {
682 const StringPiece substr("--image-format=");
683 DCHECK(option.starts_with(substr));
684 const StringPiece format_str = option.substr(substr.length());
685 if (format_str == "lz4") {
686 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
687 } else if (format_str == "uncompressed") {
688 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
689 } else {
690 Usage("Unknown image format: %s", format_str.data());
691 }
692 }
693
Jeff Hao436183f2016-01-12 16:36:50 -0800694 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800695 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700696 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
697
698 if (IsAppImage() && IsBootImage()) {
699 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
700 }
701
702 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100703 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000704 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000705 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000706
Jeff Haodcdc85b2015-12-04 14:06:18 -0800707 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 Usage("Output must be supplied with either --oat-file or --oat-fd");
709 }
710
Jeff Haodcdc85b2015-12-04 14:06:18 -0800711 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800712 Usage("--oat-file should not be used with --oat-fd");
713 }
714
Roland Levillain9ec5e222015-08-17 20:18:41 +0100715 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 Usage("--oat-symbols should not be used with --oat-fd");
717 }
718
Roland Levillain9ec5e222015-08-17 20:18:41 +0100719 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 Usage("--oat-symbols should not be used with --host");
721 }
722
Jeff Haodcdc85b2015-12-04 14:06:18 -0800723 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800724 Usage("--oat-fd should not be used with --image");
725 }
726
Jeff Haodcdc85b2015-12-04 14:06:18 -0800727 if (!parser_options->oat_symbols.empty() &&
728 parser_options->oat_symbols.size() != oat_filenames_.size()) {
729 Usage("--oat-file arguments do not match --oat-symbols arguments");
730 }
731
732 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
733 Usage("--oat-file arguments do not match --image arguments");
734 }
735
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800736 if (android_root_.empty()) {
737 const char* android_root_env_var = getenv("ANDROID_ROOT");
738 if (android_root_env_var == nullptr) {
739 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800741 android_root_ += android_root_env_var;
742 }
743
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700744 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100745 parser_options->boot_image_filename += android_root_;
746 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800747 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100748 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000749 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800750 }
751
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700752 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800753 Usage("--image-classes should only be used with --image");
754 }
755
Vladimir Marko49b0f452015-12-10 13:49:19 +0000756 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800757 Usage("--image-classes should not be used with --boot-image");
758 }
759
760 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
761 Usage("--image-classes-zip should be used with --image-classes");
762 }
763
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700764 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800765 Usage("--compiled-classes should only be used with --image");
766 }
767
Vladimir Marko49b0f452015-12-10 13:49:19 +0000768 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800769 Usage("--compiled-classes should not be used with --boot-image");
770 }
771
772 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
773 Usage("--compiled-classes-zip should be used with --compiled-classes");
774 }
775
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800776 if (dex_filenames_.empty() && zip_fd_ == -1) {
777 Usage("Input must be supplied with either --dex-file or --zip-fd");
778 }
779
780 if (!dex_filenames_.empty() && zip_fd_ != -1) {
781 Usage("--dex-file should not be used with --zip-fd");
782 }
783
784 if (!dex_filenames_.empty() && !zip_location_.empty()) {
785 Usage("--dex-file should not be used with --zip-location");
786 }
787
788 if (dex_locations_.empty()) {
789 for (const char* dex_file_name : dex_filenames_) {
790 dex_locations_.push_back(dex_file_name);
791 }
792 } else if (dex_locations_.size() != dex_filenames_.size()) {
793 Usage("--dex-location arguments do not match --dex-file arguments");
794 }
795
Jeff Haodcdc85b2015-12-04 14:06:18 -0800796 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
797 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
798 Usage("--oat-file arguments must be singular or match --dex-file arguments");
799 }
800 }
801
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800802 if (zip_fd_ != -1 && zip_location_.empty()) {
803 Usage("--zip-location should be supplied with --zip-fd");
804 }
805
Vladimir Marko49b0f452015-12-10 13:49:19 +0000806 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 if (image_base_ == 0) {
808 Usage("Non-zero --base not specified");
809 }
810 }
811
Calin Juravle877fd962016-01-05 14:29:29 +0000812 if (!profile_files_.empty() && !profile_files_fd_.empty()) {
813 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
814 }
Calin Juravle998c2162015-12-21 15:39:33 +0200815 if (!profile_files_.empty()) {
816 if (!reference_profile_files_.empty() &&
817 (reference_profile_files_.size() != profile_files_.size())) {
818 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
819 }
Calin Juravle877fd962016-01-05 14:29:29 +0000820 } else if (!reference_profile_files_.empty()) {
821 Usage("--reference-profile-file should only be supplied with --profile-file");
822 }
823 if (!profile_files_fd_.empty()) {
824 if (!reference_profile_files_fd_.empty() &&
825 (reference_profile_files_fd_.size() != profile_files_fd_.size())) {
826 Usage("If specified, --reference-profile-file-fd should match the number",
827 " of --profile-file-fd.");
828 }
829 } else if (!reference_profile_files_fd_.empty()) {
830 Usage("--reference-profile-file-fd should only be supplied with --profile-file-fd");
Calin Juravle998c2162015-12-21 15:39:33 +0200831 }
832
Roland Levillain9ec5e222015-08-17 20:18:41 +0100833 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800834 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800835 }
836
837 // If no instruction set feature was given, use the default one for the target
838 // instruction set.
839 if (instruction_set_features_.get() == nullptr) {
840 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100841 InstructionSetFeatures::FromVariant(
842 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800843 if (instruction_set_features_.get() == nullptr) {
844 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100845 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800846 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800847 }
848
849 if (instruction_set_ == kRuntimeISA) {
850 std::unique_ptr<const InstructionSetFeatures> runtime_features(
851 InstructionSetFeatures::FromCppDefines());
852 if (!instruction_set_features_->Equals(runtime_features.get())) {
853 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
854 << *instruction_set_features_ << ") and those of dex2oat executable ("
855 << *runtime_features <<") for the command line:\n"
856 << CommandLine();
857 }
858 }
859
Roland Levillaina215b952015-08-07 11:38:32 +0100860 // It they are not set, use default values for inlining settings.
861 // TODO: We should rethink the compiler filter. We mostly save
862 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000863 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
864 compiler_options_->inline_depth_limit_ =
865 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100866 // Implementation of the space filter: limit inlining depth.
867 ? CompilerOptions::kSpaceFilterInlineDepthLimit
868 : CompilerOptions::kDefaultInlineDepthLimit;
869 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000870 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
871 compiler_options_->inline_max_code_units_ =
872 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100873 // Implementation of the space filter: limit inlining max code units.
874 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
875 : CompilerOptions::kDefaultInlineMaxCodeUnits;
876 }
877
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800878 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800879 // Set the compilation target's implicit checks options.
880 switch (instruction_set_) {
881 case kArm:
882 case kThumb2:
883 case kArm64:
884 case kX86:
885 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700886 case kMips:
887 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000888 compiler_options_->implicit_null_checks_ = true;
889 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800890 break;
891
892 default:
893 // Defaults are correct.
894 break;
895 }
896
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000897 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800898
Jeff Hao436183f2016-01-12 16:36:50 -0800899 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800900 Usage("--multi-image can only be used when creating boot images");
901 }
Jeff Hao436183f2016-01-12 16:36:50 -0800902 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800903 Usage("--multi-image cannot be used with multiple image names");
904 }
905
906 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
907 if (!kIsTargetBuild && IsBootImage()) {
908 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800909 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800910 }
911 }
912
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800913 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100914 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800915 watchdog_.reset(new WatchDog(true));
916 }
917
918 // Fill some values into the key-value store for the oat header.
919 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800920
921 // Automatically force determinism for the boot image in a host build.
922 if (!kIsTargetBuild && IsBootImage()) {
923 force_determinism_ = true;
924 }
925 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100926 }
927
Jeff Hao436183f2016-01-12 16:36:50 -0800928 void ExpandOatAndImageFilenames() {
929 std::string base_oat = oat_filenames_[0];
930 size_t last_oat_slash = base_oat.rfind('/');
931 if (last_oat_slash == std::string::npos) {
932 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
933 }
934 // We also need to honor path components that were encoded through '@'. Otherwise the loading
935 // code won't be able to find the images.
936 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
937 last_oat_slash = base_oat.rfind('@');
938 }
939 base_oat = base_oat.substr(0, last_oat_slash + 1);
940
941 std::string base_img = image_filenames_[0];
942 size_t last_img_slash = base_img.rfind('/');
943 if (last_img_slash == std::string::npos) {
944 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
945 }
946 // We also need to honor path components that were encoded through '@'. Otherwise the loading
947 // code won't be able to find the images.
948 if (base_img.find('@', last_img_slash) != std::string::npos) {
949 last_img_slash = base_img.rfind('@');
950 }
951
952 // Get the prefix, which is the primary image name (without path components). Strip the
953 // extension.
954 std::string prefix = base_img.substr(last_img_slash + 1);
955 if (prefix.rfind('.') != std::string::npos) {
956 prefix = prefix.substr(0, prefix.rfind('.'));
957 }
958 if (!prefix.empty()) {
959 prefix = prefix + "-";
960 }
961
962 base_img = base_img.substr(0, last_img_slash + 1);
963
964 // Note: we have some special case here for our testing. We have to inject the differentiating
965 // parts for the different core images.
966 std::string infix; // Empty infix by default.
967 {
968 // Check the first name.
969 std::string dex_file = oat_filenames_[0];
970 size_t last_dex_slash = dex_file.rfind('/');
971 if (last_dex_slash != std::string::npos) {
972 dex_file = dex_file.substr(last_dex_slash + 1);
973 }
974 size_t last_dex_dot = dex_file.rfind('.');
975 if (last_dex_dot != std::string::npos) {
976 dex_file = dex_file.substr(0, last_dex_dot);
977 }
978 if (StartsWith(dex_file, "core-")) {
979 infix = dex_file.substr(strlen("core"));
980 }
981 }
982
983 // Now create the other names. Use a counted loop to skip the first one.
984 for (size_t i = 1; i < dex_locations_.size(); ++i) {
985 // TODO: Make everything properly std::string.
986 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
987 char_backing_storage_.push_back(base_img + image_name);
988 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
989
990 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
991 char_backing_storage_.push_back(base_oat + oat_name);
992 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
993 }
994 }
995
Andreas Gampe8994a042015-12-30 19:03:17 +0000996 // Modify the input string in the following way:
997 // 0) Assume input is /a/b/c.d
998 // 1) Strip the path -> c.d
999 // 2) Inject prefix p -> pc.d
1000 // 3) Inject infix i -> pci.d
1001 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -08001002 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +00001003 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001004 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +00001005 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001006 size_t last_dex_slash = in.rfind('/');
1007 if (last_dex_slash != std::string::npos) {
1008 in = in.substr(last_dex_slash + 1);
1009 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001010 if (!prefix.empty()) {
1011 in = prefix + in;
1012 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001013 if (!infix.empty()) {
1014 // Inject infix.
1015 size_t last_dot = in.rfind('.');
1016 if (last_dot != std::string::npos) {
1017 in.insert(last_dot, infix);
1018 }
1019 }
1020 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001021 in = in.substr(0, in.length() - strlen(".jar")) +
1022 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001023 }
1024 return in;
1025 }
1026
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001027 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001028 std::ostringstream oss;
1029 for (int i = 0; i < argc; ++i) {
1030 if (i > 0) {
1031 oss << ' ';
1032 }
1033 oss << argv[i];
1034 }
1035 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1036 oss.str(""); // Reset.
1037 oss << kRuntimeISA;
1038 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1039 key_value_store_->Put(
1040 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001041 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001042 key_value_store_->Put(
1043 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001044 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001045 }
1046
1047 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1048 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1049 // returns, arguments have been successfully parsed.
1050 void ParseArgs(int argc, char** argv) {
1051 original_argc = argc;
1052 original_argv = argv;
1053
1054 InitLogging(argv);
1055
1056 // Skip over argv[0].
1057 argv++;
1058 argc--;
1059
1060 if (argc == 0) {
1061 Usage("No arguments specified");
1062 }
1063
1064 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001065 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001066
1067 for (int i = 0; i < argc; i++) {
1068 const StringPiece option(argv[i]);
1069 const bool log_options = false;
1070 if (log_options) {
1071 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1072 }
1073 if (option.starts_with("--dex-file=")) {
1074 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1075 } else if (option.starts_with("--dex-location=")) {
1076 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1077 } else if (option.starts_with("--zip-fd=")) {
1078 ParseZipFd(option);
1079 } else if (option.starts_with("--zip-location=")) {
1080 zip_location_ = option.substr(strlen("--zip-location=")).data();
1081 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001082 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001083 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001084 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001085 } else if (option.starts_with("--oat-fd=")) {
1086 ParseOatFd(option);
1087 } else if (option == "--watch-dog") {
1088 parser_options->watch_dog_enabled = true;
1089 } else if (option == "--no-watch-dog") {
1090 parser_options->watch_dog_enabled = false;
1091 } else if (option.starts_with("-j")) {
1092 ParseJ(option);
1093 } else if (option.starts_with("--oat-location=")) {
1094 oat_location_ = option.substr(strlen("--oat-location=")).data();
1095 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001096 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001097 } else if (option.starts_with("--image-classes=")) {
1098 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1099 } else if (option.starts_with("--image-classes-zip=")) {
1100 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001101 } else if (option.starts_with("--image-format=")) {
1102 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001103 } else if (option.starts_with("--compiled-classes=")) {
1104 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1105 } else if (option.starts_with("--compiled-classes-zip=")) {
1106 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1107 } else if (option.starts_with("--compiled-methods=")) {
1108 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1109 } else if (option.starts_with("--compiled-methods-zip=")) {
1110 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1111 } else if (option.starts_with("--base=")) {
1112 ParseBase(option);
1113 } else if (option.starts_with("--boot-image=")) {
1114 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1115 } else if (option.starts_with("--android-root=")) {
1116 android_root_ = option.substr(strlen("--android-root=")).data();
1117 } else if (option.starts_with("--instruction-set=")) {
1118 ParseInstructionSet(option);
1119 } else if (option.starts_with("--instruction-set-variant=")) {
1120 ParseInstructionSetVariant(option, parser_options.get());
1121 } else if (option.starts_with("--instruction-set-features=")) {
1122 ParseInstructionSetFeatures(option, parser_options.get());
1123 } else if (option.starts_with("--compiler-backend=")) {
1124 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001125 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001126 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1127 } else if (option.starts_with("--reference-profile-file=")) {
1128 reference_profile_files_.push_back(
1129 option.substr(strlen("--reference-profile-file=")).ToString());
Calin Juravle877fd962016-01-05 14:29:29 +00001130 } else if (option.starts_with("--profile-file-fd=")) {
1131 ParseFdForCollection(option, "--profile-file-fd", &profile_files_fd_);
1132 } else if (option.starts_with("--reference-profile-file-fd=")) {
1133 ParseFdForCollection(option, "--reference_profile-file-fd", &reference_profile_files_fd_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001134 } else if (option == "--no-profile-file") {
1135 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001136 } else if (option == "--host") {
1137 is_host_ = true;
1138 } else if (option == "--runtime-arg") {
1139 if (++i >= argc) {
1140 Usage("Missing required argument for --runtime-arg");
1141 }
1142 if (log_options) {
1143 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1144 }
1145 runtime_args_.push_back(argv[i]);
1146 } else if (option == "--dump-timing") {
1147 dump_timing_ = true;
1148 } else if (option == "--dump-passes") {
1149 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001150 } else if (option == "--dump-stats") {
1151 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001152 } else if (option.starts_with("--swap-file=")) {
1153 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1154 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001155 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1156 } else if (option.starts_with("--app-image-file=")) {
1157 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1158 } else if (option.starts_with("--app-image-fd=")) {
1159 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001160 } else if (option.starts_with("--verbose-methods=")) {
1161 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1162 // conditional on having verbost methods.
1163 gLogVerbosity.compiler = false;
1164 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001165 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001166 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001167 } else if (option.starts_with("--no-inline-from=")) {
1168 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001169 } else if (option == "--force-determinism") {
1170 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001171 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001172 Usage("Unknown argument %s", option.data());
1173 }
1174 }
1175
Jeff Hao436183f2016-01-12 16:36:50 -08001176 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001177
1178 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001179 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 }
1181
Jeff Haodcdc85b2015-12-04 14:06:18 -08001182 // Check whether the oat output files are writable, and open them for later. Also open a swap
1183 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001184 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001185 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1186 PruneNonExistentDexFiles();
1187
Jeff Hao436183f2016-01-12 16:36:50 -08001188 // Expand oat and image filenames for multi image.
1189 if (IsBootImage() && multi_image_) {
1190 ExpandOatAndImageFilenames();
1191 }
1192
Jeff Haodcdc85b2015-12-04 14:06:18 -08001193 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001194 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001195 for (const char* oat_filename : oat_filenames_) {
1196 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1197 if (oat_file.get() == nullptr) {
1198 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1199 return false;
1200 }
1201 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1202 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1203 oat_file->Erase();
1204 return false;
1205 }
1206 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001207 }
1208 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001209 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1210 oat_file->DisableAutoClose();
1211 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001212 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1213 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001214 if (oat_file.get() == nullptr) {
1215 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1216 return false;
1217 }
1218 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1219 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1220 oat_file->Erase();
1221 return false;
1222 }
1223 oat_filenames_.push_back(oat_location_.c_str());
1224 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001225 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001226
1227 // Swap file handling.
1228 //
1229 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1230 // that we can use for swap.
1231 //
1232 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1233 // will immediately unlink to satisfy the swap fd assumption.
1234 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1235 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1236 if (swap_file.get() == nullptr) {
1237 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1238 return false;
1239 }
1240 swap_fd_ = swap_file->Fd();
1241 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1242 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1243 // released immediately.
1244 unlink(swap_file_name_.c_str());
1245 }
Jeff Hao436183f2016-01-12 16:36:50 -08001246
1247 // If we use a swap file, ensure we are above the threshold to make it necessary.
1248 if (swap_fd_ != -1) {
1249 if (!UseSwap(IsBootImage(), dex_files_)) {
1250 close(swap_fd_);
1251 swap_fd_ = -1;
1252 VLOG(compiler) << "Decided to run without swap.";
1253 } else {
1254 LOG(INFO) << "Large app, accepted running with swap.";
1255 }
1256 }
1257 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1258
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001259 return true;
1260 }
1261
Jeff Haodcdc85b2015-12-04 14:06:18 -08001262 void EraseOatFiles() {
1263 for (size_t i = 0; i < oat_files_.size(); ++i) {
1264 DCHECK(oat_files_[i].get() != nullptr);
1265 oat_files_[i]->Erase();
1266 oat_files_[i].reset();
1267 }
Andreas Gampea650e702014-12-03 14:28:02 -08001268 }
1269
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001270 void Shutdown() {
1271 ScopedObjectAccess soa(Thread::Current());
1272 for (jobject dex_cache : dex_caches_) {
1273 soa.Env()->DeleteLocalRef(dex_cache);
1274 }
1275 dex_caches_.clear();
1276 }
1277
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001278 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1279 // boot class path.
1280 bool Setup() {
1281 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001282 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001283
1284 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1285 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001286 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001287
Vladimir Marko307dac92015-10-20 11:20:09 +01001288 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001289 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001290 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001291 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001292 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001293 CompilerCallbacks::CallbackMode::kCompileBootImage :
1294 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001295
Vladimir Marko49b0f452015-12-10 13:49:19 +00001296 RuntimeArgumentMap runtime_options;
1297 if (!PrepareRuntimeOptions(&runtime_options)) {
1298 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001299 }
1300
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001301 CreateOatWriters();
1302 if (!AddDexFileSources()) {
1303 return false;
1304 }
1305
1306 if (IsBootImage() && image_filenames_.size() > 1) {
1307 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1308 // We need this for the multi-image case.
1309 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1310 }
1311
1312 if (!IsBootImage()) {
1313 // When compiling an app, create the runtime early to retrieve
1314 // the image location key needed for the oat header.
1315 if (!CreateRuntime(std::move(runtime_options))) {
1316 return false;
1317 }
1318
1319 {
1320 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1321 std::vector<gc::space::ImageSpace*> image_spaces =
1322 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1323 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1324 image_file_location_oat_data_begin_ =
1325 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1326 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1327 // Store the boot image filename(s).
1328 std::vector<std::string> image_filenames;
1329 for (const gc::space::ImageSpace* image_space : image_spaces) {
1330 image_filenames.push_back(image_space->GetImageFilename());
1331 }
1332 std::string image_file_location = Join(image_filenames, ':');
1333 if (!image_file_location.empty()) {
1334 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1335 }
1336 }
1337
1338 // Open dex files for class path.
1339 const std::vector<std::string> class_path_locations =
1340 GetClassPathLocations(runtime_->GetClassPathString());
1341 OpenClassPathFiles(class_path_locations, &class_path_files_);
1342
1343 // Store the classpath we have right now.
1344 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1345 key_value_store_->Put(OatHeader::kClassPathKey,
1346 OatFile::EncodeDexFileDependencies(class_path_files));
1347 }
1348
1349 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001350 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001351 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1352 rodata_.reserve(oat_writers_.size());
1353 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1354 rodata_.push_back(elf_writers_[i]->StartRoData());
1355 // Unzip or copy dex files straight to the oat file.
1356 std::unique_ptr<MemMap> opened_dex_files_map;
1357 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1358 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1359 oat_files_[i].get(),
1360 instruction_set_,
1361 instruction_set_features_.get(),
1362 key_value_store_.get(),
1363 &opened_dex_files_map,
1364 &opened_dex_files)) {
1365 return false;
1366 }
1367 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1368 if (opened_dex_files_map != nullptr) {
1369 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1370 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
1371 dex_file_oat_filename_map_.emplace(dex_file.get(), oat_filenames_[i]);
1372 opened_dex_files_.push_back(std::move(dex_file));
1373 }
1374 } else {
1375 DCHECK(opened_dex_files.empty());
1376 }
1377 }
1378 }
1379
1380 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1381 if (IsBootImage()) {
1382 // For boot image, pass opened dex files to the Runtime::Create().
1383 // Note: Runtime acquires ownership of these dex files.
1384 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001385 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001386 return false;
1387 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001388 }
1389
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001390 // If we're doing the image, override the compiler filter to force full compilation. Must be
1391 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1392 // compilation of class initializers.
1393 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001394 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001395 WellKnownClasses::Init(self->GetJniEnv());
1396
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001397 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001398 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001399 constexpr bool kSaveDexInput = false;
1400 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001401 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001402 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001403
1404 // Handle and ClassLoader creation needs to come after Runtime::Create.
1405 ScopedObjectAccess soa(self);
1406
1407 // Classpath: first the class-path given.
1408 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1409
1410 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1411 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1412
1413 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001414 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001415
1416 // Ensure opened dex files are writable for dex-to-dex transformations.
1417 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1418 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1419 PLOG(ERROR) << "Failed to make .dex files writeable.";
1420 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001421 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001422 }
1423
1424 // Ensure that the dex caches stay live since we don't want class unloading
1425 // to occur during compilation.
1426 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001427 ScopedObjectAccess soa(self);
1428 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001429 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001430 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001431
1432 /*
1433 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1434 * Don't bother to check if we're doing the image.
1435 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001436 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001437 compiler_options_->IsCompilationEnabled() &&
1438 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001439 size_t num_methods = 0;
1440 for (size_t i = 0; i != dex_files_.size(); ++i) {
1441 const DexFile* dex_file = dex_files_[i];
1442 CHECK(dex_file != nullptr);
1443 num_methods += dex_file->NumMethodIds();
1444 }
1445 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1446 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1447 VLOG(compiler) << "Below method threshold, compiling anyways";
1448 }
1449 }
1450
1451 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001452 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001453
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001454 // If we need to keep the oat file open for the image writer.
1455 bool ShouldKeepOatFileOpen() const {
1456 return IsImage() && oat_fd_ != kInvalidFd;
1457 }
1458
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001459 // Create and invoke the compiler driver. This will compile all the dex files.
1460 void Compile() {
1461 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1462 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001463
Jeff Haodcdc85b2015-12-04 14:06:18 -08001464 // Find the dex file we should not inline from.
1465
1466 // For now, on the host always have core-oj removed.
1467 if (!kIsTargetBuild && no_inline_from_string_.empty()) {
1468 no_inline_from_string_ = "core-oj";
1469 }
1470
1471 if (!no_inline_from_string_.empty()) {
1472 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1473 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1474 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1475 &class_linker->GetBootClassPath(),
1476 &class_path_files,
1477 &dex_files_
1478 };
1479 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1480 if (dex_file_vector == nullptr) {
1481 continue;
1482 }
1483
1484 bool found = false;
1485
1486 for (const DexFile* dex_file : *dex_file_vector) {
1487 // Try the complete location first.
1488 found = no_inline_from_string_ == dex_file->GetLocation();
1489 // The try just the name.
1490 if (!found) {
1491 size_t last_slash = dex_file->GetLocation().rfind('/');
1492 if (last_slash != std::string::npos) {
1493 found = StartsWith(dex_file->GetLocation().substr(last_slash + 1),
1494 no_inline_from_string_.c_str());
1495 }
1496 }
1497
1498 if (found) {
1499 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1500 compiler_options_->no_inline_from_ = dex_file;
1501 break;
1502 }
1503 }
1504
1505 if (found) {
1506 break;
1507 }
1508 }
1509 }
1510
Vladimir Marko307dac92015-10-20 11:20:09 +01001511 driver_.reset(new CompilerDriver(compiler_options_.get(),
1512 verification_results_.get(),
1513 &method_inliner_map_,
1514 compiler_kind_,
1515 instruction_set_,
1516 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001517 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001518 image_classes_.release(),
1519 compiled_classes_.release(),
1520 nullptr,
1521 thread_count_,
1522 dump_stats_,
1523 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001524 compiler_phases_timings_.get(),
1525 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001526 &dex_file_oat_filename_map_,
1527 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001528 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001529 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001530 }
1531
Jeff Hao436183f2016-01-12 16:36:50 -08001532 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533 // ensure the references between the two are correct.
1534 //
1535 // Currently we have a memory layout that looks something like this:
1536 //
1537 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001538 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001539 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001540 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001541 // +--------------+
1542 // | alloc spaces |
1543 // +--------------+
1544 //
Jeff Hao436183f2016-01-12 16:36:50 -08001545 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001546 //
Jeff Hao436183f2016-01-12 16:36:50 -08001547 // 1. The images are expected to be loaded at an absolute address and
1548 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001549 //
Jeff Hao436183f2016-01-12 16:36:50 -08001550 // 2. There are absolute pointers from Methods in the images to their
1551 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001552 //
Jeff Hao436183f2016-01-12 16:36:50 -08001553 // 3. There are absolute pointers from the code in the oat files to Methods
1554 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001555 //
Jeff Hao436183f2016-01-12 16:36:50 -08001556 // 4. There are absolute pointers from code in the oat files to other code
1557 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001558 //
1559 // To get this all correct, we go through several steps.
1560 //
Jeff Hao436183f2016-01-12 16:36:50 -08001561 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001562 // the oat data size and code size. During this stage, we also set
1563 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564 //
Jeff Hao436183f2016-01-12 16:36:50 -08001565 // 2. We prepare offsets for the objects in the images and calculate
1566 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001567 //
Jeff Hao436183f2016-01-12 16:36:50 -08001568 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001570 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001571 // can prepare the ELF headers and we then know the ELF memory segment
1572 // layout and we can now resolve all references. The compiler provides
1573 // LinkerPatch information in each CompiledMethod and we resolve these,
1574 // using the layout information and image object locations provided by
1575 // image writer, as we're writing the method code.
1576 //
Jeff Hao436183f2016-01-12 16:36:50 -08001577 // 4. We create the image files. They need to know where the oat files
1578 // will be loaded after itself. Originally oat files were simply
1579 // memory mapped so we could predict where their contents were based
1580 // on the file size. Now that they are ELF files, we need to inspect
1581 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001582 // where the oat header is located within.
1583 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001584 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001585 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586 // load the .so at the desired location at runtime by offsetting the
1587 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001588 // TODO: Do this in step 3. We already know the layout there.
1589 //
1590 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1591 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001592
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001593 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1594 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001595 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1596 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001597 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001598 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1599
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001600 // Sync the data to the file, in case we did dex2dex transformations.
1601 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1602 if (!map->Sync()) {
1603 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1604 return false;
1605 }
1606 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001607
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001609 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001610 gc::Heap* const heap = Runtime::Current()->GetHeap();
1611 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001612 image_base_ = std::max(image_base_, RoundUp(
1613 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1614 kPageSize));
1615 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001616 // The non moving space is right after the oat file. Put the preferred app image location
1617 // right after the non moving space so that we ideally get a continuous immune region for
1618 // the GC.
1619 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1620 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001621 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1622 }
1623
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001624 image_writer_.reset(new ImageWriter(*driver_,
1625 image_base_,
1626 compiler_options_->GetCompilePic(),
1627 IsAppImage(),
1628 image_storage_mode_,
1629 oat_filenames_,
1630 dex_file_oat_filename_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001631
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001632 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1634 if (!image_writer_->PrepareImageAddressSpace()) {
1635 LOG(ERROR) << "Failed to prepare image address space.";
1636 return false;
1637 }
1638 }
1639
1640 {
1641 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001642 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001643 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001644 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1645 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001646
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001647 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1648 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files);
Vladimir Marko10c13562015-11-25 14:33:36 +00001649
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001650 OutputStream*& rodata = rodata_[i];
1651 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001652 if (!oat_writer->WriteRodata(rodata)) {
1653 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1654 return false;
1655 }
1656 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001657 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001658
Jeff Haodcdc85b2015-12-04 14:06:18 -08001659 OutputStream* text = elf_writer->StartText();
1660 if (!oat_writer->WriteCode(text)) {
1661 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1662 return false;
1663 }
1664 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001665
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001666 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1667 image_file_location_oat_checksum_,
1668 image_file_location_oat_data_begin_,
1669 image_patch_delta_)) {
1670 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1671 return false;
1672 }
1673
Jeff Haodcdc85b2015-12-04 14:06:18 -08001674 elf_writer->SetBssSize(oat_writer->GetBssSize());
1675 elf_writer->WriteDynamicSection();
1676 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1677 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001678
Jeff Haodcdc85b2015-12-04 14:06:18 -08001679 if (!elf_writer->End()) {
1680 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1681 return false;
1682 }
1683
1684 // Flush the oat file.
1685 if (oat_files_[i] != nullptr) {
1686 if (oat_files_[i]->Flush() != 0) {
1687 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1688 oat_files_[i]->Erase();
1689 return false;
1690 }
1691 }
1692
1693 if (IsImage()) {
1694 // Update oat estimates.
1695 UpdateImageWriter(i);
1696 }
1697
1698 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001699
1700 oat_writer.reset();
1701 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001702 }
1703 }
1704
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001705 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001706 }
1707
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001708 // If we are compiling an image, invoke the image creation routine. Else just skip.
1709 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001710 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001711 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1712 if (!CreateImageFile()) {
1713 return false;
1714 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001715 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001716 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001717 return true;
1718 }
1719
Jeff Haodcdc85b2015-12-04 14:06:18 -08001720 // Create a copy from stripped to unstripped.
1721 bool CopyStrippedToUnstripped() {
1722 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1723 // If we don't want to strip in place, copy from stripped location to unstripped location.
1724 // We need to strip after image creation because FixupElf needs to use .strtab.
1725 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1726 // If the oat file is still open, flush it.
1727 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1728 if (!FlushCloseOatFile(i)) {
1729 return false;
1730 }
1731 }
1732
1733 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1734 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1735 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1736 size_t buffer_size = 8192;
1737 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1738 while (true) {
1739 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1740 if (bytes_read <= 0) {
1741 break;
1742 }
1743 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1744 CHECK(write_ok);
1745 }
1746 if (out->FlushCloseOrErase() != 0) {
1747 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1748 return false;
1749 }
1750 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1751 }
1752 }
1753 return true;
1754 }
1755
1756 bool FlushOatFiles() {
1757 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1758 for (size_t i = 0; i < oat_files_.size(); ++i) {
1759 if (oat_files_[i].get() != nullptr) {
1760 if (oat_files_[i]->Flush() != 0) {
1761 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1762 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001763 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001764 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001765 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001766 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001767 return true;
1768 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001769
Jeff Haodcdc85b2015-12-04 14:06:18 -08001770 bool FlushCloseOatFile(size_t i) {
1771 if (oat_files_[i].get() != nullptr) {
1772 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001773 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001774 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001775 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001776 }
1777 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001778 return true;
1779 }
1780
Jeff Haodcdc85b2015-12-04 14:06:18 -08001781 bool FlushCloseOatFiles() {
1782 bool result = true;
1783 for (size_t i = 0; i < oat_files_.size(); ++i) {
1784 result &= FlushCloseOatFile(i);
1785 }
1786 return result;
1787 }
1788
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001789 void DumpTiming() {
1790 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1791 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1792 }
1793 if (dump_passes_) {
1794 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1795 }
1796 }
1797
1798 CompilerOptions* GetCompilerOptions() const {
1799 return compiler_options_.get();
1800 }
1801
Andreas Gampe10e477d2014-11-19 12:57:42 -08001802 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001803 return IsAppImage() || IsBootImage();
1804 }
1805
1806 bool IsAppImage() const {
1807 return app_image_;
1808 }
1809
1810 bool IsBootImage() const {
1811 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001812 }
1813
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001814 bool IsHost() const {
1815 return is_host_;
1816 }
1817
Calin Juravle998c2162015-12-21 15:39:33 +02001818 bool UseProfileGuidedCompilation() const {
Calin Juravle877fd962016-01-05 14:29:29 +00001819 return !profile_files_.empty() || !profile_files_fd_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02001820 }
1821
1822 bool ProcessProfiles() {
1823 DCHECK(UseProfileGuidedCompilation());
1824 ProfileCompilationInfo* info = nullptr;
Calin Juravle877fd962016-01-05 14:29:29 +00001825 bool result = false;
1826 if (profile_files_.empty()) {
1827 DCHECK(!profile_files_fd_.empty());
1828 result = ProfileAssistant::ProcessProfiles(
1829 profile_files_fd_, reference_profile_files_fd_, &info);
1830 CloseAllFds(profile_files_fd_, "profile_files_fd_");
1831 CloseAllFds(reference_profile_files_fd_, "reference_profile_files_fd_");
1832 } else {
1833 result = ProfileAssistant::ProcessProfiles(
1834 profile_files_, reference_profile_files_, &info);
Calin Juravle998c2162015-12-21 15:39:33 +02001835 }
Calin Juravle877fd962016-01-05 14:29:29 +00001836
1837 profile_compilation_info_.reset(info);
1838
1839 return result;
Calin Juravle998c2162015-12-21 15:39:33 +02001840 }
1841
1842 bool ShouldCompileBasedOnProfiles() const {
1843 DCHECK(UseProfileGuidedCompilation());
1844 // If we are given profiles, compile only if we have new information.
1845 return profile_compilation_info_ != nullptr;
1846 }
1847
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001848 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001849 template <typename T>
1850 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1851 std::vector<T*> result;
1852 result.reserve(src.size());
1853 for (const std::unique_ptr<T>& t : src) {
1854 result.push_back(t.get());
1855 }
1856 return result;
1857 }
1858
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001859 std::string GetMultiImageBootClassPath() {
1860 DCHECK(IsBootImage());
1861 DCHECK_GT(oat_filenames_.size(), 1u);
1862 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1863 // too, but need to strip all path components (they will be re-established when loading).
1864 std::ostringstream bootcp_oss;
1865 bool first_bootcp = true;
1866 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1867 if (!first_bootcp) {
1868 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001869 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001870
1871 std::string dex_loc = dex_locations_[i];
1872 std::string image_filename = image_filenames_[i];
1873
1874 // Use the dex_loc path, but the image_filename name (without path elements).
1875 size_t dex_last_slash = dex_loc.rfind('/');
1876
1877 // npos is max(size_t). That makes this a bit ugly.
1878 size_t image_last_slash = image_filename.rfind('/');
1879 size_t image_last_at = image_filename.rfind('@');
1880 size_t image_last_sep = (image_last_slash == std::string::npos)
1881 ? image_last_at
1882 : (image_last_at == std::string::npos)
1883 ? std::string::npos
1884 : std::max(image_last_slash, image_last_at);
1885 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1886
1887 if (dex_last_slash == std::string::npos) {
1888 dex_loc = image_filename.substr(image_last_sep + 1);
1889 } else {
1890 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1891 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001892 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001893
1894 // Image filenames already end with .art, no need to replace.
1895
1896 bootcp_oss << dex_loc;
1897 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001898 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001899 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001900 }
1901
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001902 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1903 // This function is used only for apps and for an app we have exactly one oat file.
1904 DCHECK(!IsBootImage());
1905 DCHECK_EQ(oat_writers_.size(), 1u);
1906 std::vector<std::string> dex_files_canonical_locations;
1907 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1908 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001909 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001910
Vladimir Marko919f5532016-01-20 19:13:01 +00001911 std::vector<std::string> parsed;
1912 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001913 auto kept_it = std::remove_if(parsed.begin(),
1914 parsed.end(),
1915 [dex_files_canonical_locations](const std::string& location) {
1916 return ContainsElement(dex_files_canonical_locations,
1917 DexFile::GetDexCanonicalLocation(location.c_str()));
1918 });
1919 parsed.erase(kept_it, parsed.end());
1920 return parsed;
1921 }
1922
1923 // Opens requested class path files and appends them to opened_dex_files.
1924 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1925 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1926 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1927 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001928 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001929 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1930 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001931 }
1932 }
1933 }
1934
Vladimir Marko49b0f452015-12-10 13:49:19 +00001935 bool PrepareImageClasses() {
1936 // If --image-classes was specified, calculate the full list of classes to include in the image.
1937 if (image_classes_filename_ != nullptr) {
1938 image_classes_ =
1939 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1940 if (image_classes_ == nullptr) {
1941 return false;
1942 }
1943 } else if (IsBootImage()) {
1944 image_classes_.reset(new std::unordered_set<std::string>);
1945 }
1946 return true;
1947 }
1948
1949 bool PrepareCompiledClasses() {
1950 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1951 // image.
1952 if (compiled_classes_filename_ != nullptr) {
1953 compiled_classes_ =
1954 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1955 if (compiled_classes_ == nullptr) {
1956 return false;
1957 }
1958 } else {
1959 compiled_classes_.reset(nullptr); // By default compile everything.
1960 }
1961 return true;
1962 }
1963
1964 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1965 const char* classes_filename,
1966 const char* tag) {
1967 std::unique_ptr<std::unordered_set<std::string>> classes;
1968 std::string error_msg;
1969 if (zip_filename != nullptr) {
1970 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1971 } else {
1972 classes.reset(ReadImageClassesFromFile(classes_filename));
1973 }
1974 if (classes == nullptr) {
1975 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1976 << classes_filename << "': " << error_msg;
1977 }
1978 return classes;
1979 }
1980
1981 bool PrepareCompiledMethods() {
1982 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1983 if (compiled_methods_filename_ != nullptr) {
1984 std::string error_msg;
1985 if (compiled_methods_zip_filename_ != nullptr) {
1986 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1987 compiled_methods_filename_,
1988 nullptr, // No post-processing.
1989 &error_msg));
1990 } else {
1991 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1992 nullptr)); // No post-processing.
1993 }
1994 if (compiled_methods_.get() == nullptr) {
1995 LOG(ERROR) << "Failed to create list of compiled methods from '"
1996 << compiled_methods_filename_ << "': " << error_msg;
1997 return false;
1998 }
1999 } else {
2000 compiled_methods_.reset(nullptr); // By default compile everything.
2001 }
2002 return true;
2003 }
2004
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002005 void PruneNonExistentDexFiles() {
2006 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2007 size_t kept = 0u;
2008 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2009 if (!OS::FileExists(dex_filenames_[i])) {
2010 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2011 } else {
2012 dex_filenames_[kept] = dex_filenames_[i];
2013 dex_locations_[kept] = dex_locations_[i];
2014 ++kept;
2015 }
2016 }
2017 dex_filenames_.resize(kept);
2018 dex_locations_.resize(kept);
2019 }
2020
2021 bool AddDexFileSources() {
2022 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2023 if (zip_fd_ != -1) {
2024 DCHECK_EQ(oat_writers_.size(), 1u);
2025 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2026 return false;
2027 }
2028 } else if (oat_writers_.size() > 1u) {
2029 // Multi-image.
2030 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2031 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2032 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2033 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2034 return false;
2035 }
2036 }
2037 } else {
2038 DCHECK_EQ(oat_writers_.size(), 1u);
2039 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2040 DCHECK_NE(dex_filenames_.size(), 0u);
2041 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2042 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2043 return false;
2044 }
2045 }
2046 }
2047 return true;
2048 }
2049
2050 void CreateOatWriters() {
2051 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2052 elf_writers_.reserve(oat_files_.size());
2053 oat_writers_.reserve(oat_files_.size());
2054 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2055 elf_writers_.emplace_back(
2056 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2057 elf_writers_.back()->Start();
2058 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2059 }
2060 }
2061
Vladimir Marko49b0f452015-12-10 13:49:19 +00002062 void SaveDexInput() {
2063 for (size_t i = 0; i < dex_files_.size(); ++i) {
2064 const DexFile* dex_file = dex_files_[i];
2065 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2066 getpid(), i));
2067 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2068 if (tmp_file.get() == nullptr) {
2069 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2070 << ". Try: adb shell chmod 777 /data/local/tmp";
2071 continue;
2072 }
2073 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2074 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2075 UNUSED(tmp_file->Flush());
2076 UNUSED(tmp_file->Close());
2077 LOG(INFO) << "Wrote input to " << tmp_file_name;
2078 }
2079 }
2080
2081 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2082 RuntimeOptions raw_options;
2083 if (boot_image_filename_.empty()) {
2084 std::string boot_class_path = "-Xbootclasspath:";
2085 boot_class_path += Join(dex_filenames_, ':');
2086 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2087 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2088 boot_class_path_locations += Join(dex_locations_, ':');
2089 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2090 } else {
2091 std::string boot_image_option = "-Ximage:";
2092 boot_image_option += boot_image_filename_;
2093 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2094 }
2095 for (size_t i = 0; i < runtime_args_.size(); i++) {
2096 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2097 }
2098
2099 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2100 raw_options.push_back(
2101 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2102
2103 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2104 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2105 // have been stripped in preopting, anyways).
2106 if (!IsBootImage()) {
2107 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2108 }
2109 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2110 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2111 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002112 // Disable Hspace compaction to save heap size virtual space.
2113 // Only need disable Hspace for OOM becasue background collector is equal to
2114 // foreground collector by default for dex2oat.
2115 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002116
Andreas Gampeace0dc12016-01-20 13:33:13 -08002117 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2118 // force the free-list implementation for large objects.
2119 if (compiler_options_->IsForceDeterminism()) {
2120 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2121 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2122
2123 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2124 // compaction (done above) and ensure that neither foreground nor background collectors
2125 // are concurrent.
2126 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2127
2128 // To make identity hashcode deterministic, set a known seed.
2129 mirror::Object::SetHashCodeSeed(987654321U);
2130 }
2131
Vladimir Marko49b0f452015-12-10 13:49:19 +00002132 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2133 LOG(ERROR) << "Failed to parse runtime options";
2134 return false;
2135 }
2136 return true;
2137 }
2138
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002139 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002140 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2141 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002142 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002143 LOG(ERROR) << "Failed to create runtime";
2144 return false;
2145 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002146 runtime_.reset(Runtime::Current());
2147 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002148 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2149 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002150 if (!runtime_->HasCalleeSaveMethod(type)) {
2151 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002152 }
2153 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002154 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002155
2156 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2157 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002158 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002159
Vladimir Marko307dac92015-10-20 11:20:09 +01002160 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002161
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002162 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2163 // Runtime::Start, give it away now so that we don't starve GC.
2164 Thread* self = Thread::Current();
2165 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002166
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002167 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002168 }
2169
Jeff Haodcdc85b2015-12-04 14:06:18 -08002170 // 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 -08002171 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002172 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002173 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002174 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002175 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176 image_filenames_.push_back(app_image_file_name_.c_str());
2177 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002178 if (!image_writer_->Write(app_image_fd_,
2179 image_filenames_,
2180 oat_fd_,
2181 oat_filenames_,
2182 oat_location_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002183 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002184 return false;
2185 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002186
Jeff Haodcdc85b2015-12-04 14:06:18 -08002187 // We need the OatDataBegin entries.
2188 std::map<const char*, uintptr_t> oat_data_begins;
2189 for (const char* oat_filename : oat_filenames_) {
2190 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2191 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002192 // Destroy ImageWriter before doing FixupElf.
2193 image_writer_.reset();
2194
Jeff Haodcdc85b2015-12-04 14:06:18 -08002195 for (const char* oat_filename : oat_filenames_) {
2196 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2197 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2198 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2199 if (oat_file.get() == nullptr) {
2200 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2201 return false;
2202 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002203
Jeff Haodcdc85b2015-12-04 14:06:18 -08002204 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002205
Jeff Haodcdc85b2015-12-04 14:06:18 -08002206 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2207 oat_file->Erase();
2208 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2209 return false;
2210 }
2211
2212 if (oat_file->FlushCloseOrErase()) {
2213 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2214 return false;
2215 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002216 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002217 }
2218
2219 return true;
2220 }
2221
2222 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002223 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2224 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002225 std::function<std::string(const char*)> process = DotToDescriptor;
2226 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002227 }
2228
2229 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002230 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002231 const char* zip_filename,
2232 const char* image_classes_filename,
2233 std::string* error_msg) {
2234 std::function<std::string(const char*)> process = DotToDescriptor;
2235 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2236 }
2237
2238 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2239 // the given function.
2240 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2241 const char* input_filename, std::function<std::string(const char*)>* process) {
2242 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2243 if (input_file.get() == nullptr) {
2244 LOG(ERROR) << "Failed to open input file " << input_filename;
2245 return nullptr;
2246 }
2247 std::unique_ptr<std::unordered_set<std::string>> result(
2248 ReadCommentedInputStream(*input_file, process));
2249 input_file->close();
2250 return result.release();
2251 }
2252
2253 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2254 // Post-process each line with the given function.
2255 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002256 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002257 const char* input_filename,
2258 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002259 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002260 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2261 if (zip_archive.get() == nullptr) {
2262 return nullptr;
2263 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002264 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002266 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002267 zip_filename, error_msg->c_str());
2268 return nullptr;
2269 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002270 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2271 input_filename,
2272 error_msg));
2273 if (input_file.get() == nullptr) {
2274 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002275 zip_filename, error_msg->c_str());
2276 return nullptr;
2277 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002278 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2279 input_file->Size());
2280 std::istringstream input_stream(input_string);
2281 return ReadCommentedInputStream(input_stream, process);
2282 }
2283
2284 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2285 // with the given function.
2286 static std::unordered_set<std::string>* ReadCommentedInputStream(
2287 std::istream& in_stream,
2288 std::function<std::string(const char*)>* process) {
2289 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2290 new std::unordered_set<std::string>);
2291 while (in_stream.good()) {
2292 std::string dot;
2293 std::getline(in_stream, dot);
2294 if (StartsWith(dot, "#") || dot.empty()) {
2295 continue;
2296 }
2297 if (process != nullptr) {
2298 std::string descriptor((*process)(dot.c_str()));
2299 image_classes->insert(descriptor);
2300 } else {
2301 image_classes->insert(dot);
2302 }
2303 }
2304 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002305 }
2306
Mathieu Chartier49285c52014-12-02 15:43:48 -08002307 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002308 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2309 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002310 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002311 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002312 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002313 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002314 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2315 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002316 }
2317
Jeff Haodcdc85b2015-12-04 14:06:18 -08002318 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2319 std::string res(image_filename);
2320 size_t last_slash = res.rfind('/');
2321 if (last_slash == std::string::npos || last_slash == 0) {
2322 return res;
2323 }
2324 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2325 if (penultimate_slash == std::string::npos) {
2326 return res;
2327 }
2328 // Check that the string in-between is the expected one.
2329 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2330 GetInstructionSetString(isa)) {
2331 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2332 return res;
2333 }
2334 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2335 }
2336
2337 // Update the estimate for the oat file with the given index.
2338 void UpdateImageWriter(size_t index) {
2339 DCHECK(image_writer_ != nullptr);
2340 DCHECK_LT(index, oat_filenames_.size());
2341
2342 image_writer_->UpdateOatFile(oat_filenames_[index]);
2343 }
2344
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002345 std::unique_ptr<CompilerOptions> compiler_options_;
2346 Compiler::Kind compiler_kind_;
2347
2348 InstructionSet instruction_set_;
2349 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2350
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002351 uint32_t image_file_location_oat_checksum_;
2352 uintptr_t image_file_location_oat_data_begin_;
2353 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002354 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2355
Vladimir Marko307dac92015-10-20 11:20:09 +01002356 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002357
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002358 DexFileToMethodInlinerMap method_inliner_map_;
2359 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2360
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002361 std::unique_ptr<Runtime> runtime_;
2362
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002363 // Ownership for the class path files.
2364 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2365
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002366 size_t thread_count_;
2367 uint64_t start_ns_;
2368 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002369 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002370 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002371 std::vector<const char*> oat_filenames_;
2372 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002373 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002374 std::vector<const char*> dex_filenames_;
2375 std::vector<const char*> dex_locations_;
2376 int zip_fd_;
2377 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002378 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002379 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002380 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002381 uintptr_t image_base_;
2382 const char* image_classes_zip_filename_;
2383 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002384 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002385 const char* compiled_classes_zip_filename_;
2386 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002387 const char* compiled_methods_zip_filename_;
2388 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002389 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2390 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002391 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002392 bool app_image_;
2393 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002394 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002395 bool is_host_;
2396 std::string android_root_;
2397 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002398 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002399 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002400 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002401
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2403 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2404 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002405 std::unique_ptr<ImageWriter> image_writer_;
2406 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002407
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002408 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2409 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2410
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 std::vector<std::string> verbose_methods_;
2412 bool dump_stats_;
2413 bool dump_passes_;
2414 bool dump_timing_;
2415 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002416 std::string swap_file_name_;
2417 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002418 std::string app_image_file_name_;
2419 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002420 std::vector<std::string> profile_files_;
2421 std::vector<std::string> reference_profile_files_;
Calin Juravle877fd962016-01-05 14:29:29 +00002422 std::vector<uint32_t> profile_files_fd_;
2423 std::vector<uint32_t> reference_profile_files_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002424 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002425 TimingLogger* timings_;
2426 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002427 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2428 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2429
2430 // Backing storage.
2431 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002432
Andreas Gampeace0dc12016-01-20 13:33:13 -08002433 // See CompilerOptions.force_determinism_.
2434 bool force_determinism_;
2435
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002436 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2437};
2438
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002439static void b13564922() {
2440#if defined(__linux__) && defined(__arm__)
2441 int major, minor;
2442 struct utsname uts;
2443 if (uname(&uts) != -1 &&
2444 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2445 ((major < 3) || ((major == 3) && (minor < 4)))) {
2446 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2447 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2448 int old_personality = personality(0xffffffff);
2449 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2450 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2451 if (new_personality == -1) {
2452 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2453 }
2454 }
2455 }
2456#endif
2457}
2458
Andreas Gampe10e477d2014-11-19 12:57:42 -08002459static int CompileImage(Dex2Oat& dex2oat) {
2460 dex2oat.Compile();
2461
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002462 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002463 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002464 return EXIT_FAILURE;
2465 }
2466
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002467 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2468 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2469 // image writer will require this fd to generate the image.
2470 if (dex2oat.ShouldKeepOatFileOpen()) {
2471 if (!dex2oat.FlushOatFiles()) {
2472 return EXIT_FAILURE;
2473 }
2474 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002475 return EXIT_FAILURE;
2476 }
2477
Jeff Haodcdc85b2015-12-04 14:06:18 -08002478 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002479 if (!dex2oat.HandleImage()) {
2480 return EXIT_FAILURE;
2481 }
2482
2483 // When given --host, finish early without stripping.
2484 if (dex2oat.IsHost()) {
2485 dex2oat.DumpTiming();
2486 return EXIT_SUCCESS;
2487 }
2488
Jeff Haodcdc85b2015-12-04 14:06:18 -08002489 // Copy stripped to unstripped location, if necessary.
2490 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002491 return EXIT_FAILURE;
2492 }
2493
Jeff Haodcdc85b2015-12-04 14:06:18 -08002494 // FlushClose again, as stripping might have re-opened the oat files.
2495 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002496 return EXIT_FAILURE;
2497 }
2498
2499 dex2oat.DumpTiming();
2500 return EXIT_SUCCESS;
2501}
2502
2503static int CompileApp(Dex2Oat& dex2oat) {
2504 dex2oat.Compile();
2505
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002506 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002507 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002508 return EXIT_FAILURE;
2509 }
2510
Jeff Haodcdc85b2015-12-04 14:06:18 -08002511 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002512 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002513
2514 // When given --host, finish early without stripping.
2515 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002516 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002517 return EXIT_FAILURE;
2518 }
2519
2520 dex2oat.DumpTiming();
2521 return EXIT_SUCCESS;
2522 }
2523
Jeff Haodcdc85b2015-12-04 14:06:18 -08002524 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2525 // stripped versions. If this is given, we expect to be able to open writable files by name.
2526 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002527 return EXIT_FAILURE;
2528 }
2529
Jeff Haodcdc85b2015-12-04 14:06:18 -08002530 // Flush and close the files.
2531 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002532 return EXIT_FAILURE;
2533 }
2534
2535 dex2oat.DumpTiming();
2536 return EXIT_SUCCESS;
2537}
2538
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002539static int dex2oat(int argc, char** argv) {
2540 b13564922();
2541
2542 TimingLogger timings("compiler", false, false);
2543
2544 Dex2Oat dex2oat(&timings);
2545
2546 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2547 dex2oat.ParseArgs(argc, argv);
2548
Calin Juravle998c2162015-12-21 15:39:33 +02002549 // Process profile information and assess if we need to do a profile guided compilation.
2550 // This operation involves I/O.
2551 if (dex2oat.UseProfileGuidedCompilation()) {
2552 if (dex2oat.ProcessProfiles()) {
2553 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2554 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2555 return EXIT_SUCCESS;
2556 }
2557 } else {
2558 LOG(WARNING) << "Failed to process profile files";
2559 return EXIT_FAILURE;
2560 }
2561 }
2562
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002563 // Check early that the result of compilation can be written
2564 if (!dex2oat.OpenFile()) {
2565 return EXIT_FAILURE;
2566 }
2567
Andreas Gampe046c7062015-05-18 23:22:54 -07002568 // Print the complete line when any of the following is true:
2569 // 1) Debug build
2570 // 2) Compiling an image
2571 // 3) Compiling with --host
2572 // 4) Compiling on the host (not a target build)
2573 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002574 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002575 LOG(INFO) << CommandLine();
2576 } else {
2577 LOG(INFO) << StrippedCommandLine();
2578 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002579
2580 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002581 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002582 return EXIT_FAILURE;
2583 }
2584
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002585 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002586 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002587 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002588 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002589 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002590 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002591
2592 dex2oat.Shutdown();
2593 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002594}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002595} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002596
2597int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002598 int result = art::dex2oat(argc, argv);
2599 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2600 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2601 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002602 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002603 exit(result);
2604 }
2605 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002606}