blob: 374d0d37a188761f03f1dc9c718c78cbd8d4c813 [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 Rogersd582fa42014-11-05 23:46:43 -080035#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080036#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000037#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080039#include "base/macros.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000040#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "base/stl_util.h"
42#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "base/timing_logger.h"
45#include "base/unix_file/fd_file.h"
46#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000047#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000048#include "compiler_callbacks.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000049#include "debug/method_debug_info.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080050#include "dex/pass_manager.h"
Ian Rogerse63db272014-07-15 15:36:11 -070051#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000052#include "dex/quick_compiler_callbacks.h"
53#include "dex/verification_results.h"
54#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080056#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080057#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070058#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000059#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "gc/space/image_space.h"
61#include "gc/space/space-inl.h"
62#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070063#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020064#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "leb128.h"
Vladimir Marko944da602016-02-19 12:27:55 +000066#include "linker/multi_oat_relative_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/class-inl.h"
68#include "mirror/class_loader.h"
69#include "mirror/object-inl.h"
70#include "mirror/object_array-inl.h"
71#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "os.h"
73#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000074#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "ScopedLocalRef.h"
76#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070077#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "well_known_classes.h"
79#include "zip_archive.h"
80
81namespace art {
82
Brian Carlstrom6449c622014-02-10 23:48:36 -080083static int original_argc;
84static char** original_argv;
85
86static std::string CommandLine() {
87 std::vector<std::string> command;
88 for (int i = 0; i < original_argc; ++i) {
89 command.push_back(original_argv[i]);
90 }
91 return Join(command, ' ');
92}
93
Andreas Gampe046c7062015-05-18 23:22:54 -070094// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
95// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
96// locations are all staged).
97static std::string StrippedCommandLine() {
98 std::vector<std::string> command;
99
100 // Do a pre-pass to look for zip-fd.
101 bool saw_zip_fd = false;
102 for (int i = 0; i < original_argc; ++i) {
103 if (StartsWith(original_argv[i], "--zip-fd=")) {
104 saw_zip_fd = true;
105 break;
106 }
107 }
108
109 // Now filter out things.
110 for (int i = 0; i < original_argc; ++i) {
111 // All runtime-arg parameters are dropped.
112 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
113 i++; // Drop the next part, too.
114 continue;
115 }
116
117 // Any instruction-setXXX is dropped.
118 if (StartsWith(original_argv[i], "--instruction-set")) {
119 continue;
120 }
121
122 // The boot image is dropped.
123 if (StartsWith(original_argv[i], "--boot-image=")) {
124 continue;
125 }
126
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800127 // The image format is dropped.
128 if (StartsWith(original_argv[i], "--image-format=")) {
129 continue;
130 }
131
Andreas Gampe046c7062015-05-18 23:22:54 -0700132 // This should leave any dex-file and oat-file options, describing what we compiled.
133
134 // However, we prefer to drop this when we saw --zip-fd.
135 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700136 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700137 if (StartsWith(original_argv[i], "--zip-") ||
138 StartsWith(original_argv[i], "--dex-") ||
139 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700140 StartsWith(original_argv[i], "--swap-") ||
141 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700142 continue;
143 }
144 }
145
146 command.push_back(original_argv[i]);
147 }
148
149 // Construct the final output.
150 if (command.size() <= 1U) {
151 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
152 return "Starting dex2oat.";
153 }
154 return Join(command, ' ');
155}
156
Brian Carlstrom7940e442013-07-12 13:46:57 -0700157static void UsageErrorV(const char* fmt, va_list ap) {
158 std::string error;
159 StringAppendV(&error, fmt, ap);
160 LOG(ERROR) << error;
161}
162
163static void UsageError(const char* fmt, ...) {
164 va_list ap;
165 va_start(ap, fmt);
166 UsageErrorV(fmt, ap);
167 va_end(ap);
168}
169
Andreas Gampe794ad762015-02-23 08:12:24 -0800170NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 va_list ap;
172 va_start(ap, fmt);
173 UsageErrorV(fmt, ap);
174 va_end(ap);
175
Brian Carlstrom6449c622014-02-10 23:48:36 -0800176 UsageError("Command: %s", CommandLine().c_str());
177
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 UsageError("Usage: dex2oat [options]...");
179 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100180 UsageError(" -j<number>: specifies the number of threads used for compilation.");
181 UsageError(" Default is the number of detected hardware threads available on the");
182 UsageError(" host system.");
183 UsageError(" Example: -j12");
184 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700185 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 UsageError(" Example: --dex-file=/system/framework/core.jar");
187 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700188 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
189 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
190 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
191 UsageError(" --dex-location=/system/framework/core.jar");
192 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
194 UsageError(" containing a classes.dex file to compile.");
195 UsageError(" Example: --zip-fd=5");
196 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700197 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
198 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
200 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800201 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 UsageError(" Example: --oat-file=/system/framework/boot.oat");
203 UsageError("");
204 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900205 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 UsageError("");
207 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
208 UsageError(" to the file descriptor specified by --oat-fd.");
209 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
210 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
213 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 UsageError(" Example: --image=/system/framework/boot.art");
216 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800217 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800218 UsageError(" Which format to store the image.");
219 UsageError(" Example: --image-format=lz4");
220 UsageError(" Default: uncompressed");
221 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700222 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
223 UsageError(" Example: --image=frameworks/base/preloaded-classes");
224 UsageError("");
225 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
226 UsageError(" Example: --base=0x50000000");
227 UsageError("");
228 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000229 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000231 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000232 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 UsageError("");
234 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
235 UsageError(" Example: --android-root=out/host/linux-x86");
236 UsageError(" Default: $ANDROID_ROOT");
237 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800238 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700239 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 UsageError(" Example: --instruction-set=x86");
241 UsageError(" Default: arm");
242 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700243 UsageError(" --instruction-set-features=...,: Specify instruction set features");
244 UsageError(" Example: --instruction-set-features=div");
245 UsageError(" Default: default");
246 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700247 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
248 UsageError(" Default: disabled");
249 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800250 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800252 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100253 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100255 UsageError(" --compiler-filter="
256 "(verify-none"
257 "|interpret-only"
258 "|space"
259 "|balanced"
260 "|speed"
261 "|everything"
262 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700263 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800264 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800265 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800266 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
268 UsageError(" method for compiler filter tuning.");
269 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
270 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
271 UsageError("");
272 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
273 UsageError(" method for compiler filter tuning.");
274 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
275 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
276 UsageError("");
277 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
278 UsageError(" method for compiler filter tuning.");
279 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
280 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
281 UsageError("");
282 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
283 UsageError(" method for compiler filter tuning.");
284 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
285 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
286 UsageError("");
287 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
288 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700289 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
290 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800291 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
292 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
293 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100294 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
295 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100296 UsageError(" Has priority over the --compiler-filter option. Intended for ");
297 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100298 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
299 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
300 UsageError("");
301 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
302 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100303 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
304 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100305 UsageError(" Example: --inline-max-code-units=%d",
306 CompilerOptions::kDefaultInlineMaxCodeUnits);
307 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
308 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700309 UsageError(" --dump-timing: display a breakdown of where time was spent");
310 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700311 UsageError(" --include-patch-information: Include patching information so the generated code");
312 UsageError(" can have its base address moved without full recompilation.");
313 UsageError("");
314 UsageError(" --no-include-patch-information: Do not include patching information.");
315 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100316 UsageError(" -g");
317 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
318 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000319 UsageError(" If used without --native-debuggable, it will be best-effort only.");
320 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700321 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100322 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100323 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000324 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
325 UsageError(" debug information necessary to print backtraces. (disabled by default)");
326 UsageError("");
327 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
328 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000329 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000330 UsageError("");
331 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
332 UsageError(" Implies --debuggable.");
333 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
335 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
336 UsageError(" Use a separate --runtime-arg switch for each argument.");
337 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700338 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000339 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700340 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000341 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
342 UsageError(" Cannot be used together with --profile-file.");
343 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700344 UsageError(" --print-pass-names: print a list of pass names");
345 UsageError("");
346 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
347 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
348 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700349 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
350 "with the setting.");
351 UsageError(" Will print default if no overridden setting exists.");
352 UsageError("");
353 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
354 "Pass2Name:Pass2OptionName:Pass2Option#");
355 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
356 UsageError(" Separator used between options is a comma.");
357 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800358 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
359 UsageError(" Example: --swap-file=/data/tmp/swap.001");
360 UsageError("");
361 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
362 UsageError(" Example: --swap-fd=10");
363 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700364 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
365 UsageError(" Example: --app-image-fd=10");
366 UsageError("");
367 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
368 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
369 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800370 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
371 "input dex file.");
372 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000373 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
374 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
375 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
376 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 std::cerr << "See log for usage error information\n";
378 exit(EXIT_FAILURE);
379}
380
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381// The primary goal of the watchdog is to prevent stuck build servers
382// during development when fatal aborts lead to a cascade of failures
383// that result in a deadlock.
384class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800385// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386#undef CHECK_PTHREAD_CALL
387#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
388 do { \
389 int rc = call args; \
390 if (rc != 0) { \
391 errno = rc; \
392 std::string message(# call); \
393 message += " failed for "; \
394 message += reason; \
395 Fatal(message); \
396 } \
397 } while (false)
398
399 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700400 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700401 is_watch_dog_enabled_ = is_watch_dog_enabled;
402 if (!is_watch_dog_enabled_) {
403 return;
404 }
405 shutting_down_ = false;
406 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700407 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
408 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700409 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
412 }
413 ~WatchDog() {
414 if (!is_watch_dog_enabled_) {
415 return;
416 }
417 const char* reason = "dex2oat watch dog thread shutdown";
418 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
419 shutting_down_ = true;
420 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
422
Kenny Root51316382014-05-13 14:59:37 -0700423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424
425 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
427 }
428
429 private:
430 static void* CallBack(void* arg) {
431 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
432 ::art::SetThreadName("dex2oat watch dog");
433 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700434 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700435 }
436
Andreas Gampe794ad762015-02-23 08:12:24 -0800437 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700438 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
439 // it's rather easy to hang in unwinding.
440 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
441 // logcat logging or stderr output.
442 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 exit(1);
444 }
445
446 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
448 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700449 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450 timespec timeout_ts;
451 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
452 const char* reason = "dex2oat watch dog thread waiting";
453 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
454 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800455 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700456 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700457 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
458 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 } else if (rc != 0) {
460 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
461 strerror(errno)));
462 Fatal(message.c_str());
463 }
464 }
465 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
466 }
467
468 // 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 -0700469 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700470 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800471
Andreas Gampe540138a2015-09-14 15:34:38 -0700472 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
473 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
474 // itself before that watchdog would take down the system server.
475 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700476
477 bool is_watch_dog_enabled_;
478 bool shutting_down_;
479 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
480 pthread_mutex_t mutex_;
481 pthread_cond_t cond_;
482 pthread_attr_t attr_;
483 pthread_t pthread_;
484};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800486static constexpr size_t kMinDexFilesForSwap = 2;
487static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
488
489static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
490 if (is_image) {
491 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
492 return false;
493 }
494 if (dex_files.size() < kMinDexFilesForSwap) {
495 // If there are less dex files than the threshold, assume it's gonna be fine.
496 return false;
497 }
498 size_t dex_files_size = 0;
499 for (const auto* dex_file : dex_files) {
500 dex_files_size += dex_file->GetHeader().file_size_;
501 }
502 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
503}
504
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505class Dex2Oat FINAL {
506 public:
507 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100508 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509 instruction_set_(kRuntimeISA),
510 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000511 image_file_location_oat_checksum_(0),
512 image_file_location_oat_data_begin_(0),
513 image_patch_delta_(0),
514 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700515 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800516 method_inliner_map_(),
517 runtime_(nullptr),
518 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
519 start_ns_(NanoTime()),
520 oat_fd_(-1),
521 zip_fd_(-1),
522 image_base_(0U),
523 image_classes_zip_filename_(nullptr),
524 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800525 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800526 compiled_classes_zip_filename_(nullptr),
527 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700528 compiled_methods_zip_filename_(nullptr),
529 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700530 app_image_(false),
531 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800532 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800533 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000534 class_loader_(nullptr),
535 elf_writers_(),
536 oat_writers_(),
537 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000538 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700539 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000540 opened_dex_files_maps_(),
541 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000542 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800543 dump_stats_(false),
544 dump_passes_(false),
545 dump_timing_(false),
546 dump_slow_timing_(kIsDebugBuild),
Calin Juravle2e2db782016-02-23 12:00:03 +0000547 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800548 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000549 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800550 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000551 force_determinism_(false)
552 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800553
554 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800555 // Log completion time before deleting the runtime_, because this accesses
556 // the runtime.
557 LogCompletionTime();
558
Vladimir Marko307dac92015-10-20 11:20:09 +0100559 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
560 // We want to just exit on non-debug builds, not bringing the runtime down
561 // in an orderly fashion. So release the following fields.
562 driver_.release();
563 image_writer_.release();
564 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
565 dex_file.release();
566 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000567 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
568 map.release();
569 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800570 for (std::unique_ptr<File>& oat_file : oat_files_) {
571 oat_file.release();
572 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100573 runtime_.release();
574 verification_results_.release();
575 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100576 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577 }
578
Roland Levillain9ec5e222015-08-17 20:18:41 +0100579 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800580 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800581 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800582 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000583 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800584 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100585 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800586
Roland Levillain9ec5e222015-08-17 20:18:41 +0100587 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000588 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100589 }
590
591 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000592 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100593 }
594
Calin Juravle877fd962016-01-05 14:29:29 +0000595 void ParseFdForCollection(const StringPiece& option,
596 const char* arg_name,
597 std::vector<uint32_t>* fds) {
598 uint32_t fd;
599 ParseUintOption(option, arg_name, &fd, Usage);
600 fds->push_back(fd);
601 }
602
Roland Levillain9ec5e222015-08-17 20:18:41 +0100603 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000604 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100605 }
606
607 void ParseBase(const StringPiece& option) {
608 DCHECK(option.starts_with("--base="));
609 const char* image_base_str = option.substr(strlen("--base=")).data();
610 char* end;
611 image_base_ = strtoul(image_base_str, &end, 16);
612 if (end == image_base_str || *end != '\0') {
613 Usage("Failed to parse hexadecimal value for option %s", option.data());
614 }
615 }
616
617 void ParseInstructionSet(const StringPiece& option) {
618 DCHECK(option.starts_with("--instruction-set="));
619 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
620 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
621 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
622 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
623 buf.get()[instruction_set_str.length()] = 0;
624 instruction_set_ = GetInstructionSetFromString(buf.get());
625 // arm actually means thumb2.
626 if (instruction_set_ == InstructionSet::kArm) {
627 instruction_set_ = InstructionSet::kThumb2;
628 }
629 }
630
631 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
632 DCHECK(option.starts_with("--instruction-set-variant="));
633 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
634 instruction_set_features_.reset(
635 InstructionSetFeatures::FromVariant(
636 instruction_set_, str.as_string(), &parser_options->error_msg));
637 if (instruction_set_features_.get() == nullptr) {
638 Usage("%s", parser_options->error_msg.c_str());
639 }
640 }
641
642 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
643 DCHECK(option.starts_with("--instruction-set-features="));
644 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
645 if (instruction_set_features_.get() == nullptr) {
646 instruction_set_features_.reset(
647 InstructionSetFeatures::FromVariant(
648 instruction_set_, "default", &parser_options->error_msg));
649 if (instruction_set_features_.get() == nullptr) {
650 Usage("Problem initializing default instruction set features variant: %s",
651 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800653 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100654 instruction_set_features_.reset(
655 instruction_set_features_->AddFeaturesFromString(str.as_string(),
656 &parser_options->error_msg));
657 if (instruction_set_features_.get() == nullptr) {
658 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
659 }
660 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800661
Roland Levillain9ec5e222015-08-17 20:18:41 +0100662 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
663 DCHECK(option.starts_with("--compiler-backend="));
664 parser_options->requested_specific_compiler = true;
665 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
666 if (backend_str == "Quick") {
667 compiler_kind_ = Compiler::kQuick;
668 } else if (backend_str == "Optimizing") {
669 compiler_kind_ = Compiler::kOptimizing;
670 } else {
671 Usage("Unknown compiler backend: %s", backend_str.data());
672 }
673 }
674
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800675 void ParseImageFormat(const StringPiece& option) {
676 const StringPiece substr("--image-format=");
677 DCHECK(option.starts_with(substr));
678 const StringPiece format_str = option.substr(substr.length());
679 if (format_str == "lz4") {
680 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800681 } else if (format_str == "lz4hc") {
682 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800683 } else if (format_str == "uncompressed") {
684 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
685 } else {
686 Usage("Unknown image format: %s", format_str.data());
687 }
688 }
689
Jeff Hao436183f2016-01-12 16:36:50 -0800690 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800691 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700692 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
693
694 if (IsAppImage() && IsBootImage()) {
695 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
696 }
697
Nicolas Geoffray0c6e3342016-03-04 11:38:14 +0000698 if (IsBootImage()) {
699 // We need the boot image to always be debuggable.
700 // TODO: Remove this once we better deal with full frame deoptimization.
701 compiler_options_->debuggable_ = true;
702 }
703
Jeff Haodcdc85b2015-12-04 14:06:18 -0800704 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 Usage("Output must be supplied with either --oat-file or --oat-fd");
706 }
707
Jeff Haodcdc85b2015-12-04 14:06:18 -0800708 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800709 Usage("--oat-file should not be used with --oat-fd");
710 }
711
Roland Levillain9ec5e222015-08-17 20:18:41 +0100712 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800713 Usage("--oat-symbols should not be used with --oat-fd");
714 }
715
Roland Levillain9ec5e222015-08-17 20:18:41 +0100716 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800717 Usage("--oat-symbols should not be used with --host");
718 }
719
Jeff Haodcdc85b2015-12-04 14:06:18 -0800720 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800721 Usage("--oat-fd should not be used with --image");
722 }
723
Jeff Haodcdc85b2015-12-04 14:06:18 -0800724 if (!parser_options->oat_symbols.empty() &&
725 parser_options->oat_symbols.size() != oat_filenames_.size()) {
726 Usage("--oat-file arguments do not match --oat-symbols arguments");
727 }
728
729 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
730 Usage("--oat-file arguments do not match --image arguments");
731 }
732
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800733 if (android_root_.empty()) {
734 const char* android_root_env_var = getenv("ANDROID_ROOT");
735 if (android_root_env_var == nullptr) {
736 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700737 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800738 android_root_ += android_root_env_var;
739 }
740
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700741 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100742 parser_options->boot_image_filename += android_root_;
743 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800744 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100745 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000746 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800747 }
748
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700749 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800750 Usage("--image-classes should only be used with --image");
751 }
752
Vladimir Marko49b0f452015-12-10 13:49:19 +0000753 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 Usage("--image-classes should not be used with --boot-image");
755 }
756
757 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
758 Usage("--image-classes-zip should be used with --image-classes");
759 }
760
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700761 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800762 Usage("--compiled-classes should only be used with --image");
763 }
764
Vladimir Marko49b0f452015-12-10 13:49:19 +0000765 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800766 Usage("--compiled-classes should not be used with --boot-image");
767 }
768
769 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
770 Usage("--compiled-classes-zip should be used with --compiled-classes");
771 }
772
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800773 if (dex_filenames_.empty() && zip_fd_ == -1) {
774 Usage("Input must be supplied with either --dex-file or --zip-fd");
775 }
776
777 if (!dex_filenames_.empty() && zip_fd_ != -1) {
778 Usage("--dex-file should not be used with --zip-fd");
779 }
780
781 if (!dex_filenames_.empty() && !zip_location_.empty()) {
782 Usage("--dex-file should not be used with --zip-location");
783 }
784
785 if (dex_locations_.empty()) {
786 for (const char* dex_file_name : dex_filenames_) {
787 dex_locations_.push_back(dex_file_name);
788 }
789 } else if (dex_locations_.size() != dex_filenames_.size()) {
790 Usage("--dex-location arguments do not match --dex-file arguments");
791 }
792
Jeff Haodcdc85b2015-12-04 14:06:18 -0800793 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
794 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
795 Usage("--oat-file arguments must be singular or match --dex-file arguments");
796 }
797 }
798
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800799 if (zip_fd_ != -1 && zip_location_.empty()) {
800 Usage("--zip-location should be supplied with --zip-fd");
801 }
802
Vladimir Marko49b0f452015-12-10 13:49:19 +0000803 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800804 if (image_base_ == 0) {
805 Usage("Non-zero --base not specified");
806 }
807 }
808
Calin Juravle2e2db782016-02-23 12:00:03 +0000809 if (!profile_file_.empty() && (profile_file_fd_ != kInvalidFd)) {
810 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200811 }
812
Roland Levillain9ec5e222015-08-17 20:18:41 +0100813 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800814 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800815 }
816
817 // If no instruction set feature was given, use the default one for the target
818 // instruction set.
819 if (instruction_set_features_.get() == nullptr) {
820 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100821 InstructionSetFeatures::FromVariant(
822 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800823 if (instruction_set_features_.get() == nullptr) {
824 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100825 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800826 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800827 }
828
829 if (instruction_set_ == kRuntimeISA) {
830 std::unique_ptr<const InstructionSetFeatures> runtime_features(
831 InstructionSetFeatures::FromCppDefines());
832 if (!instruction_set_features_->Equals(runtime_features.get())) {
833 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
834 << *instruction_set_features_ << ") and those of dex2oat executable ("
835 << *runtime_features <<") for the command line:\n"
836 << CommandLine();
837 }
838 }
839
Roland Levillaina215b952015-08-07 11:38:32 +0100840 // It they are not set, use default values for inlining settings.
841 // TODO: We should rethink the compiler filter. We mostly save
842 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000843 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
844 compiler_options_->inline_depth_limit_ =
845 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100846 // Implementation of the space filter: limit inlining depth.
847 ? CompilerOptions::kSpaceFilterInlineDepthLimit
848 : CompilerOptions::kDefaultInlineDepthLimit;
849 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000850 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
851 compiler_options_->inline_max_code_units_ =
852 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100853 // Implementation of the space filter: limit inlining max code units.
854 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
855 : CompilerOptions::kDefaultInlineMaxCodeUnits;
856 }
857
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800858 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800859 // Set the compilation target's implicit checks options.
860 switch (instruction_set_) {
861 case kArm:
862 case kThumb2:
863 case kArm64:
864 case kX86:
865 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700866 case kMips:
867 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000868 compiler_options_->implicit_null_checks_ = true;
869 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800870 break;
871
872 default:
873 // Defaults are correct.
874 break;
875 }
876
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000877 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800878
Jeff Hao436183f2016-01-12 16:36:50 -0800879 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800880 Usage("--multi-image can only be used when creating boot images");
881 }
Jeff Hao436183f2016-01-12 16:36:50 -0800882 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800883 Usage("--multi-image cannot be used with multiple image names");
884 }
885
886 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
887 if (!kIsTargetBuild && IsBootImage()) {
888 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800889 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800890 }
891 }
892
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800893 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100894 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800895 watchdog_.reset(new WatchDog(true));
896 }
897
898 // Fill some values into the key-value store for the oat header.
899 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800900
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800901 // Automatically force determinism for the boot image in a host build if the default GC is CMS
902 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
903 // one by passing the option `-Xgc:nonconcurrent` (see below).
904 if (!kIsTargetBuild && IsBootImage()) {
905 if (SupportsDeterministicCompilation()) {
906 force_determinism_ = true;
907 } else {
908 LOG(WARNING) << "Deterministic compilation is disabled.";
909 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800910 }
911 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100912 }
913
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800914 static bool SupportsDeterministicCompilation() {
915 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
916 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
917 !kEmitCompilerReadBarrier;
918 }
919
Jeff Hao436183f2016-01-12 16:36:50 -0800920 void ExpandOatAndImageFilenames() {
921 std::string base_oat = oat_filenames_[0];
922 size_t last_oat_slash = base_oat.rfind('/');
923 if (last_oat_slash == std::string::npos) {
924 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
925 }
926 // We also need to honor path components that were encoded through '@'. Otherwise the loading
927 // code won't be able to find the images.
928 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
929 last_oat_slash = base_oat.rfind('@');
930 }
931 base_oat = base_oat.substr(0, last_oat_slash + 1);
932
933 std::string base_img = image_filenames_[0];
934 size_t last_img_slash = base_img.rfind('/');
935 if (last_img_slash == std::string::npos) {
936 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
937 }
938 // We also need to honor path components that were encoded through '@'. Otherwise the loading
939 // code won't be able to find the images.
940 if (base_img.find('@', last_img_slash) != std::string::npos) {
941 last_img_slash = base_img.rfind('@');
942 }
943
944 // Get the prefix, which is the primary image name (without path components). Strip the
945 // extension.
946 std::string prefix = base_img.substr(last_img_slash + 1);
947 if (prefix.rfind('.') != std::string::npos) {
948 prefix = prefix.substr(0, prefix.rfind('.'));
949 }
950 if (!prefix.empty()) {
951 prefix = prefix + "-";
952 }
953
954 base_img = base_img.substr(0, last_img_slash + 1);
955
956 // Note: we have some special case here for our testing. We have to inject the differentiating
957 // parts for the different core images.
958 std::string infix; // Empty infix by default.
959 {
960 // Check the first name.
961 std::string dex_file = oat_filenames_[0];
962 size_t last_dex_slash = dex_file.rfind('/');
963 if (last_dex_slash != std::string::npos) {
964 dex_file = dex_file.substr(last_dex_slash + 1);
965 }
966 size_t last_dex_dot = dex_file.rfind('.');
967 if (last_dex_dot != std::string::npos) {
968 dex_file = dex_file.substr(0, last_dex_dot);
969 }
970 if (StartsWith(dex_file, "core-")) {
971 infix = dex_file.substr(strlen("core"));
972 }
973 }
974
975 // Now create the other names. Use a counted loop to skip the first one.
976 for (size_t i = 1; i < dex_locations_.size(); ++i) {
977 // TODO: Make everything properly std::string.
978 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
979 char_backing_storage_.push_back(base_img + image_name);
980 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
981
982 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
983 char_backing_storage_.push_back(base_oat + oat_name);
984 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
985 }
986 }
987
Andreas Gampe8994a042015-12-30 19:03:17 +0000988 // Modify the input string in the following way:
989 // 0) Assume input is /a/b/c.d
990 // 1) Strip the path -> c.d
991 // 2) Inject prefix p -> pc.d
992 // 3) Inject infix i -> pci.d
993 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800994 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000995 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800996 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000997 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800998 size_t last_dex_slash = in.rfind('/');
999 if (last_dex_slash != std::string::npos) {
1000 in = in.substr(last_dex_slash + 1);
1001 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001002 if (!prefix.empty()) {
1003 in = prefix + in;
1004 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001005 if (!infix.empty()) {
1006 // Inject infix.
1007 size_t last_dot = in.rfind('.');
1008 if (last_dot != std::string::npos) {
1009 in.insert(last_dot, infix);
1010 }
1011 }
1012 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001013 in = in.substr(0, in.length() - strlen(".jar")) +
1014 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001015 }
1016 return in;
1017 }
1018
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001019 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001020 std::ostringstream oss;
1021 for (int i = 0; i < argc; ++i) {
1022 if (i > 0) {
1023 oss << ' ';
1024 }
1025 oss << argv[i];
1026 }
1027 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1028 oss.str(""); // Reset.
1029 oss << kRuntimeISA;
1030 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1031 key_value_store_->Put(
1032 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001033 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001034 key_value_store_->Put(
1035 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001036 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdilce4b0ba2016-01-28 15:05:49 +00001037 key_value_store_->Put(
1038 OatHeader::kExtractOnlyKey,
1039 compiler_options_->IsExtractOnly() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001040 }
1041
1042 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1043 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1044 // returns, arguments have been successfully parsed.
1045 void ParseArgs(int argc, char** argv) {
1046 original_argc = argc;
1047 original_argv = argv;
1048
1049 InitLogging(argv);
1050
1051 // Skip over argv[0].
1052 argv++;
1053 argc--;
1054
1055 if (argc == 0) {
1056 Usage("No arguments specified");
1057 }
1058
1059 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001060 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001061
1062 for (int i = 0; i < argc; i++) {
1063 const StringPiece option(argv[i]);
1064 const bool log_options = false;
1065 if (log_options) {
1066 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1067 }
1068 if (option.starts_with("--dex-file=")) {
1069 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1070 } else if (option.starts_with("--dex-location=")) {
1071 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1072 } else if (option.starts_with("--zip-fd=")) {
1073 ParseZipFd(option);
1074 } else if (option.starts_with("--zip-location=")) {
1075 zip_location_ = option.substr(strlen("--zip-location=")).data();
1076 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001077 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001078 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001079 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001080 } else if (option.starts_with("--oat-fd=")) {
1081 ParseOatFd(option);
1082 } else if (option == "--watch-dog") {
1083 parser_options->watch_dog_enabled = true;
1084 } else if (option == "--no-watch-dog") {
1085 parser_options->watch_dog_enabled = false;
1086 } else if (option.starts_with("-j")) {
1087 ParseJ(option);
1088 } else if (option.starts_with("--oat-location=")) {
1089 oat_location_ = option.substr(strlen("--oat-location=")).data();
1090 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001091 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001092 } else if (option.starts_with("--image-classes=")) {
1093 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1094 } else if (option.starts_with("--image-classes-zip=")) {
1095 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001096 } else if (option.starts_with("--image-format=")) {
1097 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001098 } else if (option.starts_with("--compiled-classes=")) {
1099 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1100 } else if (option.starts_with("--compiled-classes-zip=")) {
1101 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1102 } else if (option.starts_with("--compiled-methods=")) {
1103 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1104 } else if (option.starts_with("--compiled-methods-zip=")) {
1105 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1106 } else if (option.starts_with("--base=")) {
1107 ParseBase(option);
1108 } else if (option.starts_with("--boot-image=")) {
1109 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1110 } else if (option.starts_with("--android-root=")) {
1111 android_root_ = option.substr(strlen("--android-root=")).data();
1112 } else if (option.starts_with("--instruction-set=")) {
1113 ParseInstructionSet(option);
1114 } else if (option.starts_with("--instruction-set-variant=")) {
1115 ParseInstructionSetVariant(option, parser_options.get());
1116 } else if (option.starts_with("--instruction-set-features=")) {
1117 ParseInstructionSetFeatures(option, parser_options.get());
1118 } else if (option.starts_with("--compiler-backend=")) {
1119 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001120 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001121 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001122 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001123 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001124 } else if (option == "--host") {
1125 is_host_ = true;
1126 } else if (option == "--runtime-arg") {
1127 if (++i >= argc) {
1128 Usage("Missing required argument for --runtime-arg");
1129 }
1130 if (log_options) {
1131 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1132 }
1133 runtime_args_.push_back(argv[i]);
1134 } else if (option == "--dump-timing") {
1135 dump_timing_ = true;
1136 } else if (option == "--dump-passes") {
1137 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001138 } else if (option == "--dump-stats") {
1139 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001140 } else if (option.starts_with("--swap-file=")) {
1141 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1142 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001143 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1144 } else if (option.starts_with("--app-image-file=")) {
1145 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1146 } else if (option.starts_with("--app-image-fd=")) {
1147 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001148 } else if (option.starts_with("--verbose-methods=")) {
1149 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1150 // conditional on having verbost methods.
1151 gLogVerbosity.compiler = false;
1152 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001153 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001154 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001155 } else if (option.starts_with("--no-inline-from=")) {
1156 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001157 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001158 if (!SupportsDeterministicCompilation()) {
1159 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001160 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001161 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001162 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001163 Usage("Unknown argument %s", option.data());
1164 }
1165 }
1166
Jeff Hao436183f2016-01-12 16:36:50 -08001167 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168
1169 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001170 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001171 }
1172
Jeff Haodcdc85b2015-12-04 14:06:18 -08001173 // Check whether the oat output files are writable, and open them for later. Also open a swap
1174 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001175 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001176 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1177 PruneNonExistentDexFiles();
1178
Jeff Hao436183f2016-01-12 16:36:50 -08001179 // Expand oat and image filenames for multi image.
1180 if (IsBootImage() && multi_image_) {
1181 ExpandOatAndImageFilenames();
1182 }
1183
Jeff Haodcdc85b2015-12-04 14:06:18 -08001184 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001185 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001186 for (const char* oat_filename : oat_filenames_) {
1187 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1188 if (oat_file.get() == nullptr) {
1189 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1190 return false;
1191 }
1192 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1193 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1194 oat_file->Erase();
1195 return false;
1196 }
1197 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001198 }
1199 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001200 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1201 oat_file->DisableAutoClose();
1202 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001203 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1204 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001205 if (oat_file.get() == nullptr) {
1206 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1207 return false;
1208 }
1209 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1210 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1211 oat_file->Erase();
1212 return false;
1213 }
1214 oat_filenames_.push_back(oat_location_.c_str());
1215 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001216 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001217
1218 // Swap file handling.
1219 //
1220 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1221 // that we can use for swap.
1222 //
1223 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1224 // will immediately unlink to satisfy the swap fd assumption.
1225 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1226 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1227 if (swap_file.get() == nullptr) {
1228 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1229 return false;
1230 }
1231 swap_fd_ = swap_file->Fd();
1232 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1233 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1234 // released immediately.
1235 unlink(swap_file_name_.c_str());
1236 }
Jeff Hao436183f2016-01-12 16:36:50 -08001237
1238 // If we use a swap file, ensure we are above the threshold to make it necessary.
1239 if (swap_fd_ != -1) {
1240 if (!UseSwap(IsBootImage(), dex_files_)) {
1241 close(swap_fd_);
1242 swap_fd_ = -1;
1243 VLOG(compiler) << "Decided to run without swap.";
1244 } else {
1245 LOG(INFO) << "Large app, accepted running with swap.";
1246 }
1247 }
1248 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1249
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 return true;
1251 }
1252
Jeff Haodcdc85b2015-12-04 14:06:18 -08001253 void EraseOatFiles() {
1254 for (size_t i = 0; i < oat_files_.size(); ++i) {
1255 DCHECK(oat_files_[i].get() != nullptr);
1256 oat_files_[i]->Erase();
1257 oat_files_[i].reset();
1258 }
Andreas Gampea650e702014-12-03 14:28:02 -08001259 }
1260
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001261 void Shutdown() {
1262 ScopedObjectAccess soa(Thread::Current());
1263 for (jobject dex_cache : dex_caches_) {
1264 soa.Env()->DeleteLocalRef(dex_cache);
1265 }
1266 dex_caches_.clear();
1267 }
1268
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001269 void LoadClassProfileDescriptors() {
1270 if (profile_compilation_info_ != nullptr && app_image_) {
1271 Runtime* runtime = Runtime::Current();
1272 CHECK(runtime != nullptr);
1273 std::set<DexCacheResolvedClasses> resolved_classes(
1274 profile_compilation_info_->GetResolvedClasses());
1275 image_classes_.reset(new std::unordered_set<std::string>(
1276 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes)));
1277 VLOG(compiler) << "Loaded " << image_classes_->size()
1278 << " image class descriptors from profile";
1279 if (VLOG_IS_ON(compiler)) {
1280 for (const std::string& s : *image_classes_) {
1281 LOG(INFO) << "Image class " << s;
1282 }
1283 }
1284 }
1285 }
1286
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001287 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1288 // boot class path.
1289 bool Setup() {
1290 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001291 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001292
1293 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1294 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001295 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001296
Vladimir Marko307dac92015-10-20 11:20:09 +01001297 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001298 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001299 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001300 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001301 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001302 CompilerCallbacks::CallbackMode::kCompileBootImage :
1303 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001304
Vladimir Marko49b0f452015-12-10 13:49:19 +00001305 RuntimeArgumentMap runtime_options;
1306 if (!PrepareRuntimeOptions(&runtime_options)) {
1307 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001308 }
1309
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001310 CreateOatWriters();
1311 if (!AddDexFileSources()) {
1312 return false;
1313 }
1314
1315 if (IsBootImage() && image_filenames_.size() > 1) {
1316 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1317 // We need this for the multi-image case.
1318 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1319 }
1320
1321 if (!IsBootImage()) {
1322 // When compiling an app, create the runtime early to retrieve
1323 // the image location key needed for the oat header.
1324 if (!CreateRuntime(std::move(runtime_options))) {
1325 return false;
1326 }
1327
David Brazdilce4b0ba2016-01-28 15:05:49 +00001328 if (compiler_options_->IsExtractOnly()) {
1329 // ExtractOnly oat files only contain non-quickened DEX code and are
1330 // therefore independent of the image file.
1331 image_file_location_oat_checksum_ = 0u;
1332 image_file_location_oat_data_begin_ = 0u;
1333 image_patch_delta_ = 0;
1334 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001335 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1336 std::vector<gc::space::ImageSpace*> image_spaces =
1337 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1338 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1339 image_file_location_oat_data_begin_ =
1340 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1341 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1342 // Store the boot image filename(s).
1343 std::vector<std::string> image_filenames;
1344 for (const gc::space::ImageSpace* image_space : image_spaces) {
1345 image_filenames.push_back(image_space->GetImageFilename());
1346 }
1347 std::string image_file_location = Join(image_filenames, ':');
1348 if (!image_file_location.empty()) {
1349 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1350 }
1351 }
1352
1353 // Open dex files for class path.
1354 const std::vector<std::string> class_path_locations =
1355 GetClassPathLocations(runtime_->GetClassPathString());
1356 OpenClassPathFiles(class_path_locations, &class_path_files_);
1357
1358 // Store the classpath we have right now.
1359 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1360 key_value_store_->Put(OatHeader::kClassPathKey,
1361 OatFile::EncodeDexFileDependencies(class_path_files));
1362 }
1363
1364 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001365 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001366 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1367 rodata_.reserve(oat_writers_.size());
1368 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1369 rodata_.push_back(elf_writers_[i]->StartRoData());
1370 // Unzip or copy dex files straight to the oat file.
1371 std::unique_ptr<MemMap> opened_dex_files_map;
1372 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1373 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1374 oat_files_[i].get(),
1375 instruction_set_,
1376 instruction_set_features_.get(),
1377 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001378 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001379 &opened_dex_files_map,
1380 &opened_dex_files)) {
1381 return false;
1382 }
1383 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1384 if (opened_dex_files_map != nullptr) {
1385 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1386 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001387 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001388 opened_dex_files_.push_back(std::move(dex_file));
1389 }
1390 } else {
1391 DCHECK(opened_dex_files.empty());
1392 }
1393 }
1394 }
1395
1396 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1397 if (IsBootImage()) {
1398 // For boot image, pass opened dex files to the Runtime::Create().
1399 // Note: Runtime acquires ownership of these dex files.
1400 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001401 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001402 return false;
1403 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001404 }
1405
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 // If we're doing the image, override the compiler filter to force full compilation. Must be
1407 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1408 // compilation of class initializers.
1409 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001410 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001411 WellKnownClasses::Init(self->GetJniEnv());
1412
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001413 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001414 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001415 constexpr bool kSaveDexInput = false;
1416 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001417 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001418 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001419
1420 // Handle and ClassLoader creation needs to come after Runtime::Create.
1421 ScopedObjectAccess soa(self);
1422
1423 // Classpath: first the class-path given.
1424 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1425
1426 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1427 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1428
1429 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001430 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001431
1432 // Ensure opened dex files are writable for dex-to-dex transformations.
1433 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1434 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1435 PLOG(ERROR) << "Failed to make .dex files writeable.";
1436 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001437 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001438 }
1439
1440 // Ensure that the dex caches stay live since we don't want class unloading
1441 // to occur during compilation.
1442 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001443 ScopedObjectAccess soa(self);
1444 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001445 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001446 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001447
1448 /*
1449 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1450 * Don't bother to check if we're doing the image.
1451 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001452 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001453 compiler_options_->IsCompilationEnabled() &&
1454 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001455 size_t num_methods = 0;
1456 for (size_t i = 0; i != dex_files_.size(); ++i) {
1457 const DexFile* dex_file = dex_files_[i];
1458 CHECK(dex_file != nullptr);
1459 num_methods += dex_file->NumMethodIds();
1460 }
1461 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1462 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1463 VLOG(compiler) << "Below method threshold, compiling anyways";
1464 }
1465 }
1466
1467 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001468 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001469
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001470 // If we need to keep the oat file open for the image writer.
1471 bool ShouldKeepOatFileOpen() const {
1472 return IsImage() && oat_fd_ != kInvalidFd;
1473 }
1474
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001475 // Create and invoke the compiler driver. This will compile all the dex files.
1476 void Compile() {
1477 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1478 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001479
Vladimir Marko47496c22016-01-27 16:15:08 +00001480 // Find the dex files we should not inline from.
1481
1482 std::vector<std::string> no_inline_filters;
1483 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001484
1485 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001486 const std::string core_oj = "core-oj";
1487 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1488 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001489 }
1490
Vladimir Marko47496c22016-01-27 16:15:08 +00001491 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001492 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1493 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1494 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1495 &class_linker->GetBootClassPath(),
1496 &class_path_files,
1497 &dex_files_
1498 };
1499 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001500 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001501 for (const std::string& filter : no_inline_filters) {
1502 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1503 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1504 // base location passes the StartsWith() test, so do all extra locations.
1505 std::string dex_location = dex_file->GetLocation();
1506 if (filter.find('/') == std::string::npos) {
1507 // The filter does not contain the path. Remove the path from dex_location as well.
1508 size_t last_slash = dex_file->GetLocation().rfind('/');
1509 if (last_slash != std::string::npos) {
1510 dex_location = dex_location.substr(last_slash + 1);
1511 }
1512 }
1513
1514 if (StartsWith(dex_location, filter.c_str())) {
1515 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1516 no_inline_from_dex_files_.push_back(dex_file);
1517 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001518 }
1519 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001520 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001521 }
1522 if (!no_inline_from_dex_files_.empty()) {
1523 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001524 }
1525 }
1526
Vladimir Marko307dac92015-10-20 11:20:09 +01001527 driver_.reset(new CompilerDriver(compiler_options_.get(),
1528 verification_results_.get(),
1529 &method_inliner_map_,
1530 compiler_kind_,
1531 instruction_set_,
1532 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001533 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001534 image_classes_.release(),
1535 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001536 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001537 thread_count_,
1538 dump_stats_,
1539 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001540 compiler_phases_timings_.get(),
1541 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001542 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001543 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001544 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001545 }
1546
Jeff Hao436183f2016-01-12 16:36:50 -08001547 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001548 // ensure the references between the two are correct.
1549 //
1550 // Currently we have a memory layout that looks something like this:
1551 //
1552 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001553 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001554 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001555 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556 // +--------------+
1557 // | alloc spaces |
1558 // +--------------+
1559 //
Jeff Hao436183f2016-01-12 16:36:50 -08001560 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001561 //
Jeff Hao436183f2016-01-12 16:36:50 -08001562 // 1. The images are expected to be loaded at an absolute address and
1563 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564 //
Jeff Hao436183f2016-01-12 16:36:50 -08001565 // 2. There are absolute pointers from Methods in the images to their
1566 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001567 //
Jeff Hao436183f2016-01-12 16:36:50 -08001568 // 3. There are absolute pointers from the code in the oat files to Methods
1569 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001570 //
Jeff Hao436183f2016-01-12 16:36:50 -08001571 // 4. There are absolute pointers from code in the oat files to other code
1572 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001573 //
1574 // To get this all correct, we go through several steps.
1575 //
Jeff Hao436183f2016-01-12 16:36:50 -08001576 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001577 // the oat data size and code size. During this stage, we also set
1578 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001579 //
Jeff Hao436183f2016-01-12 16:36:50 -08001580 // 2. We prepare offsets for the objects in the images and calculate
1581 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001582 //
Jeff Hao436183f2016-01-12 16:36:50 -08001583 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001584 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001585 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001586 // can prepare the ELF headers and we then know the ELF memory segment
1587 // layout and we can now resolve all references. The compiler provides
1588 // LinkerPatch information in each CompiledMethod and we resolve these,
1589 // using the layout information and image object locations provided by
1590 // image writer, as we're writing the method code.
1591 //
Jeff Hao436183f2016-01-12 16:36:50 -08001592 // 4. We create the image files. They need to know where the oat files
1593 // will be loaded after itself. Originally oat files were simply
1594 // memory mapped so we could predict where their contents were based
1595 // on the file size. Now that they are ELF files, we need to inspect
1596 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001597 // where the oat header is located within.
1598 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001599 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001600 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001601 // load the .so at the desired location at runtime by offsetting the
1602 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001603 // TODO: Do this in step 3. We already know the layout there.
1604 //
1605 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1606 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001607
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001608 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1609 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001610 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1611 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001612 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001613 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1614
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001615 // Sync the data to the file, in case we did dex2dex transformations.
1616 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1617 if (!map->Sync()) {
1618 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1619 return false;
1620 }
1621 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001622
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001623 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001624 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001625 gc::Heap* const heap = Runtime::Current()->GetHeap();
1626 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001627 image_base_ = std::max(image_base_, RoundUp(
1628 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1629 kPageSize));
1630 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001631 // The non moving space is right after the oat file. Put the preferred app image location
1632 // right after the non moving space so that we ideally get a continuous immune region for
1633 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001634 // Use the default non moving space capacity since dex2oat does not have a separate non-
1635 // moving space. This means the runtime's non moving space space size will be as large
1636 // as the growth limit for dex2oat, but smaller in the zygote.
1637 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001638 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001639 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1640 }
1641
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001642 image_writer_.reset(new ImageWriter(*driver_,
1643 image_base_,
1644 compiler_options_->GetCompilePic(),
1645 IsAppImage(),
1646 image_storage_mode_,
1647 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001648 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001650 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001651 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1652 if (!image_writer_->PrepareImageAddressSpace()) {
1653 LOG(ERROR) << "Failed to prepare image address space.";
1654 return false;
1655 }
1656 }
1657
Vladimir Marko944da602016-02-19 12:27:55 +00001658 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001659 {
1660 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001661 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001662 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1663 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1664
1665 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1666 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1667
1668 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1669 size_t text_size = oat_writer->GetSize() - rodata_size;
1670 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1671
1672 if (IsImage()) {
1673 // Update oat layout.
1674 DCHECK(image_writer_ != nullptr);
1675 DCHECK_LT(i, oat_filenames_.size());
1676 image_writer_->UpdateOatFileLayout(i,
1677 elf_writer->GetLoadedSize(),
1678 oat_writer->GetOatDataOffset(),
1679 oat_writer->GetSize());
1680 }
1681 }
1682
1683 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001684 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1686 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001687
David Srbecky0c4572e2016-01-22 19:19:25 +00001688 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001689 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1690 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001691
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692 OutputStream*& rodata = rodata_[i];
1693 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001694 if (!oat_writer->WriteRodata(rodata)) {
1695 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1696 return false;
1697 }
1698 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001699 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001700
Jeff Haodcdc85b2015-12-04 14:06:18 -08001701 OutputStream* text = elf_writer->StartText();
1702 if (!oat_writer->WriteCode(text)) {
1703 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1704 return false;
1705 }
1706 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001707
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001708 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1709 image_file_location_oat_checksum_,
1710 image_file_location_oat_data_begin_,
1711 image_patch_delta_)) {
1712 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1713 return false;
1714 }
1715
Vladimir Marko944da602016-02-19 12:27:55 +00001716 if (IsImage()) {
1717 // Update oat header information.
1718 DCHECK(image_writer_ != nullptr);
1719 DCHECK_LT(i, oat_filenames_.size());
1720 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1721 }
1722
Jeff Haodcdc85b2015-12-04 14:06:18 -08001723 elf_writer->WriteDynamicSection();
1724 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1725 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001726
Jeff Haodcdc85b2015-12-04 14:06:18 -08001727 if (!elf_writer->End()) {
1728 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1729 return false;
1730 }
1731
1732 // Flush the oat file.
1733 if (oat_files_[i] != nullptr) {
1734 if (oat_files_[i]->Flush() != 0) {
1735 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001736 return false;
1737 }
1738 }
1739
Jeff Haodcdc85b2015-12-04 14:06:18 -08001740 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001741
1742 oat_writer.reset();
1743 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001744 }
1745 }
1746
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001747 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001748 }
1749
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001750 // If we are compiling an image, invoke the image creation routine. Else just skip.
1751 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001752 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001753 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1754 if (!CreateImageFile()) {
1755 return false;
1756 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001757 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001758 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001759 return true;
1760 }
1761
Jeff Haodcdc85b2015-12-04 14:06:18 -08001762 // Create a copy from stripped to unstripped.
1763 bool CopyStrippedToUnstripped() {
1764 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1765 // If we don't want to strip in place, copy from stripped location to unstripped location.
1766 // We need to strip after image creation because FixupElf needs to use .strtab.
1767 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1768 // If the oat file is still open, flush it.
1769 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1770 if (!FlushCloseOatFile(i)) {
1771 return false;
1772 }
1773 }
1774
1775 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1776 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1777 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1778 size_t buffer_size = 8192;
1779 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1780 while (true) {
1781 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1782 if (bytes_read <= 0) {
1783 break;
1784 }
1785 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1786 CHECK(write_ok);
1787 }
1788 if (out->FlushCloseOrErase() != 0) {
1789 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1790 return false;
1791 }
1792 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1793 }
1794 }
1795 return true;
1796 }
1797
1798 bool FlushOatFiles() {
1799 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1800 for (size_t i = 0; i < oat_files_.size(); ++i) {
1801 if (oat_files_[i].get() != nullptr) {
1802 if (oat_files_[i]->Flush() != 0) {
1803 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1804 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001805 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001806 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001807 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001808 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001809 return true;
1810 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001811
Jeff Haodcdc85b2015-12-04 14:06:18 -08001812 bool FlushCloseOatFile(size_t i) {
1813 if (oat_files_[i].get() != nullptr) {
1814 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001815 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001816 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001817 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001818 }
1819 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001820 return true;
1821 }
1822
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 bool FlushCloseOatFiles() {
1824 bool result = true;
1825 for (size_t i = 0; i < oat_files_.size(); ++i) {
1826 result &= FlushCloseOatFile(i);
1827 }
1828 return result;
1829 }
1830
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001831 void DumpTiming() {
1832 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1833 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1834 }
1835 if (dump_passes_) {
1836 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1837 }
1838 }
1839
1840 CompilerOptions* GetCompilerOptions() const {
1841 return compiler_options_.get();
1842 }
1843
Andreas Gampe10e477d2014-11-19 12:57:42 -08001844 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001845 return IsAppImage() || IsBootImage();
1846 }
1847
1848 bool IsAppImage() const {
1849 return app_image_;
1850 }
1851
1852 bool IsBootImage() const {
1853 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001854 }
1855
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001856 bool IsHost() const {
1857 return is_host_;
1858 }
1859
Calin Juravle998c2162015-12-21 15:39:33 +02001860 bool UseProfileGuidedCompilation() const {
Calin Juravle2e2db782016-02-23 12:00:03 +00001861 return !profile_file_.empty() || (profile_file_fd_ != kInvalidFd);
Calin Juravle998c2162015-12-21 15:39:33 +02001862 }
1863
Calin Juravle2e2db782016-02-23 12:00:03 +00001864 bool LoadProfile() {
Calin Juravle998c2162015-12-21 15:39:33 +02001865 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001866
1867 profile_compilation_info_.reset(new ProfileCompilationInfo());
1868 ScopedFlock flock;
1869 bool success = false;
1870 std::string error;
1871 if (profile_file_fd_ != -1) {
1872 // The file doesn't need to be flushed so don't check the usage.
1873 // Pass a bogus path so that we can easily attribute any reported error.
1874 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1875 if (flock.Init(&file, &error)) {
1876 success = profile_compilation_info_->Load(profile_file_fd_);
1877 }
Calin Juravle877fd962016-01-05 14:29:29 +00001878 } else {
Calin Juravle2e2db782016-02-23 12:00:03 +00001879 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1880 success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1881 }
1882 }
1883 if (!error.empty()) {
1884 LOG(WARNING) << "Cannot lock profiles: " << error;
Calin Juravle998c2162015-12-21 15:39:33 +02001885 }
Calin Juravle877fd962016-01-05 14:29:29 +00001886
Calin Juravle2e2db782016-02-23 12:00:03 +00001887 if (!success) {
1888 profile_compilation_info_.reset(nullptr);
1889 }
Calin Juravle877fd962016-01-05 14:29:29 +00001890
Calin Juravle2e2db782016-02-23 12:00:03 +00001891 return success;
Calin Juravle998c2162015-12-21 15:39:33 +02001892 }
1893
1894 bool ShouldCompileBasedOnProfiles() const {
1895 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001896 // If we are given a profile, compile only if we have some data in it.
1897 return (profile_compilation_info_ != nullptr) &&
1898 (profile_compilation_info_->GetNumberOfMethods() != 0);
Calin Juravle998c2162015-12-21 15:39:33 +02001899 }
1900
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001901 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001902 template <typename T>
1903 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1904 std::vector<T*> result;
1905 result.reserve(src.size());
1906 for (const std::unique_ptr<T>& t : src) {
1907 result.push_back(t.get());
1908 }
1909 return result;
1910 }
1911
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001912 std::string GetMultiImageBootClassPath() {
1913 DCHECK(IsBootImage());
1914 DCHECK_GT(oat_filenames_.size(), 1u);
1915 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1916 // too, but need to strip all path components (they will be re-established when loading).
1917 std::ostringstream bootcp_oss;
1918 bool first_bootcp = true;
1919 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1920 if (!first_bootcp) {
1921 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001922 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001923
1924 std::string dex_loc = dex_locations_[i];
1925 std::string image_filename = image_filenames_[i];
1926
1927 // Use the dex_loc path, but the image_filename name (without path elements).
1928 size_t dex_last_slash = dex_loc.rfind('/');
1929
1930 // npos is max(size_t). That makes this a bit ugly.
1931 size_t image_last_slash = image_filename.rfind('/');
1932 size_t image_last_at = image_filename.rfind('@');
1933 size_t image_last_sep = (image_last_slash == std::string::npos)
1934 ? image_last_at
1935 : (image_last_at == std::string::npos)
1936 ? std::string::npos
1937 : std::max(image_last_slash, image_last_at);
1938 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1939
1940 if (dex_last_slash == std::string::npos) {
1941 dex_loc = image_filename.substr(image_last_sep + 1);
1942 } else {
1943 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1944 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001945 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001946
1947 // Image filenames already end with .art, no need to replace.
1948
1949 bootcp_oss << dex_loc;
1950 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001951 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001952 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001953 }
1954
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001955 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1956 // This function is used only for apps and for an app we have exactly one oat file.
1957 DCHECK(!IsBootImage());
1958 DCHECK_EQ(oat_writers_.size(), 1u);
1959 std::vector<std::string> dex_files_canonical_locations;
1960 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1961 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001962 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001963
Vladimir Marko919f5532016-01-20 19:13:01 +00001964 std::vector<std::string> parsed;
1965 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001966 auto kept_it = std::remove_if(parsed.begin(),
1967 parsed.end(),
1968 [dex_files_canonical_locations](const std::string& location) {
1969 return ContainsElement(dex_files_canonical_locations,
1970 DexFile::GetDexCanonicalLocation(location.c_str()));
1971 });
1972 parsed.erase(kept_it, parsed.end());
1973 return parsed;
1974 }
1975
1976 // Opens requested class path files and appends them to opened_dex_files.
1977 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1978 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1979 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1980 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001981 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001982 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1983 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001984 }
1985 }
1986 }
1987
Vladimir Marko49b0f452015-12-10 13:49:19 +00001988 bool PrepareImageClasses() {
1989 // If --image-classes was specified, calculate the full list of classes to include in the image.
1990 if (image_classes_filename_ != nullptr) {
1991 image_classes_ =
1992 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1993 if (image_classes_ == nullptr) {
1994 return false;
1995 }
1996 } else if (IsBootImage()) {
1997 image_classes_.reset(new std::unordered_set<std::string>);
1998 }
1999 return true;
2000 }
2001
2002 bool PrepareCompiledClasses() {
2003 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2004 // image.
2005 if (compiled_classes_filename_ != nullptr) {
2006 compiled_classes_ =
2007 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2008 if (compiled_classes_ == nullptr) {
2009 return false;
2010 }
2011 } else {
2012 compiled_classes_.reset(nullptr); // By default compile everything.
2013 }
2014 return true;
2015 }
2016
2017 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2018 const char* classes_filename,
2019 const char* tag) {
2020 std::unique_ptr<std::unordered_set<std::string>> classes;
2021 std::string error_msg;
2022 if (zip_filename != nullptr) {
2023 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2024 } else {
2025 classes.reset(ReadImageClassesFromFile(classes_filename));
2026 }
2027 if (classes == nullptr) {
2028 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2029 << classes_filename << "': " << error_msg;
2030 }
2031 return classes;
2032 }
2033
2034 bool PrepareCompiledMethods() {
2035 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2036 if (compiled_methods_filename_ != nullptr) {
2037 std::string error_msg;
2038 if (compiled_methods_zip_filename_ != nullptr) {
2039 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2040 compiled_methods_filename_,
2041 nullptr, // No post-processing.
2042 &error_msg));
2043 } else {
2044 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2045 nullptr)); // No post-processing.
2046 }
2047 if (compiled_methods_.get() == nullptr) {
2048 LOG(ERROR) << "Failed to create list of compiled methods from '"
2049 << compiled_methods_filename_ << "': " << error_msg;
2050 return false;
2051 }
2052 } else {
2053 compiled_methods_.reset(nullptr); // By default compile everything.
2054 }
2055 return true;
2056 }
2057
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002058 void PruneNonExistentDexFiles() {
2059 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2060 size_t kept = 0u;
2061 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2062 if (!OS::FileExists(dex_filenames_[i])) {
2063 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2064 } else {
2065 dex_filenames_[kept] = dex_filenames_[i];
2066 dex_locations_[kept] = dex_locations_[i];
2067 ++kept;
2068 }
2069 }
2070 dex_filenames_.resize(kept);
2071 dex_locations_.resize(kept);
2072 }
2073
2074 bool AddDexFileSources() {
2075 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2076 if (zip_fd_ != -1) {
2077 DCHECK_EQ(oat_writers_.size(), 1u);
2078 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2079 return false;
2080 }
2081 } else if (oat_writers_.size() > 1u) {
2082 // Multi-image.
2083 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2084 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2085 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2086 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2087 return false;
2088 }
2089 }
2090 } else {
2091 DCHECK_EQ(oat_writers_.size(), 1u);
2092 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2093 DCHECK_NE(dex_filenames_.size(), 0u);
2094 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2095 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2096 return false;
2097 }
2098 }
2099 }
2100 return true;
2101 }
2102
2103 void CreateOatWriters() {
2104 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2105 elf_writers_.reserve(oat_files_.size());
2106 oat_writers_.reserve(oat_files_.size());
2107 for (const std::unique_ptr<File>& oat_file : oat_files_) {
David Srbecky5d811202016-03-08 13:21:22 +00002108 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2109 instruction_set_features_.get(),
2110 compiler_options_.get(),
2111 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002112 elf_writers_.back()->Start();
2113 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2114 }
2115 }
2116
Vladimir Marko49b0f452015-12-10 13:49:19 +00002117 void SaveDexInput() {
2118 for (size_t i = 0; i < dex_files_.size(); ++i) {
2119 const DexFile* dex_file = dex_files_[i];
2120 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2121 getpid(), i));
2122 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2123 if (tmp_file.get() == nullptr) {
2124 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2125 << ". Try: adb shell chmod 777 /data/local/tmp";
2126 continue;
2127 }
2128 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2129 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2130 UNUSED(tmp_file->Flush());
2131 UNUSED(tmp_file->Close());
2132 LOG(INFO) << "Wrote input to " << tmp_file_name;
2133 }
2134 }
2135
2136 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2137 RuntimeOptions raw_options;
2138 if (boot_image_filename_.empty()) {
2139 std::string boot_class_path = "-Xbootclasspath:";
2140 boot_class_path += Join(dex_filenames_, ':');
2141 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2142 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2143 boot_class_path_locations += Join(dex_locations_, ':');
2144 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2145 } else {
2146 std::string boot_image_option = "-Ximage:";
2147 boot_image_option += boot_image_filename_;
2148 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2149 }
2150 for (size_t i = 0; i < runtime_args_.size(); i++) {
2151 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2152 }
2153
2154 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2155 raw_options.push_back(
2156 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2157
2158 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2159 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2160 // have been stripped in preopting, anyways).
2161 if (!IsBootImage()) {
2162 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2163 }
2164 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2165 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2166 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002167 // Disable Hspace compaction to save heap size virtual space.
2168 // Only need disable Hspace for OOM becasue background collector is equal to
2169 // foreground collector by default for dex2oat.
2170 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002171
Andreas Gampeace0dc12016-01-20 13:33:13 -08002172 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2173 // force the free-list implementation for large objects.
2174 if (compiler_options_->IsForceDeterminism()) {
2175 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2176 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2177
2178 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2179 // compaction (done above) and ensure that neither foreground nor background collectors
2180 // are concurrent.
2181 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2182
2183 // To make identity hashcode deterministic, set a known seed.
2184 mirror::Object::SetHashCodeSeed(987654321U);
2185 }
2186
Vladimir Marko49b0f452015-12-10 13:49:19 +00002187 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2188 LOG(ERROR) << "Failed to parse runtime options";
2189 return false;
2190 }
2191 return true;
2192 }
2193
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002194 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002195 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2196 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002197 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002198 LOG(ERROR) << "Failed to create runtime";
2199 return false;
2200 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002201 runtime_.reset(Runtime::Current());
2202 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002203 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2204 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002205 if (!runtime_->HasCalleeSaveMethod(type)) {
2206 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002207 }
2208 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002209 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002210
2211 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2212 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002213 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002214
Vladimir Marko307dac92015-10-20 11:20:09 +01002215 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002216
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002217 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2218 // Runtime::Start, give it away now so that we don't starve GC.
2219 Thread* self = Thread::Current();
2220 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002221
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002222 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002223 }
2224
Jeff Haodcdc85b2015-12-04 14:06:18 -08002225 // 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 -08002226 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002227 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002228 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002229 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002230 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002231 image_filenames_.push_back(app_image_file_name_.c_str());
2232 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002233 if (!image_writer_->Write(app_image_fd_,
2234 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002235 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002236 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002237 return false;
2238 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002239
Jeff Haodcdc85b2015-12-04 14:06:18 -08002240 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002241 dchecked_vector<uintptr_t> oat_data_begins;
2242 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2243 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002244 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002245 // Destroy ImageWriter before doing FixupElf.
2246 image_writer_.reset();
2247
Vladimir Marko944da602016-02-19 12:27:55 +00002248 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2249 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002250 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2251 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2252 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2253 if (oat_file.get() == nullptr) {
2254 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2255 return false;
2256 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002257
Vladimir Marko944da602016-02-19 12:27:55 +00002258 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002259 oat_file->Erase();
2260 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2261 return false;
2262 }
2263
2264 if (oat_file->FlushCloseOrErase()) {
2265 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2266 return false;
2267 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002268 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002269 }
2270
2271 return true;
2272 }
2273
2274 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002275 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2276 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002277 std::function<std::string(const char*)> process = DotToDescriptor;
2278 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002279 }
2280
2281 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002282 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002283 const char* zip_filename,
2284 const char* image_classes_filename,
2285 std::string* error_msg) {
2286 std::function<std::string(const char*)> process = DotToDescriptor;
2287 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2288 }
2289
2290 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2291 // the given function.
2292 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2293 const char* input_filename, std::function<std::string(const char*)>* process) {
2294 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2295 if (input_file.get() == nullptr) {
2296 LOG(ERROR) << "Failed to open input file " << input_filename;
2297 return nullptr;
2298 }
2299 std::unique_ptr<std::unordered_set<std::string>> result(
2300 ReadCommentedInputStream(*input_file, process));
2301 input_file->close();
2302 return result.release();
2303 }
2304
2305 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2306 // Post-process each line with the given function.
2307 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002308 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002309 const char* input_filename,
2310 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002311 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002312 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2313 if (zip_archive.get() == nullptr) {
2314 return nullptr;
2315 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002316 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002317 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002318 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002319 zip_filename, error_msg->c_str());
2320 return nullptr;
2321 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002322 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2323 input_filename,
2324 error_msg));
2325 if (input_file.get() == nullptr) {
2326 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002327 zip_filename, error_msg->c_str());
2328 return nullptr;
2329 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002330 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2331 input_file->Size());
2332 std::istringstream input_stream(input_string);
2333 return ReadCommentedInputStream(input_stream, process);
2334 }
2335
2336 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2337 // with the given function.
2338 static std::unordered_set<std::string>* ReadCommentedInputStream(
2339 std::istream& in_stream,
2340 std::function<std::string(const char*)>* process) {
2341 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2342 new std::unordered_set<std::string>);
2343 while (in_stream.good()) {
2344 std::string dot;
2345 std::getline(in_stream, dot);
2346 if (StartsWith(dot, "#") || dot.empty()) {
2347 continue;
2348 }
2349 if (process != nullptr) {
2350 std::string descriptor((*process)(dot.c_str()));
2351 image_classes->insert(descriptor);
2352 } else {
2353 image_classes->insert(dot);
2354 }
2355 }
2356 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002357 }
2358
Mathieu Chartier49285c52014-12-02 15:43:48 -08002359 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002360 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2361 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002362 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002363 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002364 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002365 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002366 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2367 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002368 }
2369
Jeff Haodcdc85b2015-12-04 14:06:18 -08002370 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2371 std::string res(image_filename);
2372 size_t last_slash = res.rfind('/');
2373 if (last_slash == std::string::npos || last_slash == 0) {
2374 return res;
2375 }
2376 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2377 if (penultimate_slash == std::string::npos) {
2378 return res;
2379 }
2380 // Check that the string in-between is the expected one.
2381 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2382 GetInstructionSetString(isa)) {
2383 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2384 return res;
2385 }
2386 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2387 }
2388
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002389 std::unique_ptr<CompilerOptions> compiler_options_;
2390 Compiler::Kind compiler_kind_;
2391
2392 InstructionSet instruction_set_;
2393 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2394
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002395 uint32_t image_file_location_oat_checksum_;
2396 uintptr_t image_file_location_oat_data_begin_;
2397 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002398 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2399
Vladimir Marko307dac92015-10-20 11:20:09 +01002400 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002401
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002402 DexFileToMethodInlinerMap method_inliner_map_;
2403 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2404
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002405 std::unique_ptr<Runtime> runtime_;
2406
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002407 // Ownership for the class path files.
2408 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2409
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002410 size_t thread_count_;
2411 uint64_t start_ns_;
2412 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002413 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002414 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002415 std::vector<const char*> oat_filenames_;
2416 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002417 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002418 std::vector<const char*> dex_filenames_;
2419 std::vector<const char*> dex_locations_;
2420 int zip_fd_;
2421 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002422 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002423 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002424 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002425 uintptr_t image_base_;
2426 const char* image_classes_zip_filename_;
2427 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002428 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002429 const char* compiled_classes_zip_filename_;
2430 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002431 const char* compiled_methods_zip_filename_;
2432 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002433 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2434 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002435 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002436 bool app_image_;
2437 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002438 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002439 bool is_host_;
2440 std::string android_root_;
2441 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002442 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002443 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002444 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002445
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002446 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2447 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2448 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002449 std::unique_ptr<ImageWriter> image_writer_;
2450 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002451
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002452 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2453 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2454
Vladimir Marko47496c22016-01-27 16:15:08 +00002455 std::vector<const DexFile*> no_inline_from_dex_files_;
2456
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002457 std::vector<std::string> verbose_methods_;
2458 bool dump_stats_;
2459 bool dump_passes_;
2460 bool dump_timing_;
2461 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002462 std::string swap_file_name_;
2463 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002464 std::string app_image_file_name_;
2465 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002466 std::string profile_file_;
2467 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002468 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002469 TimingLogger* timings_;
2470 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002471 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002472 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002473
2474 // Backing storage.
2475 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002476
Andreas Gampeace0dc12016-01-20 13:33:13 -08002477 // See CompilerOptions.force_determinism_.
2478 bool force_determinism_;
2479
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002480 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2481};
2482
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002483static void b13564922() {
2484#if defined(__linux__) && defined(__arm__)
2485 int major, minor;
2486 struct utsname uts;
2487 if (uname(&uts) != -1 &&
2488 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2489 ((major < 3) || ((major == 3) && (minor < 4)))) {
2490 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2491 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2492 int old_personality = personality(0xffffffff);
2493 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2494 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2495 if (new_personality == -1) {
2496 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2497 }
2498 }
2499 }
2500#endif
2501}
2502
Andreas Gampe10e477d2014-11-19 12:57:42 -08002503static int CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002504 dex2oat.LoadClassProfileDescriptors();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002505 dex2oat.Compile();
2506
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002507 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002508 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002509 return EXIT_FAILURE;
2510 }
2511
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002512 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2513 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2514 // image writer will require this fd to generate the image.
2515 if (dex2oat.ShouldKeepOatFileOpen()) {
2516 if (!dex2oat.FlushOatFiles()) {
2517 return EXIT_FAILURE;
2518 }
2519 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002520 return EXIT_FAILURE;
2521 }
2522
Jeff Haodcdc85b2015-12-04 14:06:18 -08002523 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002524 if (!dex2oat.HandleImage()) {
2525 return EXIT_FAILURE;
2526 }
2527
2528 // When given --host, finish early without stripping.
2529 if (dex2oat.IsHost()) {
2530 dex2oat.DumpTiming();
2531 return EXIT_SUCCESS;
2532 }
2533
Jeff Haodcdc85b2015-12-04 14:06:18 -08002534 // Copy stripped to unstripped location, if necessary.
2535 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002536 return EXIT_FAILURE;
2537 }
2538
Jeff Haodcdc85b2015-12-04 14:06:18 -08002539 // FlushClose again, as stripping might have re-opened the oat files.
2540 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002541 return EXIT_FAILURE;
2542 }
2543
2544 dex2oat.DumpTiming();
2545 return EXIT_SUCCESS;
2546}
2547
2548static int CompileApp(Dex2Oat& dex2oat) {
2549 dex2oat.Compile();
2550
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002551 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002552 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002553 return EXIT_FAILURE;
2554 }
2555
Jeff Haodcdc85b2015-12-04 14:06:18 -08002556 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002557 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002558
2559 // When given --host, finish early without stripping.
2560 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002561 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002562 return EXIT_FAILURE;
2563 }
2564
2565 dex2oat.DumpTiming();
2566 return EXIT_SUCCESS;
2567 }
2568
Jeff Haodcdc85b2015-12-04 14:06:18 -08002569 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2570 // stripped versions. If this is given, we expect to be able to open writable files by name.
2571 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002572 return EXIT_FAILURE;
2573 }
2574
Jeff Haodcdc85b2015-12-04 14:06:18 -08002575 // Flush and close the files.
2576 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002577 return EXIT_FAILURE;
2578 }
2579
2580 dex2oat.DumpTiming();
2581 return EXIT_SUCCESS;
2582}
2583
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002584static int dex2oat(int argc, char** argv) {
2585 b13564922();
2586
2587 TimingLogger timings("compiler", false, false);
2588
Roland Levillain5c7e2602016-02-23 18:08:53 +00002589 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2590 // might produce a stack frame too large for this function or for
2591 // functions inlining it (such as main), that would not fit the
2592 // requirements of the `-Wframe-larger-than` option.
2593 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002594
2595 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002596 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002597
Calin Juravle998c2162015-12-21 15:39:33 +02002598 // Process profile information and assess if we need to do a profile guided compilation.
2599 // This operation involves I/O.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002600 if (dex2oat->UseProfileGuidedCompilation()) {
2601 if (dex2oat->LoadProfile()) {
2602 if (!dex2oat->ShouldCompileBasedOnProfiles()) {
Calin Juravle998c2162015-12-21 15:39:33 +02002603 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2604 return EXIT_SUCCESS;
2605 }
2606 } else {
2607 LOG(WARNING) << "Failed to process profile files";
2608 return EXIT_FAILURE;
2609 }
2610 }
2611
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002612 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00002613 if (!dex2oat->OpenFile()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002614 return EXIT_FAILURE;
2615 }
2616
Andreas Gampe046c7062015-05-18 23:22:54 -07002617 // Print the complete line when any of the following is true:
2618 // 1) Debug build
2619 // 2) Compiling an image
2620 // 3) Compiling with --host
2621 // 4) Compiling on the host (not a target build)
2622 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002623 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002624 LOG(INFO) << CommandLine();
2625 } else {
2626 LOG(INFO) << StrippedCommandLine();
2627 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002628
Roland Levillain5c7e2602016-02-23 18:08:53 +00002629 if (!dex2oat->Setup()) {
2630 dex2oat->EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002631 return EXIT_FAILURE;
2632 }
2633
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002634 bool result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00002635 if (dex2oat->IsImage()) {
2636 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002637 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00002638 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002639 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002640
Roland Levillain5c7e2602016-02-23 18:08:53 +00002641 dex2oat->Shutdown();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002642 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002643}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002644} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002645
2646int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002647 int result = art::dex2oat(argc, argv);
2648 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2649 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2650 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002651 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002652 exit(result);
2653 }
2654 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002655}